summaryrefslogtreecommitdiff
path: root/lib/pq/pq-review-table-new/vendors-table-columns.tsx
blob: 30b1c83fca6ccaf7ba5f888591db6a2d37f6c120 (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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"

// ColumnDef 타입 확장
type ExtendedColumnDef<T> = ColumnDef<T> & {
  excelHeader?: string;
}
import { Ellipsis, Eye, FileEdit, Trash2, Building2, FileText, Edit } from "lucide-react"

import { formatDate } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { useRouter } from "next/navigation"
import { PQDeleteDialog } from "@/components/pq-input/pq-delete-dialog"

// PQ 제출 타입 정의
export interface PQSubmission {
  // PQ 제출 정보
  id: number
  pqNumber: string
  type: string
  status: string
  requesterName: string | null  // 요청자 이름
  createdAt: Date
  updatedAt: Date
  submittedAt: Date | null
  approvedAt: Date | null
  rejectedAt: Date | null
  rejectReason: string | null

  // 협력업체 정보
  vendorId: number
  vendorName: string
  vendorCode: string
  taxId: string
  vendorStatus: string
  email: string
  // 프로젝트 정보
  projectId: number | null
  projectName: string | null
  projectCode: string | null

  // 답변 정보
  answerCount: number
  attachmentCount: number

  // PQ 상태
  pqStatus: string
  pqTypeLabel: string

  // PQ 대상품목
  pqItems: string | null | Array<{itemCode: string, itemName: string}>

  // 방문실사 요청 정보
  siteVisitRequestId: number | null  // 방문실사 요청 ID

  // 실사 정보
  investigation: {
    id: number
    investigationStatus: string
    requesterName: string | null  // 실사 요청자 이름
    qmManagerId: number | null
    qmManagerName: string | null // QM 담당자 이름
    qmManagerEmail: string | null // QM 담당자 이메일
    investigationAddress: string | null
    investigationMethod: string | null
    scheduledStartAt: Date | null
    scheduledEndAt: Date | null
    requestedAt: Date | null
    confirmedAt: Date | null
    completedAt: Date | null
    forecastedAt: Date | null
    evaluationScore: number | null
    evaluationResult: "APPROVED" | "SUPPLEMENT" | "REJECTED" | "RESULT_SENT" | null
    investigationNotes: string | null
  } | null
  // 통합 상태를 위한 새 필드
  combinedStatus: {
    status: string
    label: string
    variant: "default" | "outline" | "secondary" | "destructive" | "success"
  }
}

type NextRouter = ReturnType<typeof useRouter>;

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<PQSubmission> | null>>;
  router: NextRouter;
}

// 상태에 따른 Badge 변형 결정 함수
function getStatusBadge(status: string) {
  switch (status) {
    case "REQUESTED":
      return <Badge variant="outline">요청됨</Badge>
    case "IN_PROGRESS":
      return <Badge variant="secondary">진행 중</Badge>
    case "SUBMITTED":
      return <Badge>제출됨</Badge>
    case "APPROVED":
      return <Badge variant="success">승인됨</Badge>
    case "REJECTED":
      return <Badge variant="destructive">거부됨</Badge>
    default:
      return <Badge variant="outline">{status}</Badge>
  }
}

/**
 * tanstack table 컬럼 정의
 */
