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
|
// simple-basic-contracts-detail-columns.tsx
"use client"
import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { formatDateTime } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { Button } from "@/components/ui/button"
import {
MoreHorizontal,
Download,
Eye,
Mail,
FileText,
Clock,
MessageCircle,
Loader2
} from "lucide-react"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { BasicContractView } from "@/db/schema"
import { downloadFile, quickPreview } from "@/lib/file-download"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { getComplianceResponseByBasicContractId } from "@/lib/compliance/services"
type RedFlagResolutionState = {
resolved: boolean
resolvedAt: Date | null
pendingApprovalId: string | null
}
export interface GetColumnsProps {
setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<BasicContractView> | null>>
gtcData: Record<number, { gtcDocumentId: number | null; hasComments: boolean }>
isLoadingGtcData: boolean
agreementCommentData: Record<number, { hasComments: boolean; commentCount: number }>
isLoadingAgreementCommentData: boolean
redFlagData: Record<number, boolean>
isLoadingRedFlagData: boolean
redFlagResolutionData: Record<number, RedFlagResolutionState>
isLoadingRedFlagResolutionData: boolean
isComplianceTemplate: boolean
router: NextRouter;
}
type NextRouter = ReturnType<typeof useRouter>;
const CONTRACT_STATUS_CONFIG = {
PENDING: { label: "발송완료", color: "gray" },
VENDOR_SIGNED: { label: "협력업체 서명완료", color: "blue" },
BUYER_SIGNED: { label: "구매팀 서명완료", color: "green" },
LEGAL_REVIEW_REQUESTED: { label: "법무검토 요청", color: "purple" },
LEGAL_REVIEW_COMPLETED: { label: "법무검토 완료", color: "indigo" },
COMPLETED: { label: "계약완료", color: "emerald" },
REJECTED: { label: "거절됨", color: "red" },
} as const
export function getDetailColumns({
setRowAction,
gtcData,
isLoadingGtcData,
agreementCommentData,
isLoadingAgreementCommentData,
redFlagData,
isLoadingRedFlagData,
redFlagResolutionData,
isLoadingRedFlagResolutionData,
isComplianceTemplate,
router
}: GetColumnsProps): ColumnDef<BasicContractView>[] {
const selectColumn: ColumnDef<BasicContractView> = {
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
className="translate-y-0.5"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
className="translate-y-0.5"
/>
),
maxSize: 30,
enableSorting: false,
enableHiding: false,
}
const actionsColumn: ColumnDef<BasicContractView> = {
id: "actions",
header: "작업",
cell: ({ row }) => {
const contract = row.original
const hasSignedFile = contract.signedFilePath && contract.signedFileName
const handleDownload = async () => {
if (!hasSignedFile) {
toast.error("다운로드할 파일이 없습니다")
return
}
await downloadFile(
contract.signedFilePath!,
contract.signedFileName!,
{
action: 'download',
showToast: true,
onError: (error) => {
console.error("Download failed:", error)
},
onSuccess: (fileName, fileSize) => {
console.log(`Downloaded: ${fileName} (${fileSize} bytes)`)
}
}
)
}
const handlePreview = async () => {
if (!hasSignedFile) {
toast.error("미리볼 파일이 없습니다")
return
}
await quickPreview(contract.signedFilePath!, contract.signedFileName!)
}
const handleResend = () => {
setRowAction({ type: "resend", row } as DataTableRowAction<BasicContractView>)
}
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{hasSignedFile && (
<>
<DropdownMenuItem onClick={handlePreview}>
<Eye className="mr-2 h-4 w-4" />
파일 미리보기
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDownload}>
<Download className="mr-2 h-4 w-4" />
파일 다운로드
</DropdownMenuItem>
</>
)}
<DropdownMenuItem onClick={handleResend}>
<Mail className="mr-2 h-4 w-4" />
재발송
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
},
enableSorting: false,
enableHiding: false,
maxSize: 80,
}
// Red Flag 발생여부 컬럼 (준법서약 템플릿만)
const redFlagColumn: ColumnDef<BasicContractView> = {
id: "redFlag",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="Red Flag" />
),
cell: ({ row }) => {
const contract = row.original;
const contractId = contract.id;
// 로딩 중이면 로딩 표시
if (isLoadingRedFlagData) {
return <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />;
}
const hasRedFlag = redFlagData[contractId] || false;
if (hasRedFlag) {
return (
<Badge variant="destructive" className="font-medium">
Red Flag
</Badge>
);
}
return (
<div className="text-sm text-gray-400">-</div>
);
},
minSize: 120,
enableHiding: false,
}
// Red Flag 해제 컬럼 (준법서약 템플릿만)
const redFlagResolutionColumn: ColumnDef<BasicContractView> = {
id: "redFlagResolution",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="Red Flag 해제" />
),
cell: ({ row }) => {
const contract = row.original;
const contractId = contract.id;
// 로딩 중이면 로딩 표시
if (isLoadingRedFlagResolutionData) {
return <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />;
}
const resolution = redFlagResolutionData[contractId];
if (resolution?.resolved && resolution.resolvedAt) {
return (
<div className="text-sm">
<Badge variant="default" className="font-medium bg-green-600">
해제됨
</Badge>
<div className="text-xs text-gray-500 mt-1">
{formatDateTime(resolution.resolvedAt, "KR")}
</div>
</div>
);
}
if (resolution?.pendingApprovalId) {
return (
<div className="text-sm">
<Badge variant="secondary" className="font-medium">
해소요청 진행중
</Badge>
<div className="text-xs text-gray-500 mt-1">
결재 ID: {resolution.pendingApprovalId.slice(-6)}
</div>
</div>
);
}
return (
<div className="text-sm text-gray-400">-</div>
);
},
minSize: 140,
enableHiding: false,
}
// 기본 컬럼 배열
const baseColumns: ColumnDef<BasicContractView>[] = [
selectColumn,
// 업체 코드
{
accessorKey: "vendorCode",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="업체코드" />
),
cell: ({ row }) => {
const code = row.getValue("vendorCode") as string | null
return code ? (
<span className="font-mono text-sm bg-gray-100 px-2 py-1 rounded">
{code}
</span>
) : "-"
},
minSize: 120,
},
// 업체명 (GTC 정보 포함)
{
accessorKey: "vendorName",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="업체명" />
),
cell: ({ row }) => {
const name = row.getValue("vendorName") as string | null
const contract = row.original
const isGTCTemplate = contract.templateName?.includes('GTC')
const isComplianceContract = contract.templateName?.includes('준법')
const contractGtcData = gtcData[contract.id]
const complianceNegotiation = agreementCommentData[contract.id]
const hasComplianceRedFlag = !!redFlagData[contract.id]
const isNegotiationCompleted = !!contract.negotiationCompletedAt
const handleOpenGTC = (e: React.MouseEvent) => {
e.stopPropagation()
if (typeof window === "undefined") return
// 현재 URL에서 언어(lng) 추출
const pathname = window.location.pathname || ""
const segments = pathname.split("/").filter(Boolean)
const lng = segments[0] || ""
const basePath = lng ? `/${lng}` : ""
// 상세보기와 동일하게 contract.id를 경로 파라미터로 사용
const params = new URLSearchParams();
params.set("contractId", contract.id.toString());
if (contract.templateId) {
params.set("templateId", contract.templateId.toString());
}
if (contract.vendorId) {
params.set("vendorId", contract.vendorId.toString());
}
if (contract.vendorName) {
params.set("vendorName", contract.vendorName);
}
const query = params.toString();
const gtcUrl = `${basePath}/evcp/basic-contract/vendor-gtc/${contract.id}${query ? `?${query}` : ""}`;
window.open(gtcUrl, '_blank');
}
return (
<div className="flex items-center gap-2">
<div className="font-medium">{name || "-"}</div>
{isGTCTemplate && (
<div className="flex items-center gap-1">
{isLoadingGtcData ? (
<Loader2 className="h-3 w-3 animate-spin text-gray-400" />
) : contractGtcData ? (
<div className="flex items-center gap-1">
{contractGtcData.hasComments && (
<Badge
variant="secondary"
className="text-xs bg-orange-100 text-orange-700 cursor-pointer hover:bg-orange-200"
title={`GTC Document ID: ${contractGtcData.gtcDocumentId} - 클릭하여 협의이력 보기`}
onClick={handleOpenGTC}
>
<MessageCircle className="h-3 w-3 mr-1" />
협의이력
</Badge>
)}
</div>
) : (
<Badge variant="secondary" className="text-xs">
GTC
</Badge>
)}
</div>
)}
{isComplianceContract && (
<div className="flex items-center gap-1">
{isLoadingAgreementCommentData ? (
<Loader2 className="h-3 w-3 animate-spin text-gray-400" />
) : isNegotiationCompleted ? (
<Badge
variant="outline"
className="text-xs bg-green-50 text-green-700 border-green-200"
>
<MessageCircle className="h-3 w-3 mr-1" />
협의 완료
</Badge>
) : complianceNegotiation?.hasComments ? (
<Badge
variant="outline"
className="text-xs bg-orange-50 text-orange-700 border-orange-200"
title={`협의 코멘트 ${complianceNegotiation.commentCount}개`}
onClick={(event) => {
event.stopPropagation();
if (typeof window === "undefined") return;
const params = new URLSearchParams();
if (contract.templateId) {
params.set("templateId", contract.templateId.toString());
}
if (contract.vendorId) {
params.set("vendorId", contract.vendorId.toString());
}
if (contract.vendorName) {
params.set("vendorName", contract.vendorName);
}
// 현재 URL에서 언어(lng) 추출
const pathname = window.location.pathname || ""
const segments = pathname.split("/").filter(Boolean)
const lng = segments[0] || ""
const basePath = lng ? `/${lng}` : ""
const query = params.toString();
const complianceUrl = `${basePath}/evcp/basic-contract/compliance-comments/${contract.id}${query ? `?${query}` : ""}`;
window.open(complianceUrl, "_blank", "noopener,noreferrer");
}}
style={{ cursor: "pointer" }}
>
<MessageCircle className="h-3 w-3 mr-1" />
협의 진행중 ({complianceNegotiation.commentCount})
</Badge>
) : (
hasComplianceRedFlag && !isNegotiationCompleted && (
<Badge
variant="outline"
className="text-xs bg-blue-50 text-blue-700 border-blue-200"
title="SHI에서 협의 코멘트를 시작합니다"
onClick={async (event) => {
event.stopPropagation()
if (typeof window === "undefined") return
try {
const complianceResponse = await getComplianceResponseByBasicContractId(contract.id)
if (!complianceResponse) {
toast.error("준법 설문 응답을 찾을 수 없습니다.")
return
}
// 현재 URL에서 언어(lng) 추출
const pathname = window.location.pathname || ""
const segments = pathname.split("/").filter(Boolean)
const lng = segments[0] || ""
const basePath = lng ? `/${lng}` : ""
router.push(
`${basePath}/evcp/compliance/${complianceResponse.templateId}/responses/${complianceResponse.id}`
)
} catch (error) {
console.error("Failed to open compliance response detail:", error)
toast.error("준법 설문 응답 상세 페이지로 이동하는 데 실패했습니다.")
}
}}
style={{ cursor: "pointer" }}
>
<MessageCircle className="h-3 w-3 mr-1" />
협의 코멘트 작성
</Badge>
)
)}
</div>
)}
</div>
)
},
minSize: 250,
},
// 진행상태
{
accessorKey: "status",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="진행상태" />
),
cell: ({ row }) => {
const status = row.getValue("status") as keyof typeof CONTRACT_STATUS_CONFIG
const config = CONTRACT_STATUS_CONFIG[status] || { label: status, color: "gray" }
const variantMap = {
gray: "secondary",
blue: "default",
green: "default",
purple: "secondary",
indigo: "secondary",
emerald: "default",
red: "destructive",
} as const
return (
<Badge variant={variantMap[config.color as keyof typeof variantMap]}>
{config.label}
</Badge>
)
},
minSize: 140,
filterFn: (row, id, value) => {
return value.includes(row.getValue(id))
},
},
// 요청일
{
accessorKey: "createdAt",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="요청일" />
),
cell: ({ row }) => {
const date = row.getValue("createdAt") as Date
return (
<div className="text-sm">
<div>{formatDateTime(date, "KR")}</div>
</div>
)
},
minSize: 130,
},
// 마감일
{
accessorKey: "deadline",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="마감일" />
),
cell: ({ row }) => {
const deadline = row.getValue("deadline") as string | null
const status = row.getValue("status") as string
if (!deadline) return "-"
const deadlineDate = new Date(deadline)
const today = new Date()
const isOverdue = deadlineDate < today && !["COMPLETED", "REJECTED"].includes(status)
const isNearDeadline = !isOverdue && deadlineDate.getTime() - today.getTime() < 2 * 24 * 60 * 60 * 1000 // 2일 이내
return (
<div className={`text-sm flex items-center gap-1 ${
isOverdue ? 'text-red-600 font-medium' :
isNearDeadline ? 'text-orange-600' :
'text-gray-900'
}`}>
<Clock className="h-3 w-3" />
<div>
<div>{deadlineDate.toLocaleDateString('ko-KR')}</div>
{isOverdue && <div className="text-xs">(지연)</div>}
{isNearDeadline && !isOverdue && <div className="text-xs">(임박)</div>}
</div>
</div>
)
},
minSize: 120,
},
// 협력업체 서명일
{
accessorKey: "vendorSignedAt",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="협력업체 서명" />
),
cell: ({ row }) => {
const date = row.getValue("vendorSignedAt") as Date | null
return date ? (
<div className="text-sm text-blue-600">
<div className="font-medium">완료</div>
<div className="text-xs">{formatDateTime(date, "KR")}</div>
</div>
) : (
<div className="text-sm text-gray-400">미완료</div>
)
},
minSize: 130,
},
// 법무검토 상태
{
accessorKey: "legalReviewStatus",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="법무검토 상태" />
),
cell: ({ row }) => {
const status = row.getValue("legalReviewStatus") as string | null
// PRGS_STAT_DSC 연동값 우선 표시
if (status) {
return <div className="text-sm text-gray-800">{status}</div>
}
// 동기화된 값이 없으면 빈 값 처리
return <div className="text-sm text-gray-400">-</div>
},
minSize: 140,
},
// 계약완료일
{
accessorKey: "completedAt",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="계약완료" />
),
cell: ({ row }) => {
const date = row.getValue("completedAt") as Date | null
return date ? (
<div className="text-sm text-emerald-600">
<div className="font-medium">완료</div>
<div className="text-xs">{formatDateTime(date, "KR")}</div>
</div>
) : (
<div className="text-sm text-gray-400">미완료</div>
)
},
minSize: 120,
},
// 서명된 파일
{
accessorKey: "signedFileName",
header: ({ column }) => (
<DataTableColumnHeaderSimple column={column} title="서명파일" />
),
cell: ({ row }) => {
const fileName = row.getValue("signedFileName") as string | null
const filePath = row.original.signedFilePath
const vendorSignedAt = row.original.vendorSignedAt
if (!fileName || !filePath|| !vendorSignedAt) {
return <div className="text-sm text-gray-400">파일 없음</div>
}
const handleQuickDownload = async (e: React.MouseEvent) => {
e.stopPropagation()
await downloadFile(filePath, fileName, {
action: 'download',
showToast: true
})
}
const handleQuickPreview = async (e: React.MouseEvent) => {
e.stopPropagation()
await quickPreview(filePath, fileName)
}
return (
<div className="flex items-center gap-2">
<div className="text-sm">
<div className="font-medium text-blue-600 truncate max-w-[150px]" title={fileName}>
서명파일
</div>
<div className="text-xs text-gray-500">클릭하여 다운로드</div>
</div>
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
onClick={handleQuickPreview}
className="h-6 w-6 p-0"
title="미리보기"
>
<Eye className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleQuickDownload}
className="h-6 w-6 p-0"
title="다운로드"
>
<Download className="h-3 w-3" />
</Button>
</div>
</div>
)
},
minSize: 200,
enableSorting: false,
},
actionsColumn,
]
// 준법서약 템플릿인 경우 Red Flag 컬럼과 해제 컬럼을 법무검토 상태 뒤에 추가
if (isComplianceTemplate) {
const legalReviewStatusIndex = baseColumns.findIndex((col) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (col as any).accessorKey === 'legalReviewStatus'
})
if (legalReviewStatusIndex !== -1) {
baseColumns.splice(legalReviewStatusIndex + 1, 0, redFlagColumn, redFlagResolutionColumn)
}
}
return baseColumns
}
|