summaryrefslogtreecommitdiff
path: root/lib/general-contracts/main/general-contracts-table-columns.tsx
blob: ce51b79149a6e3fb62837ceca060ab89cb6b3823 (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
"use client"

import * as React from "react"
import { type ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { 
  Eye, Edit, MoreHorizontal
} from "lucide-react"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { DataTableRowAction } from "@/types/table"
import { formatDate } from "@/lib/utils"
import { GENERAL_CONTRACT_TYPE_LABELS, GeneralContractType, isGeneralContractType } from "@/lib/general-contracts/types"

// 일반계약 리스트 아이템 타입 정의
export interface GeneralContractListItem {
  id: number
  contractNumber: string
  revision: number
  status: string
  category: string
  type: string
  executionMethod: string
  name: string
  contractSourceType?: string
  startDate: string
  endDate: string
  validityEndDate?: string
  contractScope?: string
  specificationType?: string
  specificationManualText?: string
  contractAmount?: number | string | null
  totalAmount?: number | string | null
  currency?: string
  registeredAt: string
  signedAt?: string
  linkedPoNumber?: string
  linkedRfqOrItb?: string
  linkedBidNumber?: string
  lastUpdatedAt: string
  notes?: string
  vendorId?: number
  vendorName?: string
  vendorCode?: string
  managerName?: string
  lastUpdatedByName?: string
}

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<GeneralContractListItem> | null>>
}

// 상태별 배지 색상
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case 'Draft':
      return 'outline'
    case 'Contract Accept Request':
      return 'default'
    case 'Complete the Contract':
      return 'default'
    case 'Reject to Accept Contract':
    case 'Contract Delete':
      return 'destructive'
    default:
      return 'outline'
  }
}

// 상태 텍스트 변환
const getStatusText = (status: string) => {
  switch (status) {
    case 'Draft':
      return '임시저장'
    case 'Contract Accept Request':
      return '계약승인요청'
    case 'Complete the Contract':
      return '계약체결'
    case 'Reject to Accept Contract':
      return '계약승인거절'
    case 'Contract Delete':
      return '계약폐기'
    case 'PCR Request':
      return 'PCR요청'
    case 'VO Request':
      return 'VO요청'
    case 'PCR Accept':
      return 'PCR승인'
    case 'PCR Reject':
      return 'PCR거절'
    default:
      return status
  }
}

// 계약구분 텍스트 변환
const getCategoryText = (category: string) => {
  switch (category) {
    case 'unit_price':
      return '단가계약'
    case 'general':
      return '일반계약'
    case 'sale':
      return '매각계약'
    default:
      return category
  }
}

// 계약종류 텍스트 변환
const getTypeText = (type: string) => {
  if (isGeneralContractType(type)) {
    return GENERAL_CONTRACT_TYPE_LABELS[type];
  }
  return type;
}

// 체결방식 텍스트 변환
const getExecutionMethodText = (method: string) => {
  switch (method) {
    case '전자계약':
      return '전자계약'
    case '오프라인계약':
      return '오프라인계약'
    default:
      return method
  }
}

// 업체선정방법 텍스트 변환
const getcontractSourceTypeText = (method?: string) => {
  if (!method) return '-'
  switch (method) {
    case 'estimate':
      return '견적'
    case 'bid':
      return '입찰'
    case 'manual':
      return '자체생성'
    default:
      return method
  }
}

