summaryrefslogtreecommitdiff
path: root/lib/evaluation-target-list/table/evaluation-target-action-dialogs.tsx
blob: 47af419daf4cff9564df475de98f14acfe04e182 (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
// evaluation-target-action-dialogs.tsx
"use client"

import * as React from "react"
import { Loader2, AlertTriangle, Check, X, MessageSquare } from "lucide-react"
import { toast } from "sonner"

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"

import { 
  confirmEvaluationTargets, 
  excludeEvaluationTargets, 
  requestEvaluationReview 
} from "../service"
import { EvaluationTargetWithDepartments } from "@/db/schema"

// ----------------------------------------------------------------
// 확정 컨펌 다이얼로그
// ----------------------------------------------------------------
interface ConfirmTargetsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  targets: EvaluationTargetWithDepartments[]
  onSuccess?: () => void
}

export function ConfirmTargetsDialog({
  open,
  onOpenChange,
  targets,
  onSuccess
}: ConfirmTargetsDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)

  // 확정 가능한 대상들 (consensusStatus가 true인 것들)
  const confirmableTargets = targets.filter(
    t => t.status === "PENDING" && t.consensusStatus === true
  )

  const handleConfirm = async () => {
    if (confirmableTargets.length === 0) return

    setIsLoading(true)
    try {
      const targetIds = confirmableTargets.map(t => t.id)
      const result = await confirmEvaluationTargets(targetIds)

      if (result.success) {
        toast.success(result.message)
        onSuccess?.()
        onOpenChange(false)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error("확정 처리 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center gap-2">
            <Check className="h-5 w-5 text-green-600" />
            평가 대상 확정
          </AlertDialogTitle>
          <AlertDialogDescription asChild>
            <div className="space-y-3">
              <p>
                선택된 {targets.length}개 항목 중{" "}
                <span className="font-semibold text-green-600">
                  {confirmableTargets.length}개 항목
                </span>
                을 확정하시겠습니까?
              </p>
              
              {confirmableTargets.length !== targets.length && (
                <div className="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                  <p className="text-sm text-yellow-800">
                    <AlertTriangle className="h-4 w-4 inline mr-1" />
                    의견 일치 상태인 대기중 항목만 확정 가능합니다.
                    ({targets.length - confirmableTargets.length}개 항목 제외됨)
                  </p>
                </div>
              )}

              {confirmableTargets.length > 0 && (
                <div className="max-h-32 overflow-y-auto">
                  <div className="text-sm space-y-1">
                    {confirmableTargets.slice(0, 5).map(target => (
                      <div key={target.id} className="flex items-center gap-2">
                        <Badge variant="outline" className="text-xs">
                          {target.vendorCode}
                        </Badge>
                        <span className="text-xs">{target.vendorName}</span>
                      </div>
                    ))}
                    {confirmableTargets.length > 5 && (
                      <p className="text-xs text-muted-foreground">
                        ...외 {confirmableTargets.length - 5}개
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isLoading}>취소</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleConfirm}
            disabled={isLoading || confirmableTargets.length === 0}
            className="bg-green-600 hover:bg-green-700"
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            확정 ({confirmableTargets.length})
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

// ----------------------------------------------------------------
// 제외 컨펌 다이얼로그
// ----------------------------------------------------------------
interface ExcludeTargetsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  targets: EvaluationTargetWithDepartments[]
  onSuccess?: () => void
}

export function ExcludeTargetsDialog({
  open,
  onOpenChange,
  targets,
  onSuccess
}: ExcludeTargetsDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)

  // 제외 가능한 대상들 (PENDING 상태인 것들)
  const excludableTargets = targets.filter(t => t.status === "PENDING")

  const handleExclude = async () => {
    if (excludableTargets.length === 0) return

    setIsLoading(true)
    try {
      const targetIds = excludableTargets.map(t => t.id)
      const result = await excludeEvaluationTargets(targetIds)

      if (result.success) {
        toast.success(result.message)
        onSuccess?.()
        onOpenChange(false)
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error("제외 처리 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle className="flex items-center gap-2">
            <X className="h-5 w-5 text-red-600" />
            평가 대상 제외
          </AlertDialogTitle>
          <AlertDialogDescription asChild>
            <div className="space-y-3">
              <p>
                선택된 {targets.length}개 항목 중{" "}
                <span className="font-semibold text-red-600">
                  {excludableTargets.length}개 항목
                </span>
                을 제외하시겠습니까?
              </p>

              {excludableTargets.length !== targets.length && (
                <div className="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                  <p className="text-sm text-yellow-800">
                    <AlertTriangle className="h-4 w-4 inline mr-1" />
                    대기중 상태인 항목만 제외 가능합니다.
                    ({targets.length - excludableTargets.length}개 항목 제외됨)
                  </p>
                </div>
              )}

              {excludableTargets.length > 0 && (
                <div className="max-h-32 overflow-y-auto">
                  <div className="text-sm space-y-1">
                    {excludableTargets.slice(0, 5).map(target => (
                      <div key={target.id} className="flex items-center gap-2">
                        <Badge variant="outline" className="text-xs">
                          {target.vendorCode}
                        </Badge>
                        <span className="text-xs">{target.vendorName}</span>
                      </div>
                    ))}
                    {excludableTargets.length > 5 && (
                      <p className="text-xs text-muted-foreground">
                        ...외 {excludableTargets.length - 5}개
                      </p>
                    )}
                  </div>
                </div>
              )}
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isLoading}>취소</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleExclude}
            disabled={isLoading || excludableTargets.length === 0}
            className="bg-red-600 hover:bg-red-700"
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            제외 ({excludableTargets.length})
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

// ----------------------------------------------------------------
// 의견 요청 다이얼로그
// ----------------------------------------------------------------
interface RequestReviewDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  targets: EvaluationTargetWithDepartments[]
  onSuccess?: () => void
}

export function RequestReviewDialog({
  open,
  onOpenChange,
  targets,
  onSuccess
}: RequestReviewDialogProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [message, setMessage] = React.useState("")

  // 의견 요청 가능한 대상들 (PENDING 상태인 것들)
  const reviewableTargets = targets.filter(t => t.status === "PENDING")

  // 담당자 이메일들 수집
  const reviewerEmails = React.useMemo(() => {
    const emails = new Set<string>()
    reviewableTargets.forEach(target => {
      if (target.orderReviewerEmail) emails.add(target.orderReviewerEmail)
      if (target.procurementReviewerEmail) emails.add(target.procurementReviewerEmail)
      if (target.qualityReviewerEmail) emails.add(target.qualityReviewerEmail)
      if (target.designReviewerEmail) emails.add(target.designReviewerEmail)
      if (target.csReviewerEmail) emails.add(target.csReviewerEmail)
    })
    return Array.from(emails)
  }, [reviewableTargets])

  const handleRequestReview = async () => {
    if (reviewableTargets.length === 0) return

    setIsLoading(true)
    try {
      const targetIds = reviewableTargets.map(t => t.id)
      const result = await requestEvaluationReview(targetIds, message)

      if (result.success) {
        toast.success(result.message)
        onSuccess?.()
        onOpenChange(false)
        setMessage("")
      } else {
        toast.error(result.error)
      }
    } catch (error) {
      toast.error("의견 요청 중 오류가 발생했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <MessageSquare className="h-5 w-5 text-blue-600" />
            평가 의견 요청
          </DialogTitle>
          <DialogDescription>
            선택된 평가 대상에 대한 의견을 담당자들에게 요청합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 요약 정보 */}
          <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
            <div className="text-sm space-y-1">
              <p>
                <span className="font-medium">요청 대상:</span> {reviewableTargets.length}개 평가 항목
              </p>
              <p>
                <span className="font-medium">받는 사람:</span> {reviewerEmails.length}명의 담당자
              </p>
            </div>
          </div>

          {/* 메시지 입력 */}
          <div className="space-y-2">
            <Label htmlFor="review-message">추가 메시지 (선택사항)</Label>
            <Textarea
              id="review-message"
              placeholder="담당자들에게 전달할 추가 메시지를 입력하세요..."
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              rows={3}
            />
          </div>

          {reviewableTargets.length !== targets.length && (
            <div className="p-3 bg-yellow-50 rounded-lg border border-yellow-200">
              <p className="text-sm text-yellow-800">
                <AlertTriangle className="h-4 w-4 inline mr-1" />
                대기중 상태인 항목만 의견 요청 가능합니다.
                ({targets.length - reviewableTargets.length}개 항목 제외됨)
              </p>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isLoading}
          >
            취소
          </Button>
          <Button
            onClick={handleRequestReview}
            disabled={isLoading || reviewableTargets.length === 0}
          >
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            의견 요청 발송
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}