summaryrefslogtreecommitdiff
path: root/lib/vendor-evaluation-submit/table/evaluation-submissions-table-columns.tsx
blob: aa6255bcf38aec02c7c33ad2eea57bfa9b2fdff2 (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
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
"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { 
  Ellipsis, 
  InfoIcon, 
  PenToolIcon, 
  FileTextIcon, 
  ClipboardListIcon,
  DownloadIcon,
  CheckIcon,
  XIcon,
  ClockIcon,
  Send
} from "lucide-react"

import { formatDate, formatCurrency } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Badge } from "@/components/ui/badge"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { EvaluationSubmissionWithVendor } from "../service"

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<EvaluationSubmissionWithVendor> | null>>
}

/**
 * 제출 상태에 따른 배지 스타일 및 아이콘
 */
const getStatusBadge = (status: string) => {
  switch (status) {
    case 'draft':
      return {
        variant: "secondary" as const,
        icon: <ClockIcon className="h-3 w-3" />,
        label: "임시저장"
      }
    case 'submitted':
      return {
        variant: "default" as const,
        icon: <FileTextIcon className="h-3 w-3" />,
        label: "제출완료"
      }
    case 'under_review':
      return {
        variant: "outline" as const,
        icon: <ClipboardListIcon className="h-3 w-3" />,
        label: "검토중"
      }
    case 'approved':
      return {
        variant: "default" as const,
        icon: <CheckIcon className="h-3 w-3" />,
        label: "승인",
        className: "bg-green-100 text-green-800 border-green-200"
      }
    case 'rejected':
      return {
        variant: "destructive" as const,
        icon: <XIcon className="h-3 w-3" />,
        label: "반려"
      }
    default:
      return {
        variant: "secondary" as const,
        icon: null,
        label: status
      }
  }
}

/**
 * 평가 제출 테이블 컬럼 정의
 */
