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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
|
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"
import { CheckCircle, AlertCircle, Paperclip, Square } from "lucide-react"
import { PQGroupData } from "@/lib/pq/service"
import { approvePQAction, rejectPQAction, updateSHICommentAction } from "@/lib/pq/service"
// import * as ExcelJS from 'exceljs';
// import { saveAs } from "file-saver";
// PQ 제출 정보 타입
interface PQSubmission {
id: number
vendorId: number
vendorName: string | null
vendorCode: string | null
type: string
status: string
projectId: number | null
projectName: string | null
projectCode: string | null
submittedAt: Date | null
approvedAt: Date | null
rejectedAt: Date | null
rejectReason: string | null
}
interface PQReviewWrapperProps {
pqData: PQGroupData[]
vendorId: number
pqSubmission: PQSubmission
vendorInfo?: any // 협력업체 정보 (선택사항)
}
export function PQReviewWrapper({
pqData,
vendorId,
pqSubmission,
vendorInfo
}: PQReviewWrapperProps) {
const router = useRouter()
const { toast } = useToast()
const [isApproving, setIsApproving] = React.useState(false)
const [isRejecting, setIsRejecting] = React.useState(false)
const [showApproveDialog, setShowApproveDialog] = React.useState(false)
const [showRejectDialog, setShowRejectDialog] = React.useState(false)
const [rejectReason, setRejectReason] = React.useState("")
const [shiComments, setShiComments] = React.useState<Record<number, string>>({})
const [isUpdatingComment, setIsUpdatingComment] = React.useState<number | null>(null)
// 코드 순서로 정렬하는 함수 (1-1-1, 1-1-2, 1-2-1 순서)
const sortByCode = (items: any[]) => {
return [...items].sort((a, b) => {
const parseCode = (code: string) => {
return code.split('-').map(part => parseInt(part, 10))
}
const aCode = parseCode(a.code)
const bCode = parseCode(b.code)
for (let i = 0; i < Math.max(aCode.length, bCode.length); i++) {
const aPart = aCode[i] || 0
const bPart = bCode[i] || 0
if (aPart !== bPart) {
return aPart - bPart
}
}
return 0
})
}
// 기존 SHI 코멘트를 로컬 상태에 초기화
React.useEffect(() => {
const initialComments: Record<number, string> = {}
pqData.forEach(group => {
group.items.forEach(item => {
if (item.answerId && item.shiComment) {
initialComments[item.answerId] = item.shiComment
}
})
})
setShiComments(initialComments)
}, [pqData])
// PQ 승인 처리
const handleApprove = async () => {
try {
setIsApproving(true)
const result = await approvePQAction({
pqSubmissionId: pqSubmission.id,
vendorId: vendorId
})
if (result.ok) {
toast({
title: "PQ 승인 완료",
description: "PQ가 성공적으로 승인되었습니다.",
})
// 페이지 새로고침
router.refresh()
} else {
toast({
title: "승인 실패",
description: result.error || "PQ 승인 중 오류가 발생했습니다.",
variant: "destructive"
})
}
} catch (error) {
console.error("PQ 승인 오류:", error)
toast({
title: "승인 실패",
description: "PQ 승인 중 오류가 발생했습니다.",
variant: "destructive"
})
} finally {
setIsApproving(false)
setShowApproveDialog(false)
}
}
// SHI 코멘트 업데이트 처리
const handleSHICommentUpdate = async (answerId: number) => {
const comment = shiComments[answerId] || ""
try {
setIsUpdatingComment(answerId)
const result = await updateSHICommentAction({
answerId,
shiComment: comment,
})
if (result.ok) {
toast({
title: "SHI 코멘트 저장 완료",
description: "SHI 코멘트가 저장되었습니다.",
})
// 페이지 새로고침
router.refresh()
} else {
toast({
title: "저장 실패",
description: result.error || "SHI 코멘트 저장 중 오류가 발생했습니다.",
variant: "destructive"
})
}
} catch (error) {
console.error("SHI 코멘트 저장 오류:", error)
toast({
title: "저장 실패",
description: "SHI 코멘트 저장 중 오류가 발생했습니다.",
variant: "destructive"
})
} finally {
setIsUpdatingComment(null)
}
}
// // Excel export 처리
// const handleExportToExcel = async () => {
// try {
// setIsExporting(true)
// // 워크북 생성
// const workbook = new ExcelJS.Workbook()
// workbook.creator = 'PQ Management System'
// workbook.created = new Date()
// // 메인 시트 생성
// const worksheet = workbook.addWorksheet("PQ 항목")
// // 헤더 정의
// const headers = [
// "그룹명",
// "코드",
// "체크포인트",
// "설명",
// "입력형식",
// "필수여부",
// "벤더답변",
// "SHI 코멘트",
// "벤더 답변",
// ]
// // 헤더 추가
// worksheet.addRow(headers)
// // 헤더 스타일 적용
// const headerRow = worksheet.getRow(1)
// headerRow.font = { bold: true }
// headerRow.fill = {
// type: 'pattern',
// pattern: 'solid',
// fgColor: { argb: 'FFE0E0E0' }
// }
// headerRow.alignment = { vertical: 'middle', horizontal: 'center' }
// // 컬럼 너비 설정
// worksheet.columns = [
// { header: "그룹명", key: "groupName", width: 15 },
// { header: "코드", key: "code", width: 12 },
// { header: "체크포인트", key: "checkPoint", width: 30 },
// { header: "설명", key: "description", width: 40 },
// { header: "입력형식", key: "inputFormat", width: 12 },
// { header: "벤더답변", key: "answer", width: 30 },
// { header: "SHI 코멘트", key: "shiComment", width: 30 },
// { header: "벤더 답변", key: "vendorReply", width: 30 },
// ]
// // 데이터 추가
// pqData.forEach(group => {
// group.items.forEach(item => {
// const rowData = [
// group.groupName,
// item.code,
// item.checkPoint,
// item.description || "",
// item.inputFormat || "",
// item.answer || "",
// item.shiComment || "",
// item.vendorReply || "",
// ]
// worksheet.addRow(rowData)
// })
// })
// // 전체 셀에 테두리 추가
// worksheet.eachRow((row, rowNumber) => {
// row.eachCell((cell) => {
// cell.border = {
// top: { style: 'thin' },
// left: { style: 'thin' },
// bottom: { style: 'thin' },
// right: { style: 'thin' }
// }
// // 긴 텍스트는 자동 줄바꿈
// cell.alignment = {
// vertical: 'top',
// horizontal: 'left',
// wrapText: true
// }
// })
// })
// // 정보 시트 생성
// const infoSheet = workbook.addWorksheet("정보")
// infoSheet.addRow(["벤더명", pqSubmission.vendorName])
// if (pqSubmission.projectName) {
// infoSheet.addRow(["프로젝트명", pqSubmission.projectName])
// }
// infoSheet.addRow(["생성일", new Date().toLocaleDateString('ko-KR')])
// infoSheet.addRow(["총 항목 수", pqData.reduce((total, group) => total + group.items.length, 0)])
// // 정보 시트 스타일링
// infoSheet.columns = [
// { header: "항목", key: "item", width: 20 },
// { header: "값", key: "value", width: 40 }
// ]
// const infoHeaderRow = infoSheet.getRow(1)
// infoHeaderRow.font = { bold: true }
// infoHeaderRow.fill = {
// type: 'pattern',
// pattern: 'solid',
// fgColor: { argb: 'FFE6F3FF' }
// }
// // 파일명 생성
// const defaultFilename = pqSubmission.projectName
// ? `${pqSubmission.vendorName}_${pqSubmission.projectName}_PQ_${new Date().toISOString().slice(0, 10)}`
// : `${pqSubmission.vendorName}_PQ_${new Date().toISOString().slice(0, 10)}`
// const finalFilename = defaultFilename
// // 파일 다운로드
// const buffer = await workbook.xlsx.writeBuffer()
// const blob = new Blob([buffer], {
// type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
// })
// saveAs(blob, `${finalFilename}.xlsx`)
// } catch (error) {
// console.error("Excel export 오류:", error)
// toast({
// title: "내보내기 실패",
// description: "Excel 내보내기 중 오류가 발생했습니다.",
// variant: "destructive"
// })
// } finally {
// setIsExporting(false)
// }
// }
// PQ 거부 처리
const handleReject = async () => {
if (!rejectReason.trim()) {
toast({
title: "거부 사유 필요",
description: "거부 사유를 입력해주세요.",
variant: "destructive"
})
return
}
try {
setIsRejecting(true)
const result = await rejectPQAction({
pqSubmissionId: pqSubmission.id,
vendorId: vendorId,
rejectReason: rejectReason
})
if (result.ok) {
toast({
title: "PQ 거부 완료",
description: "PQ가 거부되었습니다.",
})
// 페이지 새로고침
router.refresh()
} else {
toast({
title: "거부 실패",
description: result.error || "PQ 거부 중 오류가 발생했습니다.",
variant: "destructive"
})
}
} catch (error) {
console.error("PQ 거부 오류:", error)
toast({
title: "거부 실패",
description: "PQ 거부 중 오류가 발생했습니다.",
variant: "destructive"
})
} finally {
setIsRejecting(false)
setShowRejectDialog(false)
}
}
return (
<div className="space-y-6">
{/* 그룹별 PQ 항목 표시 */}
{pqData.map((group) => (
<div key={group.groupName} className="space-y-4">
<h3 className="text-lg font-medium">{group.groupName}</h3>
<div className="grid grid-cols-2 gap-4">
{sortByCode(group.items).map((item) => (
<Card key={item.criteriaId}>
<CardHeader>
<div className="flex justify-between items-start">
<div className="flex-1">
<div className="flex items-start gap-3">
<div className="flex-1">
<CardTitle className="text-base">
{item.code} - {item.checkPoint}
</CardTitle>
{item.description && (
<CardDescription className="mt-1 whitespace-pre-wrap">
{item.description}
</CardDescription>
)}
{item.remarks && (
<div className="mt-2 p-2 rounded-md">
<p className="text-sm font-medium text-muted-foreground mb-1">Remark:</p>
<p className="text-sm whitespace-pre-wrap">
{item.remarks}
</p>
</div>
)}
</div>
</div>
</div>
{/* 항목 상태 표시 */}
{!!item.answer || item.attachments.length > 0 ? (
<Badge variant="outline" className="text-green-600 bg-green-50">
<CheckCircle className="h-3 w-3 mr-1" />
답변 있음
</Badge>
) : (
<Badge variant="outline" className="text-amber-600 bg-amber-50">
<AlertCircle className="h-3 w-3 mr-1" />
답변 없음
</Badge>
)}
</div>
</CardHeader>
<CardContent className="space-y-4">
{/* 프로젝트별 추가 정보 */}
{pqSubmission.projectId && item.contractInfo && (
<div className="space-y-1">
<p className="text-sm font-medium">계약 정보</p>
<div className="rounded-md bg-muted/30 p-3 text-sm whitespace-pre-wrap">
{item.contractInfo}
</div>
</div>
)}
{pqSubmission.projectId && item.additionalRequirement && (
<div className="space-y-1">
<p className="text-sm font-medium">추가 요구사항</p>
<div className="rounded-md bg-muted/30 p-3 text-sm whitespace-pre-wrap">
{item.additionalRequirement}
</div>
</div>
)}
{/* 벤더 답변 - 입력 형식에 따라 다르게 표시 */}
<div className="space-y-1">
<p className="text-sm font-medium flex items-center gap-1">
벤더 답변
{item.inputFormat && (
<Badge variant="outline" className="ml-2 text-xs">
{item.inputFormat === "TEXT" && "텍스트"}
{item.inputFormat === "EMAIL" && "이메일"}
{item.inputFormat === "PHONE" && "전화번호"}
{item.inputFormat === "FAX" && "팩스번호"}
{item.inputFormat === "NUMBER" && "숫자"}
{item.inputFormat === "NUMBER_WITH_UNIT" && "숫자+단위"}
{item.inputFormat === "FILE" && "파일"}
{item.inputFormat === "TEXT_FILE" && "텍스트+파일"}
</Badge>
)}
</p>
<div className="rounded-md border p-3 min-h-20">
{(() => {
const inputFormat = item.inputFormat || "TEXT";
switch (inputFormat) {
case "EMAIL":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">이메일 주소:</div>
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">답변 없음</span>}
</div>
</div>
);
case "PHONE":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">전화번호:</div>
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">답변 없음</span>}
</div>
</div>
);
case "FAX":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">팩스번호:</div>
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">답변 없음</span>}
</div>
</div>
);
case "NUMBER":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">숫자 값:</div>
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">답변 없음</span>}
</div>
</div>
);
case "NUMBER_WITH_UNIT":
const numberWithUnit = item.answer || "";
const [number, unit] = numberWithUnit.split(' ');
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">숫자+단위:</div>
<div className="flex items-center gap-2">
{number && (
<span className="font-mono text-lg font-semibold text-blue-600">
{number}
</span>
)}
{unit && (
<Badge variant="outline" className="text-xs">
{unit}
</Badge>
)}
{!numberWithUnit && (
<span className="text-muted-foreground">답변 없음</span>
)}
</div>
</div>
);
case "FILE":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">파일 업로드 항목:</div>
<div className="text-sm text-muted-foreground">
{item.attachments.length > 0 ? "파일이 업로드되었습니다." : "파일이 업로드되지 않았습니다."}
</div>
</div>
);
case "TEXT_FILE":
return (
<div className="space-y-2">
<div className="text-sm font-medium text-muted-foreground">텍스트 답변:</div>
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">텍스트 답변 없음</span>}
</div>
<div className="text-sm font-medium text-muted-foreground">파일 업로드:</div>
<div className="text-sm text-muted-foreground">
{item.attachments.length > 0 ? "파일이 업로드되었습니다." : "파일이 업로드되지 않았습니다."}
</div>
</div>
);
default: // TEXT
return (
<div className="whitespace-pre-wrap">
{item.answer || <span className="text-muted-foreground">답변 없음</span>}
</div>
);
}
})()}
</div>
</div>
{/* SHI 코멘트 필드 (편집 가능) */}
<div className="space-y-1">
<p className="text-sm font-medium flex items-center gap-1">
SHI 코멘트
</p>
<div className="rounded-md border p-3 min-h-20">
<Textarea
value={shiComments[item.answerId || 0] ?? item.shiComment ?? ""}
onChange={(e) => {
if (item.answerId) {
setShiComments(prev => ({
...prev,
[item.answerId!]: e.target.value
}))
}
}}
placeholder="SHI 코멘트를 입력하세요."
className="min-h-20"
/>
{item.answerId && (
<div className="mt-2 flex justify-end">
<Button
size="sm"
onClick={() => handleSHICommentUpdate(item.answerId!)}
disabled={isUpdatingComment === item.answerId}
>
{isUpdatingComment === item.answerId ? "저장 중..." : "저장"}
</Button>
</div>
)}
</div>
</div>
{/* 벤더 답변 필드 (읽기 전용) */}
<div className="space-y-1">
<p className="text-sm font-medium flex items-center gap-1">
벤더 reply
</p>
<div className="rounded-md border p-3 min-h-20 bg-muted/30">
<div className="whitespace-pre-wrap">
{item.vendorReply || <span className="text-muted-foreground">벤더 reply 없음</span>}
</div>
</div>
</div>
{/* 첨부 파일 - FILE 또는 TEXT_FILE 형식에서만 표시 */}
{(item.inputFormat === "FILE" || item.inputFormat === "TEXT_FILE") && item.attachments.length > 0 && (
<div className="space-y-1">
<p className="text-sm font-medium flex items-center gap-1">
<Paperclip className="h-4 w-4" />
첨부 파일 ({item.attachments.length})
</p>
<div className="rounded-md border p-3">
<ul className="space-y-1">
{item.attachments.map((attachment, idx) => (
<li key={idx} className="flex items-center gap-2">
<button
onClick={async () => {
try {
const { downloadFile } = await import('@/lib/file-download')
await downloadFile(attachment.filePath, attachment.fileName, {
showToast: true,
onError: (error) => {
console.error('다운로드 오류:', error)
toast({
title: "다운로드 실패",
description: error,
variant: "destructive"
})
},
onSuccess: (fileName, fileSize) => {
console.log(`다운로드 성공: ${fileName} (${fileSize} bytes)`)
}
})
} catch (error) {
console.error('다운로드 오류:', error)
toast({
title: "다운로드 실패",
description: "파일 다운로드 중 오류가 발생했습니다.",
variant: "destructive"
})
}
}}
className="text-sm text-blue-600 hover:underline cursor-pointer"
>
{attachment.fileName}
</button>
</li>
))}
</ul>
</div>
</div>
)}
</CardContent>
</Card>
))}
</div>
</div>
))}
{/* 검토 버튼 */}
<div className="fixed bottom-4 right-4 bg-background p-4 rounded-lg shadow-md border">
<div className="flex gap-2">
{/* <Button
variant="outline"
onClick={handleExportToExcel}
disabled={isExporting}
>
<Download className="h-4 w-4 mr-2" />
{isExporting ? "내보내기 중..." : "Excel 내보내기"}
</Button> */}
<Button
variant="outline"
onClick={() => setShowRejectDialog(true)}
disabled={isRejecting}
>
{isRejecting ? "거부 중..." : "거부"}
</Button>
<Button
variant="default"
onClick={() => setShowApproveDialog(true)}
disabled={isApproving}
>
{isApproving ? "승인 중..." : "승인"}
</Button>
</div>
</div>
{/* 승인 확인 다이얼로그 */}
<Dialog open={showApproveDialog} onOpenChange={setShowApproveDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>PQ 승인 확인</DialogTitle>
<DialogDescription>
{pqSubmission.vendorName || "알 수 없는 업체"}의 {
pqSubmission.type === "GENERAL" ? "일반" :
pqSubmission.type === "PROJECT" ? "프로젝트" :
pqSubmission.type === "NON_INSPECTION" ? "미실사" : "일반"
} PQ를 승인하시겠습니까?
{pqSubmission.projectId && (
<span> 프로젝트: {pqSubmission.projectName}</span>
)}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => setShowApproveDialog(false)}>
취소
</Button>
<Button onClick={handleApprove} disabled={isApproving}>
{isApproving ? "승인 중..." : "승인"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* 거부 확인 다이얼로그 */}
<Dialog open={showRejectDialog} onOpenChange={setShowRejectDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>PQ 거부</DialogTitle>
<DialogDescription>
{pqSubmission.vendorName || "알 수 없는 업체"}의 {
pqSubmission.type === "GENERAL" ? "일반" :
pqSubmission.type === "PROJECT" ? "프로젝트" :
pqSubmission.type === "NON_INSPECTION" ? "미실사" : "일반"
} PQ를 거부하는 이유를 입력해주세요.
{pqSubmission.projectId && (
<span> 프로젝트: {pqSubmission.projectName}</span>
)}
</DialogDescription>
</DialogHeader>
<Textarea
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
placeholder="거부 사유를 입력하세요"
className="min-h-24"
/>
<DialogFooter>
<Button variant="outline" onClick={() => setShowRejectDialog(false)}>
취소
</Button>
<Button
variant="destructive"
onClick={handleReject}
disabled={isRejecting || !rejectReason.trim()}
>
{isRejecting ? "거부 중..." : "거부"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
|