summaryrefslogtreecommitdiff
path: root/lib/vendors/table/vendors-table-columns.tsx
blob: 738b8b5fe0d345287e1b14297ac92f780899afec (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
"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { Ellipsis, PaperclipIcon } from "lucide-react"
import { toast } from "sonner"

import { getErrorMessage } from "@/lib/handle-error"
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,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header"
import { useRouter } from "next/navigation"

import { VendorWithTypeAndMaterials, vendors, VendorWithAttachments } from "@/db/schema/vendors"
import { modifyVendor } from "../service"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { vendorColumnsConfig } from "@/config/vendorColumnsConfig"
import { Separator } from "@/components/ui/separator"
import { AttachmentsButton } from "./attachmentButton"
import { getVendorStatusIcon } from "../utils"

// 타입 정의 추가
type StatusType = (typeof vendors.status.enumValues)[number];
type BadgeVariantType = "default" | "secondary" | "destructive" | "outline";
type StatusConfig = {
  variant: BadgeVariantType;
  className: string;
};
type StatusDisplayMap = {
  [key in StatusType]: string;
};

type NextRouter = ReturnType<typeof useRouter>;

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





/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction, router, userId }: GetColumnsProps): ColumnDef<VendorWithTypeAndMaterials>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<VendorWithTypeAndMaterials> = {
    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"
      />
    ),
    size: 50,
    minSize: 50,
    maxSize: 50,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<VendorWithTypeAndMaterials> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      const [isUpdatePending, startUpdateTransition] = React.useTransition()

      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-56">
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "update" })}
            >
              레코드 편집
            </DropdownMenuItem>

            <DropdownMenuItem
              onSelect={() => {
                // 1) 만약 rowAction을 열고 싶다면
                // setRowAction({ row, type: "update" })

                // 2) 자세히 보기 페이지로 클라이언트 라우팅
                router.push(`/evcp/vendors/${row.original.id}/info`);
              }}
            >
              상세보기
            </DropdownMenuItem>
            <DropdownMenuItem
              onSelect={() => {
                // 새창으로 열기 위해 window.open() 사용
                window.open(`/evcp/vendors/${row.original.id}/info`, '_blank');
              }}
            >
              상세보기(새창)
            </DropdownMenuItem>
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "log" })}
            >
              감사 로그 보기
            </DropdownMenuItem>

            <Separator />
            <DropdownMenuSub>
              <DropdownMenuSubTrigger>Status</DropdownMenuSubTrigger>
              <DropdownMenuSubContent>
                <DropdownMenuRadioGroup
                  value={row.original.status}
                  onValueChange={(value) => {
                    startUpdateTransition(() => {
                      toast.promise(
                        modifyVendor({
                          id: String(row.original.id),
                          status: value as any,
                          userId,
                          vendorName: row.original.vendorName, // Required field from UpdateVendorSchema
                          comment: `Status changed to ${value}`
                        } as any),
                        {
                          loading: "Updating...",
                          success: "Label updated",
                          error: (err) => getErrorMessage(err),
                        }
                      )
                    })
                  }}
                >
                  {vendors.status.enumValues.map((status) => (
                    <DropdownMenuRadioItem
                      key={status}
                      value={status}
                      className="capitalize"
                      disabled={isUpdatePending}
                    >
                      {status}
                    </DropdownMenuRadioItem>
                  ))}
                </DropdownMenuRadioGroup>
              </DropdownMenuSubContent>
            </DropdownMenuSub>


          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 60,
    minSize: 60,
    maxSize: 60,
  }

  // ----------------------------------------------------------------
  // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
  // ----------------------------------------------------------------
  // 3-1) groupMap: { [groupName]: ColumnDef<VendorWithType>[] }
  const groupMap: Record<string, ColumnDef<VendorWithTypeAndMaterials>[]> = {}

  vendorColumnsConfig.forEach((cfg) => {
    // 만약 group가 없으면 "_noGroup" 처리
    const groupName = cfg.group || "_noGroup"

    if (!groupMap[groupName]) {
      groupMap[groupName] = []
    }

    // child column 정의
    const childCol: ColumnDef<VendorWithTypeAndMaterials> = {
      accessorKey: cfg.id,
      enableResizing: true,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
      size: cfg.width || 150,
      minSize: cfg.minWidth || 100,
      maxSize: cfg.maxWidth,
      cell: ({ row, cell }) => {
        // Status 컬럼 렌더링 개선 - 아이콘과 더 선명한 배경색 사용
        if (cfg.id === "status") {
          const statusVal = row.original.status as StatusType;
          if (!statusVal) return null;

          // Status badge variant mapping - 더 뚜렷한 색상으로 변경
          const getStatusConfig = (status: StatusType): StatusConfig & { iconColor: string } => {
            switch (status) {
              case "PENDING_REVIEW":
                return {
                  variant: "outline",
                  className: "bg-yellow-100 text-yellow-800 border-yellow-300",
                  iconColor: "text-yellow-600"
                };
              case "IN_REVIEW":
                return {
                  variant: "outline",
                  className: "bg-blue-100 text-blue-800 border-blue-300",
                  iconColor: "text-blue-600"
                };
              case "REJECTED":
                return {
                  variant: "outline",
                  className: "bg-red-100 text-red-800 border-red-300",
                  iconColor: "text-red-600"
                };
              case "IN_PQ":
                return {
                  variant: "outline",
                  className: "bg-purple-100 text-purple-800 border-purple-300",
                  iconColor: "text-purple-600"
                };
              case "PQ_SUBMITTED":
                return {
                  variant: "outline",
                  className: "bg-indigo-100 text-indigo-800 border-indigo-300",
                  iconColor: "text-indigo-600"
                };
              case "PQ_FAILED":
                return {
                  variant: "outline",
                  className: "bg-red-100 text-red-800 border-red-300",
                  iconColor: "text-red-600"
                };
              case "PQ_APPROVED":
                return {
                  variant: "outline",
                  className: "bg-green-100 text-green-800 border-green-300",
                  iconColor: "text-green-600"
                };
              case "APPROVED":
                return {
                  variant: "outline",
                  className: "bg-green-100 text-green-800 border-green-300",
                  iconColor: "text-green-600"
                };
              case "READY_TO_SEND":
                return {
                  variant: "outline",
                  className: "bg-emerald-100 text-emerald-800 border-emerald-300",
                  iconColor: "text-emerald-600"
                };
              case "ACTIVE":
                return {
                  variant: "outline",
                  className: "bg-emerald-100 text-emerald-800 border-emerald-300 font-semibold",
                  iconColor: "text-emerald-600"
                };
              case "INACTIVE":
                return {
                  variant: "outline",
                  className: "bg-gray-100 text-gray-800 border-gray-300",
                  iconColor: "text-gray-600"
                };
              case "BLACKLISTED":
                return {
                  variant: "outline",
                  className: "bg-slate-800 text-white border-slate-900",
                  iconColor: "text-white"
                };
              default:
                return {
                  variant: "outline",
                  className: "bg-gray-100 text-gray-800 border-gray-300",
                  iconColor: "text-gray-600"
                };
            }
          };

          // Translate status for display
          const getStatusDisplay = (status: StatusType): string => {
            const statusMap: StatusDisplayMap = {
              "PENDING_REVIEW": "가입 신청 중",
              "IN_REVIEW": "심사 중",
              "REJECTED": "심사 거부됨",
              "IN_PQ": "PQ 진행 중",
              "PQ_SUBMITTED": "PQ 제출",
              "PQ_FAILED": "PQ 실패",
              "PQ_APPROVED": "PQ 통과",
              "APPROVED": "승인됨",
              "READY_TO_SEND": "MDG 송부대기",
              "ACTIVE": "활성 상태",
              "INACTIVE": "비활성 상태",
              "BLACKLISTED": "거래 금지"
            };

            return statusMap[status] || status;
          };

          const config = getStatusConfig(statusVal);
          const displayText = getStatusDisplay(statusVal);
          const StatusIcon = getVendorStatusIcon(statusVal);

          return (
            <Badge variant={config.variant} className={`flex items-center px-2 py-1 ${config.className}`}>
              <StatusIcon className={`mr-1 h-3.5 w-3.5 ${config.iconColor}`} />
              <span>{displayText}</span>
            </Badge>
          );
        }

        // 업체 유형 컬럼 처리
        if (cfg.id === "vendorTypeName") {
          const typeVal = row.original.vendorTypeName as string | null;
          return typeVal ? (
            <span className="text-sm font-medium">
              {typeVal}
            </span>
          ) : (
            <span className="text-sm text-gray-400">미지정</span>
          );
        }

        // 업체 분류 컬럼 처리 (별도로 표시하고 싶은 경우)
        if (cfg.id === "vendorCategory") {
          const categoryVal = row.original.vendorCategory as string | null;
          if (!categoryVal) return null;

          let badgeClass = "";

          if (categoryVal === "정규업체") {
            badgeClass = "bg-green-50 text-green-700 border-green-200";
          } else if (categoryVal === "잠재업체") {
            badgeClass = "bg-blue-50 text-blue-700 border-blue-200";
          }

          return (
            <Badge variant="outline" className={badgeClass}>
              {categoryVal}
            </Badge>
          );
        }

        if (cfg.id === "createdAt") {
          const dateVal = cell.getValue() as Date
          return formatDate(dateVal, "KR")
        }

        if (cfg.id === "updatedAt") {
          const dateVal = cell.getValue() as Date
          return formatDate(dateVal, "KR")
        }

        // 업체대표품목 컬럼들 처리
        if (cfg.id === "primaryMaterial1" || cfg.id === "primaryMaterial2" || cfg.id === "primaryMaterial3") {
          const materialVal = cell.getValue() as string | null;
          if (!materialVal) return <span className="text-gray-400">-</span>;
          
          return (
            <div className="text-sm font-medium whitespace-pre-line max-w-[200px]">
              {materialVal}
            </div>
          );
        }

        // 성조회가입여부 처리 - 읽기전용 배지만 표시 (편집은 update-vendor-sheet에서 처리)
        if (cfg.id === "isAssociationMember") {
          const memberVal = row.original.isAssociationMember as string | null;
          
          const getDisplayText = (value: string | null) => {
            switch (value) {
              case "Y": return "가입";
              case "N": return "미가입";
              case "E": return "해당없음";
              default: return "정보없음";
            }
          };

          const getBadgeStyle = (value: string | null) => {
            switch (value) {
              case "Y": 
                return "bg-green-100 text-green-800 border-green-300";
              case "N": 
                return "bg-red-100 text-red-800 border-red-300";
              case "E": 
                return "bg-gray-100 text-gray-800 border-gray-300";
              default: 
                return "bg-gray-100 text-gray-800 border-gray-300";
            }
          };

          // 읽기전용 배지만 표시
          return (
            <Badge variant="outline" className={getBadgeStyle(memberVal)}>
              {getDisplayText(memberVal)}
            </Badge>
          );
        }

        // 최근 발주 실적 컬럼들 처리
        if (cfg.id === "recentPoNumber") {
          const poNumber = cell.getValue() as string | null;
          if (!poNumber) return <span className="text-gray-400">-</span>;
          
          return (
            <div className="text-sm font-medium max-w-[150px] truncate" title={poNumber}>
              {poNumber}
            </div>
          );
        }

        if (cfg.id === "recentPoOrderBy") {
          const orderBy = cell.getValue() as string | null;
          if (!orderBy) return <span className="text-gray-400">-</span>;
          
          return (
            <div className="text-sm font-medium whitespace-pre-line max-w-[150px]">
              {orderBy}
            </div>
          );
        }

        if (cfg.id === "recentPoDate") {
          const poDate = cell.getValue() as Date | null;
          if (!poDate) return <span className="text-gray-400">-</span>;
          
          return (
            <div className="text-sm">
              {formatDate(poDate, "KR")}
            </div>
          );
        }

        // TODO 컬럼들 (UI만) - 모두 "-" 표시
        if (cfg.id === "regularEvaluationGrade" || cfg.id === "faContract" || 
            cfg.id === "avlRegistration" || cfg.id === "regularVendorRegistration" ||
            cfg.id === "recentDeliveryNumber" || cfg.id === "recentDeliveryBy") {
          return <span className="text-gray-400">-</span>;
        }

        // 날짜 컬럼들 (TODO)
        if (cfg.id === "recentDeliveryDate") {
          return <span className="text-gray-400">-</span>;
        }

        // code etc...
        return row.getValue(cfg.id) ?? ""
      },
    }

    groupMap[groupName].push(childCol)
  })

  // ----------------------------------------------------------------
  // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기
  // ----------------------------------------------------------------
  const nestedColumns: ColumnDef<VendorWithTypeAndMaterials>[] = []

  // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함
  // 여기서는 그냥 Object.entries 순서
  Object.entries(groupMap).forEach(([groupName, colDefs]) => {
    if (groupName === "_noGroup") {
      // 그룹 없음 → 그냥 최상위 레벨 컬럼
      nestedColumns.push(...colDefs)
    } else {
      // 상위 컬럼
      nestedColumns.push({
        id: groupName,
        header: groupName, // "Basic Info", "Metadata" 등
        columns: colDefs,
      })
    }
  })

  // attachments 컬럼 타입 문제 해결을 위한 타입 단언
  const attachmentsColumn: ColumnDef<VendorWithTypeAndMaterials> = {
    id: "attachments",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="" />
    ),
    cell: ({ row }) => {
      const vendor = row.original as unknown as VendorWithAttachments;
    
    // 속성이 undefined일 수 있으므로 옵셔널 체이닝과 기본값 사용
    const hasAttachments = vendor.hasAttachments ?? false;
    const attachmentsList = vendor.attachmentsList ?? [];
    
      if (hasAttachments) {
        // 서버 액션을 사용하는 컴포넌트로 교체
        return (
          <AttachmentsButton
            vendorId={row.original.id}
            hasAttachments={hasAttachments}
            attachmentsList={attachmentsList}
          />
        );
      } else {
        return null;
      }
    },
    enableSorting: false,
    enableHiding: false,
    size: 50,
    minSize: 50,
    maxSize: 50,
  };


  // ----------------------------------------------------------------
  // 4) 최종 컬럼 배열: select, nestedColumns, actions
  // ----------------------------------------------------------------
  return [
    selectColumn,
    attachmentsColumn,
    ...nestedColumns,
    actionsColumn,
  ]
}