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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
|
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { FileText, Users, Calendar, Send, Mail, Building } from "lucide-react"
import { toast } from "sonner"
import { PeriodicEvaluationView } from "@/db/schema"
import {
checkExistingSubmissions,
requestDocumentsFromVendors,
getReviewersForEvaluations,
createReviewerEvaluationsRequest
} from "../service"
import { DEPARTMENT_CODE_LABELS } from "@/types/evaluation"
// ================================================================
// 부서 코드 매핑
// ================================================================
const getDepartmentLabel = (code: string): string => {
return DEPARTMENT_CODE_LABELS[code as keyof typeof DEPARTMENT_CODE_LABELS] || code
}
// ================================================================
// 타입 정의
// ================================================================
interface ReviewerInfo {
id: number
name: string
email: string
deptName: string | null
departmentCode: string
evaluationTargetId: number
evaluationTargetReviewerId: number
}
interface EvaluationWithReviewers extends PeriodicEvaluationView {
reviewers: ReviewerInfo[]
}
// ================================================================
// 2. 협력업체 자료 요청 다이얼로그
// ================================================================
interface RequestDocumentsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
evaluations: PeriodicEvaluationView[]
onSuccess: () => void
}
interface EvaluationWithSubmissionStatus extends PeriodicEvaluationView {
hasExistingSubmission?: boolean
submissionDate?: Date | null
}
export function RequestDocumentsDialog({
open,
onOpenChange,
evaluations,
onSuccess,
}: RequestDocumentsDialogProps) {
console.log(evaluations)
const [isLoading, setIsLoading] = React.useState(false)
const [isCheckingStatus, setIsCheckingStatus] = React.useState(false)
const [message, setMessage] = React.useState("")
const [evaluationsWithStatus, setEvaluationsWithStatus] = React.useState<EvaluationWithSubmissionStatus[]>([])
// 제출대기 상태인 평가들만 필터링
const pendingEvaluations = React.useMemo(() =>
evaluations.filter(e => e.status === "PENDING_SUBMISSION" ||e.status === "PENDING" ),
[evaluations]
)
React.useEffect(() => {
if (!open) return;
// 대기 중 평가가 없으면 초기화
if (pendingEvaluations.length === 0) {
setEvaluationsWithStatus([]);
setIsCheckingStatus(false);
return;
}
// 상태 확인
(async () => {
setIsCheckingStatus(true);
try {
const ids = pendingEvaluations.map(e => e.id);
const existing = await checkExistingSubmissions(ids);
setEvaluationsWithStatus(
pendingEvaluations.map(e => ({
...e,
hasExistingSubmission: existing.some(s => s.periodicEvaluationId === e.id),
submissionDate: existing.find(s => s.periodicEvaluationId === e.id)?.createdAt ?? null,
})),
);
} catch (err) {
console.error(err);
setEvaluationsWithStatus(
pendingEvaluations.map(e => ({ ...e, hasExistingSubmission: false })),
);
} finally {
setIsCheckingStatus(false);
}
})();
}, [open, pendingEvaluations]); // 함수 대신 값에만 의존
// 새 요청과 재요청 분리
const newRequests = evaluationsWithStatus.filter(e => !e.hasExistingSubmission)
const reRequests = evaluationsWithStatus.filter(e => e.hasExistingSubmission)
const handleSubmit = async () => {
if (!message.trim()) {
toast.error("요청 메시지를 입력해주세요.")
return
}
setIsLoading(true)
try {
// 서버 액션 데이터 준비
const requestData = evaluationsWithStatus.map(evaluation => ({
periodicEvaluationId: evaluation.id,
companyId: evaluation.vendorId,
evaluationYear: evaluation.evaluationYear,
evaluationRound: evaluation.evaluationPeriod,
message: message.trim()
}))
// 서버 액션 호출
const result = await requestDocumentsFromVendors(requestData)
if (result.success) {
toast.success(result.message)
onSuccess()
onOpenChange(false)
setMessage("")
} else {
toast.error(result.message)
}
} catch (error) {
console.error('Error requesting documents:', error)
toast.error("자료 요청 발송 중 오류가 발생했습니다.")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<FileText className="size-4" />
협력업체 자료 요청
</DialogTitle>
<DialogDescription>
선택된 평가의 협력업체들에게 평가 자료 제출을 요청합니다.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{isCheckingStatus ? (
<div className="flex items-center justify-center py-8">
<div className="text-sm text-muted-foreground">요청 상태를 확인하고 있습니다...</div>
</div>
) : (
<>
{/* 신규 요청 대상 업체 */}
{newRequests.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm text-blue-600">
신규 요청 대상 ({newRequests.length}개 업체)
</CardTitle>
</CardHeader>
<CardContent className="space-y-2 max-h-32 overflow-y-auto">
{newRequests.map((evaluation) => (
<div
key={evaluation.id}
className="flex items-center justify-between text-sm p-2 bg-blue-50 rounded"
>
<span className="font-medium">{evaluation.vendorName}</span>
<div className="flex gap-2">
<Badge variant="outline">{evaluation.vendorCode}</Badge>
<Badge variant="default" className="bg-blue-600">신규</Badge>
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* 재요청 대상 업체 */}
{reRequests.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-sm text-orange-600">
재요청 대상 ({reRequests.length}개 업체)
</CardTitle>
</CardHeader>
<CardContent className="space-y-2 max-h-32 overflow-y-auto">
{reRequests.map((evaluation) => (
<div
key={evaluation.id}
className="flex items-center justify-between text-sm p-2 bg-orange-50 rounded"
>
<span className="font-medium">{evaluation.vendorName}</span>
<div className="flex gap-2">
<Badge variant="outline">{evaluation.vendorCode}</Badge>
<Badge variant="secondary" className="bg-orange-100">
재요청
</Badge>
{evaluation.submissionDate && (
<span className="text-xs text-muted-foreground">
{new Intl.DateTimeFormat("ko-KR", {
month: "2-digit",
day: "2-digit",
}).format(new Date(evaluation.submissionDate))}
</span>
)}
</div>
</div>
))}
</CardContent>
</Card>
)}
{/* 요청 대상이 없는 경우 */}
{!isCheckingStatus && evaluationsWithStatus.length === 0 && (
<Card>
<CardContent className="pt-6">
<div className="text-center text-sm text-muted-foreground">
요청할 수 있는 평가가 없습니다.
</div>
</CardContent>
</Card>
)}
</>
)}
{/* 요청 메시지 */}
<div className="space-y-2">
<Label htmlFor="message">요청 메시지</Label>
<Textarea
id="message"
placeholder="협력업체에게 전달할 메시지를 입력하세요..."
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
disabled={isCheckingStatus}
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading || isCheckingStatus}
>
취소
</Button>
<Button
onClick={handleSubmit}
disabled={isLoading || isCheckingStatus || evaluationsWithStatus.length === 0}
>
<Send className="size-4 mr-2" />
{isLoading ? "발송 중..." :
`요청 발송 (신규 ${newRequests.length}개${reRequests.length > 0 ? `, 재요청 ${reRequests.length}개` : ''})`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
// ================================================================
// 3. 평가자 평가 요청 다이얼로그 (업데이트됨)
// ================================================================
interface RequestEvaluationDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
evaluations: PeriodicEvaluationView[]
onSuccess: () => void
}
export function RequestEvaluationDialog({
open,
onOpenChange,
evaluations,
onSuccess,
}: RequestEvaluationDialogProps) {
const [isLoading, setIsLoading] = React.useState(false)
const [isLoadingReviewers, setIsLoadingReviewers] = React.useState(false)
const [message, setMessage] = React.useState("")
const [evaluationsWithReviewers, setEvaluationsWithReviewers] = React.useState<EvaluationWithReviewers[]>([])
// 제출완료 상태인 평가들만 필터링
const submittedEvaluations = evaluations.filter(e =>
e.status === "SUBMITTED" || e.status === "PENDING_SUBMISSION"
)
// 리뷰어 정보 로딩
React.useEffect(() => {
if (!open || submittedEvaluations.length === 0) {
setEvaluationsWithReviewers([])
return
}
const loadReviewers = async () => {
setIsLoadingReviewers(true)
try {
const evaluationTargetIds = submittedEvaluations
.map(e => e.evaluationTargetId)
.filter(id => id !== null)
if (evaluationTargetIds.length === 0) {
setEvaluationsWithReviewers([])
return
}
const reviewersData = await getReviewersForEvaluations(evaluationTargetIds)
// 평가별로 리뷰어 그룹핑
const evaluationsWithReviewersData = submittedEvaluations.map(evaluation => ({
...evaluation,
reviewers: reviewersData.filter(reviewer =>
reviewer.evaluationTargetId === evaluation.evaluationTargetId
)
}))
setEvaluationsWithReviewers(evaluationsWithReviewersData)
} catch (error) {
console.error('Error loading reviewers:', error)
toast.error("평가자 정보를 불러오는데 실패했습니다.")
setEvaluationsWithReviewers([])
} finally {
setIsLoadingReviewers(false)
}
}
loadReviewers()
}, [open, submittedEvaluations.length])
// 총 리뷰어 수 계산
const totalReviewers = evaluationsWithReviewers.reduce((sum, evaluation) =>
sum + evaluation.reviewers.length, 0
)
const handleSubmit = async () => {
if (!message.trim()) {
toast.error("요청 메시지를 입력해주세요.")
return
}
if (evaluationsWithReviewers.length === 0) {
toast.error("평가 요청할 대상이 없습니다.")
return
}
setIsLoading(true)
try {
// 리뷰어 평가 레코드 생성 데이터 준비
const reviewerEvaluationsData = evaluationsWithReviewers.flatMap(evaluation =>
evaluation.reviewers.map(reviewer => ({
periodicEvaluationId: evaluation.id,
evaluationTargetId: evaluation.evaluationTargetId, // 추가됨
evaluationTargetReviewerId: reviewer.evaluationTargetReviewerId,
message: message.trim()
}))
)
// 서버 액션 호출
const result = await createReviewerEvaluationsRequest(reviewerEvaluationsData)
if (result.success) {
toast.success(result.message)
onSuccess()
onOpenChange(false)
setMessage("")
} else {
toast.error(result.message)
}
} catch (error) {
console.error('Error requesting evaluation:', error)
toast.error("평가 요청 발송 중 오류가 발생했습니다.")
} finally {
setIsLoading(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-4xl max-h-[80vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Users className="size-4" />
평가자 평가 요청
</DialogTitle>
<DialogDescription>
선택된 평가들에 대해 평가자들에게 평가를 요청합니다.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{isLoadingReviewers ? (
<div className="flex items-center justify-center py-8">
<div className="text-sm text-muted-foreground">평가자 정보를 불러오고 있습니다...</div>
</div>
) : (
<>
{/* 평가별 리뷰어 목록 */}
{evaluationsWithReviewers.length > 0 ? (
<div className="space-y-4">
<div className="text-sm font-medium text-green-600">
총 {evaluationsWithReviewers.length}개 평가, {totalReviewers}명의 평가자
</div>
{evaluationsWithReviewers.map((evaluation) => (
<Card key={evaluation.id}>
<CardHeader className="pb-3">
<CardTitle className="text-sm flex items-center justify-between">
<span>{evaluation.vendorName}</span>
<div className="flex gap-2">
<Badge variant="outline">{evaluation.vendorCode}</Badge>
<Badge variant={evaluation.submissionDate ? "default" : "secondary"}>
{evaluation.submissionDate ? "자료 제출완료" : "자료 미제출"}
</Badge>
</div>
</CardTitle>
</CardHeader>
<CardContent>
{evaluation.reviewers.length > 0 ? (
<div className="space-y-2">
<div className="text-xs text-muted-foreground mb-2">
평가자 {evaluation.reviewers.length}명
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-2">
{evaluation.reviewers.map((reviewer) => (
<div
key={reviewer.evaluationTargetReviewerId}
className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg"
>
<div className="flex-1">
<div className="font-medium text-sm">{reviewer.name}</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Mail className="size-3" />
{reviewer.email}
</div>
{reviewer.deptName && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Building className="size-3" />
{reviewer.deptName}
</div>
)}
</div>
<Badge variant="outline" className="text-xs">
{getDepartmentLabel(reviewer.departmentCode)}
</Badge>
</div>
))}
</div>
</div>
) : (
<div className="text-sm text-muted-foreground text-center py-4">
지정된 평가자가 없습니다.
</div>
)}
</CardContent>
</Card>
))}
</div>
) : (
<Card>
<CardContent className="pt-6">
<div className="text-center text-sm text-muted-foreground">
평가 요청할 대상이 없습니다.
</div>
</CardContent>
</Card>
)}
</>
)}
{/* 요청 메시지 */}
<div className="space-y-2">
<Label htmlFor="evaluation-message">요청 메시지</Label>
<Textarea
id="evaluation-message"
placeholder="평가자들에게 전달할 메시지를 입력하세요..."
value={message}
onChange={(e) => setMessage(e.target.value)}
rows={4}
disabled={isLoadingReviewers}
/>
</div>
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading || isLoadingReviewers}
>
취소
</Button>
<Button
onClick={handleSubmit}
disabled={isLoading || isLoadingReviewers || totalReviewers === 0}
>
<Send className="size-4 mr-2" />
{isLoading ? "발송 중..." : `${totalReviewers}명에게 평가 요청`}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
|