export function getColumns({ setRowAction, router }: GetColumnsProps): ExtendedColumnDef<PQSubmission>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ExtendedColumnDef<PQSubmission> = {
    id: "select",
    header: ({ table }) => {
      const selectedRows = table.getSelectedRowModel().rows;
      const isAllSelected = table.getIsAllPageRowsSelected();
      const isSomeSelected = table.getIsSomePageRowsSelected();

      return (
        <Checkbox
          checked={isAllSelected}
          indeterminate={isSomeSelected && !isAllSelected}
          onCheckedChange={(value) => {
            if (value) {
              // 전체 선택: 첫 번째 행만 선택
              table.toggleAllRowsSelected(false);
              if (table.getRowModel().rows.length > 0) {
                table.getRowModel().rows[0].toggleSelected(true);
              }
            } else {
              // 전체 해제
              table.toggleAllRowsSelected(false);
            }
          }}
          aria-label="Select all"
          className="translate-y-0.5"
        />
      );
    },
    cell: ({ row, table }) => {
      const selectedRows = table.getSelectedRowModel().rows;
      const isCurrentlySelected = row.getIsSelected();

      return (
        <Checkbox
          checked={isCurrentlySelected}
          onCheckedChange={(value) => {
            if (value) {
              // 체크하려는 경우: 이미 선택된 행이 있으면 모두 해제하고 현재 행만 선택
              table.toggleAllRowsSelected(false);
              row.toggleSelected(true);
            } else {
              // 체크 해제하는 경우
              row.toggleSelected(false);
            }
          }}
          aria-label="Select row"
          className="translate-y-0.5"
        />
      );
    },
    size: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) 일반 컬럼들
  // --------------------------
  // --------------------------------------

  const pqNoColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "pqNumber",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="PQ No." />
    ),
    cell: ({ row }) => (
      <div className="flex flex-col">
        <span className="font-medium">{row.getValue("pqNumber")}</span>
      </div>
    ),
    excelHeader: "PQ No.",
  }

  // 협력업체 컬럼
  const vendorColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "vendorName",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="협력업체" />
    ),
    cell: ({ row }) => (
      <div className="flex flex-col">
        <span className="font-medium">{row.getValue("vendorName")}</span>
        {/* <span className="text-xs text-muted-foreground">{row.original.vendorCode ? row.original.vendorCode : "-"}/{row.original.taxId}</span> */}
      </div>
    ),
    enableSorting: true,
    enableHiding: true,
    excelHeader: "협력업체",
  }

  // PQ 유형 컬럼
  const typeColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "type",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="PQ 유형" />
    ),
    cell: ({ row }) => {
      const { type, pqTypeLabel } = row.original;
      let label = pqTypeLabel;
      if (type === "NON_INSPECTION") {
        label = "미실사 PQ";
      }
      return (
        <div className="flex items-center">
          <Badge variant={type === "PROJECT" ? "default" : "outline"}>
            {label}
          </Badge>
        </div>
      );
    },
    filterFn: (row, id, value) => {
      return value.includes(row.getValue(id));
    },
    enableSorting: true,
    enableHiding: true,
    excelHeader: "PQ 유형",
  }

  // 프로젝트 컬럼
  const projectColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "projectName",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="프로젝트" />
    ),
    cell: ({ row }) => {
      const projectName = row.original.projectName
      const projectCode = row.original.projectCode

      if (!projectName) {
        return <span className="text-muted-foreground">-</span>
      }

      return (
        <div className="flex flex-col">
          <span>{projectName}</span>
          {projectCode && (
            <span className="text-xs text-muted-foreground">{projectCode}</span>
          )}
        </div>
      )
    },
    enableSorting: true,
    enableHiding: true,
    excelHeader: "프로젝트",
  }

  // 상태 컬럼
  const statusColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "combinedStatus",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="진행현황" />
    ),
    cell: ({ row }) => {
      const combinedStatus = getCombinedStatus(row.original);
      return <Badge variant={combinedStatus.variant}>{combinedStatus.label}</Badge>;
    },
    filterFn: (row, id, value) => {
      const combinedStatus = getCombinedStatus(row.original);
      return value.includes(combinedStatus.status);
    },
    enableSorting: true,
    enableHiding: true,
    excelHeader: "진행현황",
  };

  // PQ 상태와 실사 상태를 결합하는 헬퍼 함수
  function getCombinedStatus(submission: PQSubmission) {
    // PQ가 승인되지 않은 경우, PQ 상태를 우선 표시
    if (submission.status !== "APPROVED") {
      switch (submission.status) {
        case "REQUESTED":
          return { status: "PQ_REQUESTED", label: "PQ 요청됨", variant: "outline" as const };
        case "IN_PROGRESS":
          return { status: "PQ_IN_PROGRESS", label: "PQ 진행 중", variant: "secondary" as const };
        case "SUBMITTED":
          return { status: "PQ_SUBMITTED", label: "PQ 제출됨", variant: "default" as const };
        case "REJECTED":
          return { status: "PQ_REJECTED", label: "PQ 거부됨", variant: "destructive" as const };
        default:
          return { status: submission.status, label: submission.status, variant: "outline" as const };
      }
    }

    // PQ가 승인되었지만 실사가 없는 경우
    if (!submission.investigation) {
      return { status: "PQ_APPROVED", label: "PQ 승인됨", variant: "success" as const };
    }

    // PQ가 승인되고 실사가 있는 경우
    switch (submission.investigation.investigationStatus) {
      case "PLANNED":
        return { status: "INVESTIGATION_PLANNED", label: "실사 계획됨", variant: "outline" as const };
      case "IN_PROGRESS":
        return { status: "INVESTIGATION_IN_PROGRESS", label: "실사 진행 중", variant: "secondary" as const };
      case "COMPLETED":
        // 실사 완료 후 평가 결과에 따라 다른 상태 표시
        if (submission.investigation.evaluationResult) {
          switch (submission.investigation.evaluationResult) {
            case "APPROVED":
              return { status: "INVESTIGATION_APPROVED", label: "실사 승인", variant: "success" as const };
            case "SUPPLEMENT":
              return { status: "INVESTIGATION_SUPPLEMENT", label: "실사 보완필요", variant: "secondary" as const };
            case "REJECTED":
              return { status: "INVESTIGATION_REJECTED", label: "실사 불가", variant: "destructive" as const };
            default:
              return { status: "INVESTIGATION_COMPLETED", label: "실사 완료", variant: "default" as const };
          }
        }
        return { status: "INVESTIGATION_COMPLETED", label: "실사 완료", variant: "default" as const };
      case "CANCELED":
        return { status: "INVESTIGATION_CANCELED", label: "실사 취소됨", variant: "destructive" as const };
      case "RESULT_SENT":
        return { status: "INVESTIGATION_RESULT_SENT", label: "실사 결과 발송", variant: "success" as const };
      default:
        return {
          status: `INVESTIGATION_${submission.investigation.investigationStatus}`,
          label: `실사 ${submission.investigation.investigationStatus}`,
          variant: "outline" as const
        };
    }
  }

  // 평가유형 컬럼 (QM실사방법으로 교체됨)
  // const evaluationTypeColumn: ColumnDef<PQSubmission> = {
  //   accessorKey: "evaluationType",
  //   header: ({ column }) => (
  //     <DataTableColumnHeaderSimple column={column} title="평가 유형" />
  //   ),
  //   cell: ({ row }) => {
  //     const investigation = row.original.investigation;

  //     if (!investigation || !investigation.evaluationType) {
  //       return <span className="text-muted-foreground">-</span>;
  //     }

  //     switch (investigation.evaluationType) {
  //       case "PURCHASE_SELF_EVAL":
  //         return <Badge variant="outline">구매자체평가</Badge>;
  //       case "DOCUMENT_EVAL":
  //         return <Badge variant="secondary">서류평가</Badge>;
  //       case "PRODUCT_INSPECTION":
  //         return <Badge variant="default">제품검사평가</Badge>;
  //       case "SITE_VISIT_EVAL":
  //         return <Badge variant="destructive">방문실사평가</Badge>;
  //       default:
  //         return <span>{investigation.evaluationType}</span>;
  //     }
  //   },
  //   filterFn: (row, id, value) => {
  //     const investigation = row.original.investigation;
  //     if (!investigation || !investigation.evaluationType) return value.includes("null");
  //     return value.includes(investigation.evaluationType);
  //   },
  // };


  const evaluationResultColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "evaluationResult",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="평가 결과" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.evaluationResult) {
        return <span className="text-muted-foreground">-</span>;
      }

      switch (investigation.evaluationResult) {
        case "APPROVED":
          return <Badge variant="success">승인</Badge>;
        case "SUPPLEMENT":
          return <Badge variant="secondary">보완</Badge>;
        case "REJECTED":
          return <Badge variant="destructive">불가</Badge>;
        default:
          return <span>{investigation.evaluationResult}</span>;
      }
    },
    filterFn: (row, id, value) => {
      const investigation = row.original.investigation;
      if (!investigation || !investigation.evaluationResult) return value.includes("null");
      return value.includes(investigation.evaluationResult);
    },
    enableSorting: true,
    enableHiding: true,
    excelHeader: "평가 결과",
  };

  // 답변 수 컬럼
  const answerCountColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "answerCount",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="답변 수" />
    ),
    cell: ({ row }) => {
      return (
        <div className="flex items-center gap-2">
          <span>{row.original.answerCount}</span>
        </div>
      )
    },
    excelHeader: "답변 수",
  }

  const investigationAddressColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationAddress",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실사 주소" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.investigationAddress) {
        return <span className="text-muted-foreground">-</span>;
      }

      return (
        <div className="flex items-center gap-2">
          <span>{investigation.investigationAddress}</span>
        </div>
      )
    },
    excelHeader: "실사 주소",
  }
  const investigationRequestedAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationRequestedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실사 의뢰일" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.requestedAt) {
        return <span className="text-muted-foreground">-</span>;
      }
      const dateVal = investigation.requestedAt

      return (
        <div className="flex items-center gap-2">
          <span>{dateVal ? formatDate(dateVal, 'KR') : "-"}</span>
        </div>
      )
    },
    excelHeader: "실사 의뢰일",
  }

  const investigationNotesColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationNotes",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="QM 의견" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.investigationNotes) {
        return <span className="text-muted-foreground">-</span>;
      }

      return (
        <div className="flex items-center gap-2">
          <span>{investigation.investigationNotes}</span>
        </div>
      )
    },
    excelHeader: "QM 의견",
  }
  const investigationMethodColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationMethod",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="QM실사방법" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;
      if (!investigation || !investigation.investigationMethod) {
        return <span className="text-muted-foreground">-</span>;
      }

      switch (investigation.investigationMethod) {
        case "PURCHASE_SELF_EVAL":
          return <Badge variant="outline">구매자체평가</Badge>;
        case "DOCUMENT_EVAL":
          return <Badge variant="secondary">서류평가</Badge>;
        case "PRODUCT_INSPECTION":
          return <Badge variant="default">제품검사평가</Badge>;
        case "SITE_VISIT_EVAL":
          return <Badge variant="destructive">방문실사평가</Badge>;
        default:
          return <span>{investigation.investigationMethod}</span>;
      }
    },
    excelHeader: "실사품목",
  }

  // 실사품목 컬럼
  const pqItemsColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "pqItems",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실사품목" />
    ),
    cell: ({ row }) => {
      const pqItems = row.original.pqItems;

      if (!pqItems) {
        return <span className="text-muted-foreground">-</span>;
      }

      // JSON 파싱하여 첫 번째 아이템 표시
        const items = typeof pqItems === 'string' ? JSON.parse(pqItems) : pqItems;
        if (Array.isArray(items) && items.length > 0) {
          const firstItem = items[0];
          return (
            <div className="flex items-center gap-2">
              <span className="text-sm">{firstItem.itemCode} - {firstItem.itemName}</span>
              {items.length > 1 && (
                <span className="text-xs text-muted-foreground">외 {items.length - 1}건</span>
              )}
            </div>
          );
        }
    },
  }





  const investigationForecastedAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationForecastedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실사 수행 예정일" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.forecastedAt) {
        return <span className="text-muted-foreground">-</span>;
      }
      const dateVal = investigation.forecastedAt

      return (
        <div className="flex items-center gap-2">
          <span>{dateVal ? formatDate(dateVal, 'KR') : "-"}</span>
        </div>
      )
    },
    excelHeader: "실사 수행 예정일",
  }

  const investigationConfirmedAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationConfirmedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실사 계획 확정일" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.confirmedAt) {
        return <span className="text-muted-foreground">-</span>;
      }
      const dateVal = investigation.confirmedAt

      return (
        <div className="flex items-center gap-2">
          <span>{dateVal ? formatDate(dateVal, 'KR') : "-"}</span>
        </div>
      )
    },
    excelHeader: "실사 계획 확정일",
  }

  const investigationCompletedAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "investigationCompletedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="실제 실사일" />
    ),
    cell: ({ row }) => {
      const investigation = row.original.investigation;

      if (!investigation || !investigation.completedAt) {
        return <span className="text-muted-foreground">-</span>;
      }
      const dateVal = investigation.completedAt

      return (
        <div className="flex items-center gap-2">
          <span>{dateVal ? formatDate(dateVal, 'KR') : "-"}</span>
        </div>
      )
    },
    excelHeader: "실제 실사일",
  }

  // 제출일 컬럼
  const createdAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "createdAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="PQ 전송일" />
    ),
    cell: ({ row }) => {
      const dateVal = row.original.createdAt as Date
      return formatDate(dateVal, 'KR')
    },
    excelHeader: "PQ 전송일",
  }

  // 제출일 컬럼
  const submittedAtColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "submittedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="PQ 회신일" />
    ),
    cell: ({ row }) => {
      const dateVal = row.original.submittedAt as Date
      return dateVal ? formatDate(dateVal, 'KR') : "-"
    },
    excelHeader: "PQ 회신일",
  }

  // 승인/거부일 컬럼
  const approvalDateColumn: ExtendedColumnDef<PQSubmission> = {
    accessorKey: "approvedAt",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="PQ 승인/거부일" />
    ),
    cell: ({ row }) => {
      if (row.original.approvedAt) {
        return <span className="text-green-600">{formatDate(row.original.approvedAt)}</span>
      }
      if (row.original.rejectedAt) {
        return <span className="text-red-600">{formatDate(row.original.rejectedAt)}</span>
      }
      return "-"
    },
    excelHeader: "PQ 승인/거부일",
  }

  // ----------------------------------------------------------------
  // 3) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ExtendedColumnDef<PQSubmission> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      const pq = row.original
      const isSubmitted = pq.status === "SUBMITTED"
      const reviewUrl = `/evcp/pq_new/${pq.vendorId}/${pq.id}`

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="Open menu"
              variant="ghost"
              className="flex size-8 p-0 data-[state=open]:bg-muted"
            >
              <Ellipsis className="size-4" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-40">
            <DropdownMenuItem
              onSelect={() => {
                router.push(reviewUrl);
              }}
            >
              {isSubmitted ? (
                <>
                  <FileEdit className="mr-2 h-4 w-4" />
                  검토
                </>
              ) : (
                <>
                  <Eye className="mr-2 h-4 w-4" />
                  PQ 현황
                </>
              )}
            </DropdownMenuItem>
            
            {/* 방문실사 버튼 - PQ가 승인됨 상태이고 제품검사평가 또는 방문실사평가인 경우에만 표시 */}
            {pq.status === "APPROVED" && pq.investigation &&
             (pq.investigation.investigationMethod === "PRODUCT_INSPECTION" ||
              pq.investigation.investigationMethod === "SITE_VISIT_EVAL") && (
              <>
                <DropdownMenuItem
                  onSelect={(e) => {
                    e.preventDefault();
                    // 방문실사 다이얼로그 열기 로직
                    setRowAction({
                      type: "site-visit",
                      row: row.original
                    });
                  }}
                >
                  <Building2 className="mr-2 h-4 w-4" />
                  실사 정보 전달 및 요청
                </DropdownMenuItem>
                <DropdownMenuItem
                  onSelect={(e) => {
                    e.preventDefault();
                    // 협력업체 정보 조회 다이얼로그 열기 로직
                    setRowAction({
                      type: "vendor-info-view",
                      row: row.original
                    });
                  }}
                >
                  <FileText className="mr-2 h-4 w-4" />
                  실사 실시 확정 정보
                </DropdownMenuItem>
              </>
            )}

            {/* 실사 정보 수정 버튼 - 구매자체평가인 경우에만 표시 */}
            {pq.investigation && 
             pq.investigation.investigationMethod === "PURCHASE_SELF_EVAL" && (
              <DropdownMenuItem
                onSelect={(e) => {
                  e.preventDefault();
                  // 실사 정보 수정 다이얼로그 열기 로직
                  setRowAction({
                    type: "update",
                    row: row.original
                  });
                }}
              >
                <Edit className="mr-2 h-4 w-4" />
                실사 정보 수정
              </DropdownMenuItem>
            )}
            
            {/* 삭제 메뉴 - REQUESTED 상태일 때만 표시 */}
            {pq.status === "REQUESTED" && (
              <PQDeleteDialog
                pqSubmissionId={pq.id}
                status={pq.status}
              >
                <DropdownMenuItem
                  onSelect={(e) => {
                    e.preventDefault();
                  }}
                  className="text-destructive focus:text-destructive"
                >
                  <Trash2 className="mr-2 h-4 w-4" />
                  삭제
                </DropdownMenuItem>
              </PQDeleteDialog>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 40,
  }

  // 요청자 컬럼 추가
const requesterColumn: ExtendedColumnDef<PQSubmission> = {
  accessorKey: "requesterName",
  header: ({ column }) => (
    <DataTableColumnHeaderSimple column={column} title="PQ/실사 요청자" />
  ),
  cell: ({ row }) => {
    // PQ 요청자와 실사 요청자를 모두 표시
    const pqRequesterName = row.original.requesterName;
    const investigationRequesterName = row.original.investigation?.requesterName;
    
    // 상태에 따라 적절한 요청자 표시
    const status = getCombinedStatus(row.original).status;
    
    if (status.startsWith('INVESTIGATION_') && investigationRequesterName) {
      return <span>{investigationRequesterName}</span>;
    }
    
    return pqRequesterName 
      ? <span>{pqRequesterName}</span> 
      : <span className="text-muted-foreground">-</span>;
  },
  excelHeader: "PQ/실사 요청자",
};
const qmManagerColumn: ExtendedColumnDef<PQSubmission> = {
  accessorKey: "qmManager",
  header: ({ column }) => (
    <DataTableColumnHeaderSimple column={column} title="QM 담당자" />
  ),
  cell: ({ row }) => {
    const investigation = row.original.investigation;
    
    if (!investigation || !investigation.qmManagerName) {
      return <span className="text-muted-foreground">-</span>;
    }
    
    return (
      <div className="flex flex-col">
        <span>{investigation.qmManagerName}</span>
        {investigation.qmManagerEmail && (
          <span className="text-xs text-muted-foreground">{investigation.qmManagerEmail}</span>
        )}
      </div>
    );
  },
  excelHeader: "QM 담당자",
};


  // ----------------------------------------------------------------
  // 4) 최종 컬럼 배열
  // ----------------------------------------------------------------
  return [
    selectColumn,
    statusColumn,       // 통합된 진행현황 컬럼
    pqNoColumn,
    vendorColumn,
    investigationAddressColumn,
    typeColumn,
    projectColumn,
    pqItemsColumn,      // 실사품목 컬럼
    createdAtColumn,
    submittedAtColumn,
    approvalDateColumn,
    answerCountColumn,
    investigationMethodColumn,
    investigationForecastedAtColumn,
    investigationRequestedAtColumn,
    investigationConfirmedAtColumn,
    investigationCompletedAtColumn,
    evaluationResultColumn, // 평가 결과 컬럼
    requesterColumn,
    qmManagerColumn,
    investigationNotesColumn,
    actionsColumn,
  ];
}