summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/table/investigation-table-columns.tsx
blob: 03e66076631a7588958f9c9c6da84fc6246a1de1 (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
"use client"

import * as React from "react"
import { ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Edit, Ellipsis, AlertTriangle, FileEdit, Eye, FileText } from "lucide-react"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { formatDate } from "@/lib/utils"

// Import types
import { type DataTableRowAction } from "@/types/table"
import { 
  vendorInvestigationsColumnsConfig, 
  VendorInvestigationsViewWithContacts 
} from "@/config/vendorInvestigationsColumnsConfig"
import { useRouter } from "next/navigation"
// Props for the column generator function
interface GetVendorInvestigationsColumnsProps {
  setRowAction?: React.Dispatch<
    React.SetStateAction<
      DataTableRowAction<VendorInvestigationsViewWithContacts> | null
    >
  >
  openVendorDetailsModal?: (vendorId: number) => void
  openSupplementRequestDialog?: (investigationId: number, investigationMethod: string, vendorName: string) => void
}

// Helper function for investigation method variants
function getMethodVariant(method: string): "default" | "secondary" | "outline" | "destructive" {
  switch (method) {
    case "PURCHASE_SELF_EVAL":
      return "secondary"
    case "DOCUMENT_EVAL":
      return "outline"
    case "PRODUCT_INSPECTION":
      return "default"
    case "SITE_VISIT_EVAL":
      return "destructive"
    default:
      return "outline"
  }
}

export function getColumns({
  setRowAction,
  openVendorDetailsModal,
  openSupplementRequestDialog,
}: GetVendorInvestigationsColumnsProps): ColumnDef<
  VendorInvestigationsViewWithContacts
>[] {
  // --------------------------------------------
  // 1) Select (checkbox) column
  // --------------------------------------------
  const selectColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    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: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // --------------------------------------------
  // 2) Actions column
  // --------------------------------------------
  const actionsColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const router = useRouter()
      const isCanceled = row.original.investigationStatus === "CANCELED"
      const isCompleted = row.original.investigationStatus === "COMPLETED"
      const canReviewPQ = !isCanceled && row.original.investigationStatus === "PLANNED" && !!row.original.pqSubmissionId
      const reviewUrl = `/evcp/pq_new/${row.original.vendorId}/${row.original.pqSubmissionId}`
      const canRequestSupplement = (row.original.investigationMethod === "PRODUCT_INSPECTION" || 
                                   row.original.investigationMethod === "SITE_VISIT_EVAL") &&
                                   row.original.investigationStatus === "COMPLETED" &&
                                   (row.original.evaluationResult === "SUPPLEMENT" || 
                                    row.original.evaluationResult === "SUPPLEMENT_REINSPECT" || 
                                    row.original.evaluationResult === "SUPPLEMENT_DOCUMENT")
      
      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-48">
            <DropdownMenuItem
              onSelect={() => {
                if (!canReviewPQ) return
                if (router) {
                  router.push(reviewUrl)
                } else if (typeof window !== "undefined") {
                  window.location.href = reviewUrl
                }
              }}
              disabled={!canReviewPQ}
            >
              <FileEdit className="mr-2 h-4 w-4" />
              검토
            </DropdownMenuItem>
            <DropdownMenuItem
              onSelect={() => {
                if (!isCanceled && row.original.investigationStatus === "QM_REVIEW_CONFIRMED") {
                  (setRowAction as any)?.({ type: "update-progress", row })
                }
              }}
              disabled={isCanceled || row.original.investigationStatus !== "QM_REVIEW_CONFIRMED"}
            >
              <Edit className="mr-2 h-4 w-4" />
              실사 진행 관리
            </DropdownMenuItem>
            
            <DropdownMenuItem
              onSelect={async () => {
                if (isCanceled || (row.original.investigationStatus !== "IN_PROGRESS" && row.original.investigationStatus !== "SUPPLEMENT_REQUIRED")) return
                // 구매자체평가일 경우 결과입력 비활성화
                if (row.original.investigationMethod === "PURCHASE_SELF_EVAL") {
                  return
                }
                // 방문/제품 평가 시: 벤더 회신 여부 확인 후 열기 (없으면 토스트)
                if (
                  row.original.investigationMethod === "PRODUCT_INSPECTION" ||
                  row.original.investigationMethod === "SITE_VISIT_EVAL"
                ) {
                  try {
                    const { getSiteVisitRequestAction } = await import("@/lib/site-visit/service")
                    const req = await getSiteVisitRequestAction(row.original.investigationId)
                    const canProceed = req.success && req.data && req.data.status === "VENDOR_SUBMITTED"
                    if (!canProceed) {
                      const { toast } = await import("sonner")
                      toast.error("협력업체 방문실사 정보 회신 전에는 결과 입력이 불가합니다.")
                      return
                    }
                  } catch {}
                }
                ;(setRowAction as any)?.({ type: "update-result", row })
              }}
              disabled={
                isCanceled ||
                (row.original.investigationStatus !== "IN_PROGRESS" && row.original.investigationStatus !== "SUPPLEMENT_REQUIRED") ||
                row.original.investigationMethod === "PURCHASE_SELF_EVAL"
              }
            >
              <Edit className="mr-2 h-4 w-4" />
              실사 결과 입력
            </DropdownMenuItem>
            
            {/* 실사 실시 확정 정보 버튼 - 제품검사평가 또는 방문실사평가인 경우 */}
            {(row.original.investigationMethod === "PRODUCT_INSPECTION" ||
              row.original.investigationMethod === "SITE_VISIT_EVAL") && (
              <DropdownMenuItem
                onSelect={() => {
                  (setRowAction as any)?.({ type: "vendor-info-view", row })
                }}
              >
                <FileText className="mr-2 h-4 w-4" />
                실사 실시 확정 정보
              </DropdownMenuItem>
            )}
            
            {canRequestSupplement && (
              <>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onSelect={() => {
                    openSupplementRequestDialog?.(
                      row.original.investigationId,
                      row.original.investigationMethod || "",
                      row.original.vendorName
                    )
                  }}
                  className="text-amber-600 focus:text-amber-600"
                >
                  <AlertTriangle className="mr-2 h-4 w-4" />
                  보완 요청
                </DropdownMenuItem>
              </>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 40,
  }

  // --------------------------------------------
  // 3) Vendor Name with click handler
  // --------------------------------------------
  const vendorNameColumn: ColumnDef<VendorInvestigationsViewWithContacts> = {
    accessorKey: "vendorName",
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="협력사명" />
    ),
    cell: ({ row }) => {
      const vendorId = row.original.vendorId
      const vendorName = row.getValue("vendorName") as string

      return (
        <Button
          variant="link"
          className="p-0 h-auto font-normal"
          onClick={() => openVendorDetailsModal?.(vendorId)}
        >
          {vendorName}
        </Button>
      )
    },
    meta: {
      excelHeader: "협력사명",
      group: "협력업체",
    },
  }

  // --------------------------------------------
  // 4) Build grouped columns from config
  // --------------------------------------------
  const groupMap: Record<string, ColumnDef<VendorInvestigationsViewWithContacts>[]> = {}

  vendorInvestigationsColumnsConfig.forEach((cfg) => {
    // Skip vendorName as we have a custom column for it
    if (cfg.id === "vendorName") {
      return
    }

    const groupName = cfg.group || "_noGroup"

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

    const childCol: ColumnDef<VendorInvestigationsViewWithContacts> = {
      accessorKey: cfg.id,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
      cell: ({ row, column }) => {
        const value = row.getValue(column.id)
        
        // Handle date fields
        if (
          column.id === "scheduledStartAt" ||
          column.id === "scheduledEndAt" ||
          column.id === "forecastedAt" ||
          column.id === "requestedAt" ||
          column.id === "confirmedAt" ||
          column.id === "completedAt" ||
          column.id === "createdAt" ||
          column.id === "updatedAt"
        ) {
          if (!value) return ""
          return formatDate(new Date(value as string), "KR")
        }

        // Handle status fields with badges
        if (column.id === "investigationStatus") {
          if (!value) return ""
          
          return (
            <Badge variant={getStatusVariant(value as string)}>
              {formatStatus(value as string)}
            </Badge>
          )
        }

        // Handle investigation method
        if (column.id === "investigationMethod") {
          if (!value) return ""
          
          return (
            <Badge variant={getMethodVariant(value as string)}>
              {formatEnumValue(value as string)}
            </Badge>
          )
        }

        // Handle evaluation result
        if (column.id === "evaluationResult") {
          if (!value) return ""
          
          return (
            <Badge variant={getResultVariant(value as string)}>
              {formatEnumValue(value as string)}
            </Badge>
          )
        }

        // Handle pqItems
        if (column.id === "pqItems") {
          if (!value) return <span className="text-muted-foreground">-</span>
            const items = typeof value === 'string' ? JSON.parse(value as string) : value;
            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>
              );
            }
        }

        // Handle IDs for pqSubmissionId (keeping for reference)
        if (column.id === "pqSubmissionId") {
          return value ? `#${value}` : ""
        }

        // Handle pqNumber
        if (column.id === "pqNumber") {
          return value ? (value as string) : <span className="text-muted-foreground">-</span>
        }

        // Handle file attachment status
        if (column.id === "hasAttachments") {
          return (
            <div className="flex items-center justify-center">
              {value ? (
                <Badge variant="default" className="text-xs">
                  📎 첨부
                </Badge>
              ) : (
                <span className="text-muted-foreground text-xs">-</span>
              )}
            </div>
          )
        }

        if (column.id === "requesterName") {
          if (!value && !row.original.requesterEmail) {
            return <span className="text-muted-foreground">미배정</span>
          }
          
          return (
            <div className="flex flex-col">
              <span>{value || "미배정"}</span>
              {row.original.requesterEmail ? (
                <span className="text-xs text-muted-foreground">{row.original.requesterEmail}</span>
              ) : null}
            </div>
          )
        }

        if (column.id === "qmManagerName") {
          if (!value && !row.original.qmManagerEmail) {
            return <span className="text-muted-foreground">미배정</span>
          }
          
          return (
            <div className="flex flex-col">
              <span>{value || "미배정"}</span>
              {row.original.qmManagerEmail ? (
                <span className="text-xs text-muted-foreground">{row.original.qmManagerEmail}</span>
              ) : null}
            </div>
          )
        }

        return value ?? ""
      },
    }

    groupMap[groupName].push(childCol)
  })

  // Insert custom vendorNameColumn in the 협력업체 group
  if (groupMap["협력업체"]) {
    groupMap["협력업체"].unshift(vendorNameColumn)
  }

  // Convert the groupMap into nested columns
  const nestedColumns: ColumnDef<VendorInvestigationsViewWithContacts>[] = []
  for (const [groupName, colDefs] of Object.entries(groupMap)) {
    if (groupName === "_noGroup") {
      nestedColumns.push(...colDefs)
    } else {
      nestedColumns.push({
        id: groupName,
        header: groupName as any,
        columns: colDefs,
      })
    }
  }

  // --------------------------------------------
  // 5) Return final columns array (simplified)
  // --------------------------------------------
  return [
    selectColumn,
    ...nestedColumns,
    actionsColumn,
  ]
}

