summaryrefslogtreecommitdiff
path: root/lib/vendor-investigation/table/investigation-table-columns.tsx
blob: b5344a1ef7036f244491a96fec3ea7a00926bfcb (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
"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 } from "lucide-react"
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"

// Props for the column generator function
interface GetVendorInvestigationsColumnsProps {
  setRowAction?: React.Dispatch<
    React.SetStateAction<
      DataTableRowAction<VendorInvestigationsViewWithContacts> | null
    >
  >
  openVendorDetailsModal?: (vendorId: number) => 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,
}: 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 isCanceled = row.original.investigationStatus === "CANCELED"
      const isCompleted = row.original.investigationStatus === "COMPLETED"
      return (
        <Button
          variant="ghost"
          className="flex size-8 p-0 data-[state=open]:bg-muted"
          aria-label="실사 정보 수정"
          disabled={isCanceled}
          onClick={() => {
            if (!isCanceled || !isCompleted) {
              setRowAction?.({ type: "update", row })
            }
          }}
        >
          <Edit className="size-4" aria-hidden="true" />
        </Button>
      )
    },
    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 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>
              )}
            </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>
              )}
            </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,
        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 "IN_PROGRESS":
      return "진행 중"
    case "COMPLETED":
      return "완료됨"
    case "CANCELED":
      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 "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"
    default:
      return "default"
  }
}



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