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

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import {  Paperclip } from "lucide-react"
import { toast } from "sonner"

import { getErrorMessage } from "@/lib/handle-error"
import { formatDate, formatDateTime } from "@/lib/utils"
import { downloadFile } from "@/lib/file-download"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { basicContractColumnsConfig, basicContractVendorColumnsConfig } from "@/config/basicContractColumnsConfig"
import { BasicContractView } from "@/db/schema"

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<BasicContractView> | null>>
  locale?: string
  t: (key: string) => string // 번역 함수
}

// 기본 번역값들 (fallback)
const fallbackTranslations = {
  ko: {
    download: "다운로드",
    selectAll: "전체 선택", 
    selectRow: "행 선택",
    fileInfoMissing: "파일 정보가 없습니다.",
    fileDownloadError: "파일 다운로드 중 오류가 발생했습니다.",
    statusValues: {
      PENDING: "서명대기",
      COMPLETED: "서명완료"
    }
  },
  en: {
    download: "Download",
    selectAll: "Select all",
    selectRow: "Select row", 
    fileInfoMissing: "File information is missing.",
    fileDownloadError: "An error occurred while downloading the file.",
    statusValues: {
      PENDING: "Pending",
      COMPLETED: "Completed"
    }
  }
};

// 안전한 번역 함수
const safeTranslate = (t: (key: string) => string, key: string, locale: string = 'ko', fallback?: string): string => {
  try {
    const translated = t(key);
    // 번역 키가 그대로 반환되는 경우 (번역 실패) fallback 사용
    if (translated === key && fallback) {
      return fallback;
    }
    return translated || fallback || key;
  } catch (error) {
    console.warn(`Translation failed for key: ${key}`, error);
    return fallback || key;
  }
};

/**
 * 파일 다운로드 함수
 */
const handleFileDownload = async (
  filePath: string | null, 
  fileName: string | null,
  t: (key: string) => string,
  locale: string = 'ko'
) => {
  const fallback = fallbackTranslations[locale as keyof typeof fallbackTranslations] || fallbackTranslations.ko;
  
  if (!filePath || !fileName) {
    const message = safeTranslate(t, "basicContracts.fileInfoMissing", locale, fallback.fileInfoMissing);
    toast.error(message);
    return;
  }

  try {
    // /api/files/ 엔드포인트를 통한 안전한 다운로드
    const apiFilePath = `/api/files/${filePath.startsWith('/') ? filePath.substring(1) : filePath}`;
    
    const result = await downloadFile(apiFilePath, fileName, {
      action: 'download',
      showToast: true
    });

    if (!result.success) {
      console.error("파일 다운로드 실패:", result.error);
    }
  } catch (error) {
    console.error("파일 다운로드 오류:", error);
    const message = safeTranslate(t, "basicContracts.fileDownloadError", locale, fallback.fileDownloadError);
    toast.error(message);
  }
};