// 금액 포맷팅
const formatCurrency = (amount: string | number | null | undefined, currency = 'KRW') => {
  if (!amount && amount !== 0) return '-'

  const numAmount = typeof amount === 'string' ? parseFloat(amount) : amount
  if (isNaN(numAmount)) return '-'

  // 통화 코드가 null이거나 유효하지 않은 경우 기본값 사용
  const safeCurrency = currency && typeof currency === 'string' ? currency : 'USD'

  return new Intl.NumberFormat('ko-KR', {
    style: 'currency',
    currency: safeCurrency,
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(numAmount)
}

export function getGeneralContractsColumns({ setRowAction }: GetColumnsProps): ColumnDef<GeneralContractListItem>[] {
  return [
    // ═══════════════════════════════════════════════════════════════
    // 선택 및 기본 정보
    // ═══════════════════════════════════════════════════════════════
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
          onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
          aria-label="select all"
          className="translate-y-0.5"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(v) => row.toggleSelected(!!v)}
          aria-label="select row"
          className="translate-y-0.5"
        />
      ),
      size: 40,
      enableSorting: false,
      enableHiding: false,
    },

    // ░░░ 계약번호 ░░░
    {
      accessorKey: "contractNumber",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약번호 (Rev.)" />,
      cell: ({ row }) => (
        <div className="font-mono text-sm">
          {row.original.contractNumber}
          {row.original.revision > 0 && (
            <span className="ml-1 text-xs text-muted-foreground">
              Rev.{row.original.revision}
            </span>
          )}
        </div>
      ),
      size: 150,
      meta: { excelHeader: "계약번호 (Rev.)" },
    },

    // ░░░ 계약상태 ░░░
    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약상태" />,
      cell: ({ row }) => (
        <Badge variant={getStatusBadgeVariant(row.original.status)}>
          {getStatusText(row.original.status)}
        </Badge>
      ),
      size: 120,
      meta: { excelHeader: "계약상태" },
    },

    // ░░░ 계약명 ░░░
    {
      accessorKey: "name",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약명" />,
      cell: ({ row }) => (
        <div className="truncate max-w-[200px]" title={row.original.name}>
          <Button
            variant="link"
            className="p-0 h-auto text-left justify-start"
            onClick={() => setRowAction({ row, type: "view" })}
          >
            {row.original.name}
          </Button>
        </div>
      ),
      size: 200,
      meta: { excelHeader: "계약명" },
    },

    // ═══════════════════════════════════════════════════════════════
    // 계약 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "계약 정보",
      columns: [
        {
          accessorKey: "category",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약구분" />,
          cell: ({ row }) => (
            <Badge variant="outline">
              {getCategoryText(row.original.category)}
            </Badge>
          ),
          size: 100,
          meta: { excelHeader: "계약구분" },
        },

        {
          accessorKey: "type",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약종류" />,
          cell: ({ row }) => (
            <Badge variant="secondary">
              {getTypeText(row.original.type)}
            </Badge>
          ),
          size: 120,
          meta: { excelHeader: "계약종류" },
        },

        {
          accessorKey: "executionMethod",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="체결방식" />,
          cell: ({ row }) => (
            <Badge variant="outline">
              {getExecutionMethodText(row.original.executionMethod)}
            </Badge>
          ),
          size: 100,
          meta: { excelHeader: "체결방식" },
        },

        {
          accessorKey: "contractSourceType",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="업체선정방법" />,
          cell: ({ row }) => (
            <Badge variant="outline">
              {getcontractSourceTypeText(row.original.contractSourceType)}
            </Badge>
          ),
          size: 200,
          meta: { excelHeader: "업체선정방법" },
        },
      ]
    },

    // ═══════════════════════════════════════════════════════════════
    // 협력업체 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "협력업체",
      columns: [
        {
          accessorKey: "vendorName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="협력업체명" />,
          cell: ({ row }) => (
            <div className="flex flex-col">
              <span className="font-medium">{row.original.vendorName || '-'}</span>
              <span className="text-xs text-muted-foreground">
                {row.original.vendorCode ? row.original.vendorCode : "-"}
              </span>
            </div>
          ),
          size: 150,
          meta: { excelHeader: "협력업체명" },
        },
      ]
    },

    // ═══════════════════════════════════════════════════════════════
    // 기간 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "계약기간",
      columns: [
        {
          id: "contractPeriod",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약기간" />,
          cell: ({ row }) => {
            const startDate = row.original.startDate
            const endDate = row.original.endDate
            
            if (!startDate || !endDate) return <span className="text-muted-foreground">-</span>
            
            // UI 표시용 KST 변환 (YYYY-MM-DD)
            const formatKstDate = (d: string | Date) => {
              const date = new Date(d)
              return new Date(date.getTime() + 9 * 60 * 60 * 1000).toISOString().slice(0, 10)
            }

            const formattedStart = formatKstDate(startDate)
            const formattedEnd = formatKstDate(endDate)
            
            const now = new Date()
            const startObj = new Date(startDate)
            const endObj = new Date(endDate)
            
            // 종료일의 경우 23:59:59까지 유효하다고 가정하거나, 단순히 날짜 비교
            const isActive = now >= startObj && now <= new Date(endObj.getTime() + 24 * 60 * 60 * 1000 - 1)
            const isExpired = now > new Date(endObj.getTime() + 24 * 60 * 60 * 1000 - 1)
            
            return (
              <div className="text-xs">
                <div className={`${isActive ? 'text-green-600 font-medium' : isExpired ? 'text-red-600' : 'text-gray-600'}`}>
                  {formattedStart} ~ {formattedEnd}
                </div>
                {isActive && (
                  <Badge variant="default" className="text-xs mt-1">진행중</Badge>
                )}
                {isExpired && (
                  <Badge variant="destructive" className="text-xs mt-1">만료</Badge>
                )}
              </div>
            )
          },
          size: 200,
          meta: { excelHeader: "계약기간" },
        },
      ]
    },

    // ═══════════════════════════════════════════════════════════════
    // 금액 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "금액 정보",
      columns: [
        {
          accessorKey: "currency",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="통화" />,
          cell: ({ row }) => (
            <span className="font-mono text-sm">{row.original.currency || 'KRW'}</span>
          ),
          size: 60,
          meta: { excelHeader: "통화" },
        },

        {
          accessorKey: "contractAmount",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약금액" />,
          cell: ({ row }) => (
            <span className="text-sm font-medium">
              {formatCurrency(row.original.contractAmount, row.original.currency)}
            </span>
          ),
          size: 200,
          meta: { excelHeader: "계약금액" },
        },
      ]
    },

    // ═══════════════════════════════════════════════════════════════
    // 담당자 및 관리 정보
    // ═══════════════════════════════════════════════════════════════
    {
      header: "관리 정보",
      columns: [
        {
          accessorKey: "managerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약담당자" />,
          cell: ({ row }) => (
            <div className="truncate max-w-[100px]" title={row.original.managerName || ''}>
              {row.original.managerName || '-'}
            </div>
          ),
          size: 100,
          meta: { excelHeader: "계약담당자" },
        },

        {
          accessorKey: "registeredAt",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약등록일" />,
          cell: ({ row }) => (
            <span className="text-sm">{formatDate(row.original.registeredAt, "KR")}</span>
          ),
          size: 100,
          meta: { excelHeader: "계약등록일" },
        },

        {
          accessorKey: "signedAt",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약체결일" />,
          cell: ({ row }) => (
            <span className="text-sm">
              {row.original.signedAt ? formatDate(row.original.signedAt, "KR") : '-'}
            </span>
          ),
          size: 100,
          meta: { excelHeader: "계약체결일" },
        },

        {
          accessorKey: "linkedPoNumber",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="연계 PO번호" />,
          cell: ({ row }) => (
            <span className="font-mono text-sm">{row.original.linkedPoNumber || '-'}</span>
          ),
          size: 140,
          meta: { excelHeader: "연계 PO번호" },
        },

        {
          accessorKey: "lastUpdatedAt",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종수정일" />,
          cell: ({ row }) => (
            <span className="text-sm">{formatDate(row.original.lastUpdatedAt, "KR")}</span>
          ),
          size: 100,
          meta: { excelHeader: "최종수정일" },
        },

        {
          accessorKey: "lastUpdatedByName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종수정자" />,
          cell: ({ row }) => (
            <span className="text-sm">{row.original.lastUpdatedByName || '-'}</span>
          ),
          size: 100,
          meta: { excelHeader: "최종수정자" },
        },
      ]
    },

    // ░░░ 비고 ░░░
    {
      accessorKey: "notes",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="비고" />,
      cell: ({ row }) => (
        <div className="truncate max-w-[150px]" title={row.original.notes || ''}>
          {row.original.notes || '-'}
        </div>
      ),
      size: 150,
      meta: { excelHeader: "비고" },
    },

    // ═══════════════════════════════════════════════════════════════
    // 액션
    // ═══════════════════════════════════════════════════════════════
    {
      id: "actions",
      header: "액션",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">메뉴 열기</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            {row.original.status !== 'Contract Delete' && (
              <>
                <DropdownMenuItem onClick={() => setRowAction({ row, type: "view" })}>
                  <Eye className="mr-2 h-4 w-4" />
                  상세보기
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setRowAction({ row, type: "update" })}>
                  <Edit className="mr-2 h-4 w-4" />
                  수정
                </DropdownMenuItem>
              </>
            )}
          </DropdownMenuContent>
        </DropdownMenu>
      ),
      size: 50,
      enableSorting: false,
      enableHiding: false,
    },
  ]
}