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

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { InfoIcon, PenIcon } from "lucide-react"

import { formatDate } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { poColumnsConfig } from "@/config/poColumnsConfig"
import { ContractDetail } from "@/db/schema/contract"

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

/**
 * tanstack table column definitions with nested headers
 */
export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ContractDetail>[] {
  // ----------------------------------------------------------------
  // 1) select column (checkbox) - if needed
  // ----------------------------------------------------------------

  // ----------------------------------------------------------------
  // 2) actions column (buttons for item info and signature request)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<ContractDetail> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      // Check if this contract already has a signature envelope
      const hasSignature = row.original.hasSignature;
      
      return (
        <div className="flex items-center space-x-1">
          {/* Item Info Button */}
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => setRowAction({ row, type: "items" })}
                >
                  <InfoIcon className="h-4 w-4" aria-hidden="true" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>
                View Item Info
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
          
          {/* Signature Request Button - only show if no signature exists */}
          {!hasSignature && (
            <TooltipProvider>
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    onClick={() => setRowAction({ row, type: "signature" })}
                  >
                    <PenIcon className="h-4 w-4" aria-hidden="true" />
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  Request Electronic Signature
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}
        </div>
      );
    },
    size: 80, // Increased width to accommodate both buttons
  };

  // ----------------------------------------------------------------
  // 3) Regular columns grouped by group name
  // ----------------------------------------------------------------
  // 3-1) groupMap: { [groupName]: ColumnDef<ContractDetail>[] }
  const groupMap: Record<string, ColumnDef<ContractDetail>[]> = {};

 // (1) JSON config를 읽어서 ColumnDef를 생성하는 부분 (일부 발췌)
poColumnsConfig.forEach((cfg) => {
  const groupName = cfg.group || "_noGroup"
  if (!groupMap[groupName]) {
    groupMap[groupName] = []
  }

  let childCol: ColumnDef<ContractDetail>

  if (cfg.type === "custom" && cfg.customType === "esignStatus") {
    // ========================================
    // (2) 전자서명 전용 커스텀 컬럼
    // ========================================
    childCol = {
      id: cfg.id,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      // 여기서 row.original.envelopes 등 활용하여 최신 전자서명 상태 표시
      cell: ({ row }) => {
        const data = row.original
        if (!data.envelopes || data.envelopes.length === 0) {
          return (
            <div className="text-sm text-gray-500">
              No E-Sign
            </div>
          )
        }

        // envelopes가 여러 개 있으면 최신(가장 최근 updatedAt) 가져오기
        const sorted = [...data.envelopes].sort((a, b) => {
          const dateA = new Date(a.updatedAt)
          const dateB = new Date(b.updatedAt)
          return dateB.getTime() - dateA.getTime()
        })
        const latest = sorted[0]

        // 상태에 따라 다른 UI 색상/아이콘
        const status = latest.envelopeStatus // "sent", "completed", ...
        const colorMap: Record<string, string> = {
          completed: "text-green-600",
          sent: "text-blue-600",
          voided: "text-red-600",
          // ...
        }
        const colorClass = colorMap[status] || "text-gray-700"

        return (
          <Button
            onClick={() => {
              // 다이얼로그 열기 등
              // 예: setRowAction({ row, type: "esign-detail" })
              setRowAction({ row, type: "esign-detail" })
            }}
            className={`underline underline-offset-2 ${colorClass}`}
          >
            {status}
          </Button>
        )
      },
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
    }
  } else {
    // ========================================
    // (3) 일반 컬럼 (type: text/date/number 등)
    // ========================================
    childCol = {
      accessorKey: cfg.id,
      enableResizing: true,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
      cell: ({ row, cell }) => {
        // 날짜 포맷, 숫자 포맷 등 처리
        if (cfg.type === "date") {
          const dateVal = cell.getValue() as Date
          return formatDate(dateVal)
        }
        // ...
        return row.getValue(cfg.id) ?? ""
      },
    }
  }

  groupMap[groupName].push(childCol)
})

  // ----------------------------------------------------------------
  // 3-2) Create actual parent columns (groups) from the groupMap
  // ----------------------------------------------------------------
  const nestedColumns: ColumnDef<ContractDetail>[] = [];

  // Order can be fixed by pre-defining group order or sorting
  // Here we just use Object.entries order
  Object.entries(groupMap).forEach(([groupName, colDefs]) => {
    if (groupName === "_noGroup") {
      // No group → Add as top-level columns
      nestedColumns.push(...colDefs);
    } else {
      // Parent column
      nestedColumns.push({
        id: groupName,
        header: groupName, // "Basic Info", "Metadata", etc.
        columns: colDefs,
      });
    }
  });

  // ----------------------------------------------------------------
  // 4) Final column array: nestedColumns + actionsColumn
  // ----------------------------------------------------------------
  return [
    ...nestedColumns,
    actionsColumn,
  ];
}