/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction, locale = 'ko', t }: GetColumnsProps): ColumnDef<BasicContractView>[] {
  const fallback = fallbackTranslations[locale as keyof typeof fallbackTranslations] || fallbackTranslations.ko;
  
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<BasicContractView> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label={safeTranslate(t, "basicContracts.selectAll", locale, fallback.selectAll)}
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label={safeTranslate(t, "basicContracts.selectRow", locale, fallback.selectRow)}
        className="translate-y-0.5"
      />
    ),
    maxSize: 30,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) 파일 다운로드 컬럼 (아이콘)
  // ----------------------------------------------------------------
  const downloadColumn: ColumnDef<BasicContractView> = {
    id: "download",
    header: "",
    cell: ({ row }) => {
      const contract = row.original;
      // PENDING 상태일 때는 원본 PDF 파일 (signedFilePath), COMPLETED일 때는 서명된 파일 (signedFilePath)
      const filePath = contract.signedFilePath;
      const fileName = contract.signedFileName;
      const downloadText = safeTranslate(t, "basicContracts.download", locale, fallback.download);
      
      return (
        <Button
          variant="ghost"
          size="icon"
          onClick={() => handleFileDownload(filePath, fileName, t, locale)}
          title={`${fileName} ${downloadText}`}
          className="hover:bg-muted"
          disabled={!filePath || !fileName}
        >
          <Paperclip className="h-4 w-4" />
          <span className="sr-only">{downloadText}</span>
        </Button>
      );
    },
    maxSize: 30,
    enableSorting: false,
  }

  // ----------------------------------------------------------------
  // 4) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
  // ----------------------------------------------------------------
  // 4-1) groupMap: { [groupName]: ColumnDef<BasicContractView>[] }
  const groupMap: Record<string, ColumnDef<BasicContractView>[]> = {}

  basicContractVendorColumnsConfig.forEach((cfg) => {
    // 만약 group가 없으면 "_noGroup" 처리
    const groupName = cfg.group || "_noGroup"

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

    // child column 정의
    const childCol: ColumnDef<BasicContractView> = {
      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.id === "createdAt" || cfg.id === "updatedAt" || cfg.id === "completedAt") {
          const dateVal = cell.getValue() as Date
          return formatDateTime(dateVal, locale)
        }
        
        // Status 컬럼에 Badge 적용 - 다국어 적용
        if (cfg.id === "status") {
          const status = row.getValue(cfg.id) as string
          const isPending = status === "PENDING"
          const statusText = safeTranslate(
            t, 
            `basicContracts.statusValues.${status}`, 
            locale, 
            fallback.statusValues[status as keyof typeof fallback.statusValues] || status
          );
          
          return (
            <Badge 
              variant={!isPending ? "default" : "secondary"}
            >
              {statusText}
            </Badge>
          )
        }

        // 나머지 컬럼은 그대로 값 표시
        return row.getValue(cfg.id) ?? ""
      },
      minSize: 80,
    }

    groupMap[groupName].push(childCol)
  })

  const contractTypeColumn: ColumnDef<BasicContractView> = {
    id: "contractType",
    accessorFn: (row) => {
      // 계약 유형 판별 로직
      if (row.generalContractId) return "contract";
      if (row.rfqCompanyId) return "quotation";
      if (row.biddingCompanyId) return "bidding";
      return "general";
    },
    header: ({ column }) => (
      <DataTableColumnHeaderSimple 
        column={column} 
        title={locale === 'ko' ? "계약 소스" : "Contract Source"} 
      />
    ),
    cell: ({ getValue }) => {
      const type = getValue() as string;
      
      // 타입별 표시 텍스트와 스타일 정의
      const typeConfig = {
        general: { 
          label: locale === 'ko' ? '일반' : 'General',
          variant: 'outline' as const
        },
        quotation: { 
          label: locale === 'ko' ? '견적' : 'Quotation',
          variant: 'secondary' as const
        },
        contract: { 
          label: locale === 'ko' ? '계약' : 'Contract',
          variant: 'default' as const
        },
        bidding: { 
          label: locale === 'ko' ? '입찰' : 'Bidding',
          variant: 'destructive' as const
        }
      };
      
      const config = typeConfig[type as keyof typeof typeConfig] || typeConfig.general;
      
      return (
        <Badge variant={config.variant}>
          {config.label}
        </Badge>
      );
    },
    enableSorting: true,
    enableHiding: true,
    minSize: 80,
  };

  // ----------------------------------------------------------------
  // 4-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기
  // ----------------------------------------------------------------
  const nestedColumns: ColumnDef<BasicContractView>[] = []

  // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함
  // 여기서는 그냥 Object.entries 순서
  Object.entries(groupMap).forEach(([groupName, colDefs]) => {
    if (groupName === "_noGroup") {
      // 그룹 없음 → 그냥 최상위 레벨 컬럼
      nestedColumns.push(...colDefs)
    } else {
      // 상위 컬럼 - 그룹명 다국어 적용
      const translatedGroupName = t(`basicContracts.groups.${groupName}`) || groupName;
      nestedColumns.push({
        id: groupName,
        header: translatedGroupName,
        columns: colDefs,
      })
    }
  })

  // ----------------------------------------------------------------
  // 5) 최종 컬럼 배열: select, download, nestedColumns, actions
  // ----------------------------------------------------------------
  return [
    selectColumn,
    downloadColumn, // 다운로드 컬럼 추가
    contractTypeColumn,
    ...nestedColumns,
  ]
}