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

import { type ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { format } from "date-fns"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig"
import { DocumentStatusDialog } from "@/components/vendor-regular-registrations/document-status-dialog"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Eye, FileText, Ellipsis, Shield, Package } from "lucide-react"
import { toast } from "sonner"
import { useState } from "react"
import { SafetyQualificationUpdateDialog } from "./safety-qualification-update-dialog"
import { MajorItemsUpdateDialog } from "./major-items-update-dialog"


const statusLabels = {
  under_review: "검토중",
  approval_ready: "조건충족",
  in_review: "정규등록검토",
  completed: "등록완료",
  pending_approval: "장기미등록",
}

const statusColors = {
  under_review: "bg-blue-100 text-blue-800",
  approval_ready: "bg-emerald-100 text-emerald-800",
  in_review: "bg-orange-100 text-orange-800",
  completed: "bg-green-100 text-green-800",
  pending_approval: "bg-red-100 text-red-800",
}

export function getColumns(): ColumnDef<VendorRegularRegistration>[] {

  return [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && "indeterminate")
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
          className="translate-y-[2px]"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
          className="translate-y-[2px]"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: "status",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Status" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("status") as string
        return (
          <Badge
            variant="secondary"
            className={statusColors[status as keyof typeof statusColors]}
          >
            {statusLabels[status as keyof typeof statusLabels] || status}
          </Badge>
        )
      },
      filterFn: (row, id, value) => {
        return Array.isArray(value) && value.includes(row.getValue(id))
      },
    },
    {
      accessorKey: "potentialCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="잠재코드" />
      ),
      cell: ({ row }) => row.getValue("potentialCode") || "-",
    },
    {
      accessorKey: "businessNumber",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="사업자번호" />
      ),
    },
    {
      accessorKey: "companyName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="업체명" />
      ),
    },
    {
      accessorKey: "majorItems",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="주요품목" />
      ),
      cell: ({ row }) => {
        const majorItems = row.getValue("majorItems") as string
        try {
          const items = majorItems ? JSON.parse(majorItems) : []
          if (items.length === 0) return "-"
          
          // 첫 번째 아이템을 itemCode-itemName 형태로 표시
          const firstItem = items[0]
          let displayText = ""
          
          if (typeof firstItem === 'string') {
            displayText = firstItem
          } else if (typeof firstItem === 'object') {
            const code = firstItem.itemCode || firstItem.code || ""
            const name = firstItem.itemName || firstItem.name || firstItem.materialGroupName || ""
            if (code && name) {
              displayText = `${code}-${name}`
            } else {
              displayText = name || code || String(firstItem)
            }
          } else {
            displayText = String(firstItem)
          }
          
          // 나머지 개수 표시
          if (items.length > 1) {
            displayText += ` 외 ${items.length - 1}개`
          }
          
          return displayText
        } catch {
          return majorItems || "-"
        }
      },
    },
    {
      accessorKey: "establishmentDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="설립일자" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("establishmentDate") as string
        return date ? format(new Date(date), "yyyy.MM.dd") : "-"
      },
    },
    {
      accessorKey: "representative",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="대표자명" />
      ),
      cell: ({ row }) => row.getValue("representative") || "-",
    },
    {
      id: "documentStatus", 
      header: "진행현황",
      cell: ({ row }) => {
        const DocumentStatusCell = () => {
          const [documentDialogOpen, setDocumentDialogOpen] = useState(false)
          const registration = row.original
          
          // 문서 현황 계산 (국가별 요구사항 적용)
          const isForeign = registration.country !== 'KR'
          const requiredDocs = isForeign ? 4 : 3 // 외자: 4개(통장사본 포함), 내자: 3개(통장사본 제외)
          const submittedDocs = Object.values(registration.documentSubmissions).filter(Boolean).length
          const incompleteDocs = requiredDocs - submittedDocs
          
          // 기본계약 현황 계산
          const totalContracts = registration.basicContracts?.length || 0
          const completedContracts = registration.basicContracts?.filter(c => c.status === "VENDOR_SIGNED" || c.status === "COMPLETED").length || 0
          const incompleteContracts = totalContracts - completedContracts
          
          // 안전적격성 평가 현황
          const safetyCompleted = !!registration.safetyQualificationContent
          
          // 추가정보 현황
          const additionalInfoCompleted = registration.additionalInfo
          
          // 전체 미완료 항목 계산
          const totalIncomplete = 
            (incompleteDocs > 0 ? 1 : 0) +
            incompleteContracts +
            (!safetyCompleted ? 1 : 0) +
            (!additionalInfoCompleted ? 1 : 0)
          
          const isAllComplete = totalIncomplete === 0

          return (
            <>
              <div className="space-y-1">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setDocumentDialogOpen(true)}
                  className="h-auto p-1 text-left justify-start"
                >
                  <div className="space-y-0.5">
                    {isAllComplete ? (
                      <div className="text-xs text-green-600 font-medium">모든 항목 완료</div>
                    ) : (
                      <div className="text-xs text-orange-600 font-medium">
                        총 {totalIncomplete}건 미완료
                      </div>
                    )}
                  </div>
                </Button>
              </div>
              <DocumentStatusDialog
                open={documentDialogOpen}
                onOpenChange={setDocumentDialogOpen}
                registration={registration}
                isVendorUser={false}
              />
            </>
          )
        }
        
        return <DocumentStatusCell />
      },
    },
    {
      accessorKey: "registrationRequestDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록요청일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("registrationRequestDate") as string
        return date ? format(new Date(date), "yyyy.MM.dd") : "-"
      },
    },
    {
      accessorKey: "assignedDepartment",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="담당부서" />
      ),
      cell: ({ row }) => row.getValue("assignedDepartment") || "-",
    },
    {
      accessorKey: "assignedUser",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="담당자" />
      ),
      cell: ({ row }) => row.getValue("assignedUser") || "-",
    },
    {
      accessorKey: "remarks",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="비고" />
      ),
      cell: ({ row }) => row.getValue("remarks") || "-",
    },
    {
      id: "actions",
      cell: ({ row }) => {
        const ActionsDropdownCell = () => {
          const [safetyQualificationSheetOpen, setSafetyQualificationSheetOpen] = useState(false)
          const [majorItemsSheetOpen, setMajorItemsSheetOpen] = useState(false)
          const registration = row.original

          return (
            <>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    aria-label="Open menu"
                    variant="ghost"
                    className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
                  >
                    <Ellipsis className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-[160px]">
                  <DropdownMenuItem
                    onClick={() => setSafetyQualificationSheetOpen(true)}
                  >
                    <Shield className="mr-2 h-4 w-4" />
                    안전적격성 평가
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => setMajorItemsSheetOpen(true)}
                  >
                    <Package className="mr-2 h-4 w-4" />
                    주요품목 등록
                  </DropdownMenuItem>

                </DropdownMenuContent>
              </DropdownMenu>
              <SafetyQualificationUpdateDialog
                open={safetyQualificationSheetOpen}
                onOpenChange={setSafetyQualificationSheetOpen}
                registrationId={registration.id}
                vendorName={registration.companyName}
                currentContent={registration.safetyQualificationContent}
                onSuccess={() => {
                  // 페이지 새로고침 또는 데이터 리페치
                  window.location.reload()
                }}
              />
              <MajorItemsUpdateDialog
                open={majorItemsSheetOpen}
                onOpenChange={setMajorItemsSheetOpen}
                registrationId={registration.id}
                vendorName={registration.companyName}
                currentItems={registration.majorItems}
                onSuccess={() => {
                  // 페이지 새로고침 또는 데이터 리페치
                  window.location.reload()
                }}
              />

            </>
          )
        }

        return <ActionsDropdownCell />
      },
    },
  ]
}