// Helper functions for formatting
function formatStatus(status: string): string {
  switch (status) {
    case "PLANNED":
      return "계획됨"
    case "QM_REVIEW_CONFIRMED":
      return "QM 검토 확정"
    case "IN_PROGRESS":
      return "진행 중"
    case "COMPLETED":
      return "완료됨"
    case "CANCELED":
      return "취소됨"
    case "SUPPLEMENT_REQUIRED":
      return "보완 요구됨"
    case "RESULT_SENT":
      return "실사결과발송"
    default:
      return status
  }
}

function formatEnumValue(value: string): string {
  switch (value) {
    // Evaluation types
    case "PURCHASE_SELF_EVAL":
      return "구매자체평가"
    case "DOCUMENT_EVAL":
      return "서류평가"
    case "PRODUCT_INSPECTION":
      return "제품검사평가"
    case "SITE_VISIT_EVAL":
      return "방문실사평가"
    
    // Evaluation results
    case "APPROVED":
      return "승인"
    case "SUPPLEMENT":
      return "보완"
    case "SUPPLEMENT_REINSPECT":
      return "보완-재실사"
    case "SUPPLEMENT_DOCUMENT":
      return "보완-서류제출"
    case "REJECTED":
      return "불가"
    
    default:
      return value.replace(/_/g, " ").toLowerCase()
  }
}

function getStatusVariant(status: string): "default" | "secondary" | "outline" | "destructive" {
  switch (status) {
    case "PLANNED":
      return "secondary"
    case "IN_PROGRESS":
      return "default"
    case "COMPLETED":
      return "outline"
    case "CANCELED":
      return "destructive"
    case "SUPPLEMENT_REQUIRED":
      return "secondary"
    case "RESULT_SENT":
      return "default"
    default:
      return "default"
  }
}



function getResultVariant(result: string): "default" | "secondary" | "outline" | "destructive" {
  switch (result) {
    case "APPROVED":
      return "default"
    case "SUPPLEMENT":
      return "secondary"
    case "SUPPLEMENT_REINSPECT":
      return "secondary"
    case "SUPPLEMENT_DOCUMENT":
      return "secondary"
    case "REJECTED":
      return "destructive"
    default:
      return "outline"
  }
}