export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<EvaluationSubmissionWithVendor>[] {
  
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<EvaluationSubmissionWithVendor> = {
    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"
      />
    ),
    enableSorting: false,
    enableHiding: false,
    size: 40,
  }

  // ----------------------------------------------------------------
  // 2) 기본 정보 컬럼들
  // ----------------------------------------------------------------
  const basicColumns: ColumnDef<EvaluationSubmissionWithVendor>[] = [
    // {
    //   accessorKey: "submissionId",
    //   header: ({ column }) => (
    //     <DataTableColumnHeaderSimple column={column} title="제출 ID" />
    //   ),
    //   cell: ({ row }) => (
    //     <div className="font-mono text-sm">
    //       {row.getValue("submissionId")}
    //     </div>
    //   ),
    //   enableSorting: true,
    //   enableHiding: true,
    //   size: 400,
    //   minSize: 400,
    // },
    
    // {
    //   id: "vendorInfo",
    //   header: ({ column }) => (
    //     <DataTableColumnHeaderSimple column={column} title="협력업체" />
    //   ),
    //   cell: ({ row }) => {
    //     const vendor = row.original.vendor;
    //     return (
    //       <div className="space-y-1">
    //         <div className="font-medium">{vendor.vendorName}</div>
    //         <div className="text-sm text-muted-foreground">
    //           {vendor.vendorCode} • {vendor.countryCode}
    //         </div>
    //       </div>
    //     );
    //   },
    //   enableSorting: false,
    //   size: 200,
    // },
    

    
    // {
    //   accessorKey: "evaluationRound",
    //   header: ({ column }) => (
    //     <DataTableColumnHeaderSimple column={column} title="평가회차" />
    //   ),
    //   cell: ({ row }) => {
    //     const round = row.getValue("evaluationRound") as string;
    //     return round ? (
    //       <Badge variant="secondary">{round}</Badge>
    //     ) : (
    //       <span className="text-muted-foreground">-</span>
    //     );
    //   },
    //   size: 60,
    // },
  ]

  // ----------------------------------------------------------------
  // 3) 상태 정보 컬럼들
  // ----------------------------------------------------------------
  const statusColumns: ColumnDef<EvaluationSubmissionWithVendor>[] = [
    {
      accessorKey: "submissionStatus",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="제출상태" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("submissionStatus") as string;
        const badgeInfo = getStatusBadge(status);
        
        return (
          <Badge 
            variant={badgeInfo.variant}
            className={`flex items-center gap-1 ${badgeInfo.className || ''}`}
          >
            {badgeInfo.icon}
            {badgeInfo.label}
          </Badge>
        );
      },
      size: 120,
    },
    
    {
      accessorKey: "submittedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="제출일시" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("submittedAt") as Date;
        return date ? formatDate(date) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 140,
    },
    
    {
      id: "reviewInfo",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="검토정보" />
      ),
      cell: ({ row }) => {
        const reviewedAt = row.original.reviewedAt;
        const reviewedBy = row.original.reviewedBy;
        
        if (!reviewedAt) {
          return <span className="text-muted-foreground">미검토</span>;
        }
        
        return (
          <div className="space-y-1">
            <div className="text-sm">{formatDate(reviewedAt)}</div>
            {reviewedBy && (
              <div className="text-xs text-muted-foreground">{reviewedBy}</div>
            )}
          </div>
        );
      },
      enableSorting: false,
      size: 140,
    },
  ]

  // ----------------------------------------------------------------
  // 4) 점수 및 통계 컬럼들
  // ----------------------------------------------------------------
  const scoreColumns: ColumnDef<EvaluationSubmissionWithVendor>[] = [
    {
      id: "generalProgress",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="일반평가" />
      ),
      cell: ({ row }) => {
        const totalItems = row.original.totalGeneralItems || 0;
        const completedItems = row.original.completedGeneralItems || 0;
        const completionRate = totalItems > 0 ? (completedItems / totalItems) * 100 : 0;
        
        return (
          <div className="text-center space-y-1">
            {/* ❌ 점수 표시 제거 */}
            <div className="font-medium">
              {completionRate === 100 ? "완료" : "진행중"}
            </div>
            <div className="flex items-center gap-1">
              <Badge variant="outline" className="text-xs">
                {completedItems}/{totalItems}개
              </Badge>
              {completionRate > 0 && (
                <span className="text-xs text-muted-foreground">
                  ({completionRate.toFixed(0)}%)
                </span>
              )}
            </div>
            {/* 📊 진행률 바 */}
            <div className="w-full bg-gray-200 rounded-full h-1">
              <div
                className={`h-1 rounded-full transition-all duration-300 ${
                  completionRate === 100 
                    ? 'bg-green-500' 
                    : completionRate >= 50 
                      ? 'bg-blue-500' 
                      : 'bg-yellow-500'
                }`}
                style={{ width: `${completionRate}%` }}
              />
            </div>
          </div>
        );
      },
      enableSorting: false,
      size: 120,
    },
    
    {
      id: "esgScore",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="ESG평가" />
      ),
      cell: ({ row }) => {
        const averageScore = row.original.averageEsgScore;
        const totalItems = row.original.totalEsgItems || 0;
        const completedItems = row.original.completedEsgItems || 0;
        const completionRate = totalItems > 0 ? (completedItems / totalItems) * 100 : 0;
        const isKorean = row.original.vendor.countryCode === 'KR';
        
        if (!isKorean) {
          return (
            <div className="text-center text-muted-foreground">
              <Badge variant="outline">해당없음</Badge>
            </div>
          );
        }
        
        return (
          <div className="text-center space-y-1">
            {/* ✅ ESG는 평균점수 표시 */}
            <div className="font-medium">
              {averageScore ? (
                <span className="text-blue-600">
                  평균 {parseFloat(averageScore.toString()).toFixed(1)}점
                </span>
              ) : (
                <span className="text-muted-foreground">미완료</span>
              )}
            </div>
            <div className="flex items-center gap-1">
              <Badge variant="outline" className="text-xs">
                {completedItems}/{totalItems}개
              </Badge>
              {completionRate > 0 && (
                <span className="text-xs text-muted-foreground">
                  ({completionRate.toFixed(0)}%)
                </span>
              )}
            </div>
            {/* 📊 진행률 바 */}
            <div className="w-full bg-gray-200 rounded-full h-1">
              <div
                className={`h-1 rounded-full transition-all duration-300 ${
                  completionRate === 100 
                    ? 'bg-green-500' 
                    : completionRate >= 50 
                      ? 'bg-blue-500' 
                      : 'bg-yellow-500'
                }`}
                style={{ width: `${completionRate}%` }}
              />
            </div>
          </div>
        );
      },
      enableSorting: false,
      size: 140,
    },
    
    {
      id: "overallProgress",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="전체 진행률" />
      ),
      cell: ({ row }) => {
        const totalGeneral = row.original.totalGeneralItems || 0;
        const completedGeneral = row.original.completedGeneralItems || 0;
        const totalEsg = row.original.totalEsgItems || 0;
        const completedEsg = row.original.completedEsgItems || 0;
        const isKorean = row.original.vendor.countryCode === 'KR';
        
        const totalItems = totalGeneral + (isKorean ? totalEsg : 0);
        const completedItems = completedGeneral + (isKorean ? completedEsg : 0);
        const completionRate = totalItems > 0 ? (completedItems / totalItems) * 100 : 0;
        
        return (
          <div className="text-center space-y-2">
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div
                className={`h-2 rounded-full transition-all duration-300 ${
                  completionRate === 100 
                    ? 'bg-green-500' 
                    : completionRate >= 50 
                      ? 'bg-blue-500' 
                      : 'bg-yellow-500'
                }`}
                style={{ width: `${completionRate}%` }}
              />
            </div>
            <div className="text-xs space-y-1">
              <div className="font-medium">
                {completionRate.toFixed(0)}% 완료
              </div>
              <div className="text-muted-foreground">
                {completedItems}/{totalItems}개 항목
              </div>
            </div>
          </div>
        );
      },
      enableSorting: false,
      size: 120,
    },
  
    {
      id: "attachments",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="첨부파일" />
      ),
      cell: ({ row }) => {
        const count = row.original._count.attachments;
        
        return (
          <div className="text-center">
            <Badge variant="outline">
              {count}개 파일
            </Badge>
          </div>
        );
      },
      enableSorting: false,
      size: 100,
    },
  ]
  

  // ----------------------------------------------------------------
  // 5) 메타데이터 컬럼들
  // ----------------------------------------------------------------
  const metaColumns: ColumnDef<EvaluationSubmissionWithVendor>[] = [
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("createdAt") as Date;
        return formatDate(date);
      },
      size: 140,
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수정일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("updatedAt") as Date;
        return formatDate(date);
      },
      size: 140,
    },
  ]

  // ----------------------------------------------------------------
  // 6) actions 컬럼 (드롭다운 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<EvaluationSubmissionWithVendor> = {
    id: "actions",
    header: "작업",
    enableHiding: false,
    cell: function Cell({ row }) {
      const status = row.original.submissionStatus;
      const isKorean = row.original.vendor.countryCode === 'KR';
      
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon">
              <Ellipsis className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              onClick={() => setRowAction({ row, type: "general_evaluation" })}
            >
              <FileTextIcon className="mr-2 h-4 w-4" />
              일반평가 작성
            </DropdownMenuItem>
            
            {isKorean && (
              <DropdownMenuItem
                onClick={() => setRowAction({ row, type: "esg_evaluation" })}
              >
                <ClipboardListIcon className="mr-2 h-4 w-4" />
                ESG평가 작성
              </DropdownMenuItem>
            )}
            
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onClick={() => setRowAction({ row, type: "submit" })}
            >
              <Send className="mr-2 h-4 w-4" />
              제출
            </DropdownMenuItem>
            
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 80,
  }

  // ----------------------------------------------------------------
  // 7) 최종 컬럼 배열 (그룹화 버전)
  // ----------------------------------------------------------------
  return [
    selectColumn,
    {
      accessorKey: "evaluationYear",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="평가연도" />
      ),
      cell: ({ row }) => (
        <Badge variant="outline">
          {row.getValue("evaluationYear")}년
        </Badge>
      ),
      size: 60,
    },
    {
      id: "statusInfo",
      header: "상태 정보",
      columns: statusColumns,
    },
    {
      id: "scoreInfo", 
      header: "점수 및 통계",
      columns: scoreColumns,
    },
    {
      id: "metadata",
      header: "메타데이터",
      columns: metaColumns,
    },
    actionsColumn,
  ]
}

// ----------------------------------------------------------------
// 8) 컬럼 설정 (필터링용)
// ----------------------------------------------------------------
export const evaluationSubmissionsColumnsConfig = [
  {
    id: "submissionId",
    label: "제출 ID",
    group: "기본 정보",
    type: "text",
    excelHeader: "Submission ID",
  },
  {
    id: "vendorName",
    label: "협력업체명",
    group: "기본 정보", 
    type: "text",
    excelHeader: "Vendor Name",
  },
  {
    id: "vendorCode",
    label: "협력업체 코드",
    group: "기본 정보",
    type: "text", 
    excelHeader: "Vendor Code",
  },
  {
    id: "evaluationYear",
    label: "평가연도",
    group: "기본 정보",
    type: "number",
    excelHeader: "Evaluation Year",
  },
  {
    id: "evaluationRound",
    label: "평가회차",
    group: "기본 정보",
    type: "text",
    excelHeader: "Evaluation Round",
  },
  {
    id: "submissionStatus",
    label: "제출상태",
    group: "상태 정보",
    type: "select",
    options: [
      { label: "임시저장", value: "draft" },
      { label: "제출완료", value: "submitted" },
      { label: "검토중", value: "under_review" },
      { label: "승인", value: "approved" },
      { label: "반려", value: "rejected" },
    ],
    excelHeader: "Submission Status",
  },
  {
    id: "submittedAt",
    label: "제출일시",
    group: "상태 정보",
    type: "date",
    excelHeader: "Submitted At",
  },
  {
    id: "reviewedAt",
    label: "검토일시",
    group: "상태 정보", 
    type: "date",
    excelHeader: "Reviewed At",
  },
  {
    id: "totalGeneralScore",
    label: "일반평가 점수",
    group: "점수 정보",
    type: "number",
    excelHeader: "Total General Score",
  },
  {
    id: "totalEsgScore",
    label: "ESG평가 점수",
    group: "점수 정보",
    type: "number",
    excelHeader: "Total ESG Score",
  },
  {
    id: "createdAt",
    label: "생성일",
    group: "메타데이터",
    type: "date",
    excelHeader: "Created At",
  },
  {
    id: "updatedAt",
    label: "수정일",
    group: "메타데이터",
    type: "date",
    excelHeader: "Updated At",
  },
] as const;