summaryrefslogtreecommitdiff
path: root/components/form-data/form-data-table-columns.tsx
blob: a1fbcae1c2049ed9f0e7c57f61561a8ea8095633 (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
import type { ColumnDef, Row } from "@tanstack/react-table";
import { ClientDataTableColumnHeaderSimple } from "../client-data-table/data-table-column-simple-header";
import { Button } from "@/components/ui/button";
import { Ellipsis } from "lucide-react";
import { formatDate } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { toast } from 'sonner';
/** row 액션 관련 타입 */
export interface DataTableRowAction<TData> {
  row: Row<TData>;
  type: "open" | "edit" | "update";
}

/** 컬럼 타입 (필요에 따라 확장) */
export type ColumnType = "STRING" | "NUMBER" | "LIST";

export interface DataTableColumnJSON {
  key: string;
  /** 실제 Excel 등에서 구분용으로 쓰이는 label (고정) */
  label: string;

  /** UI 표시용 label (예: 단위를 함께 표시) */
  displayLabel?: string;

  type: ColumnType;
  options?: string[];
  uom?: string;
  uomId?: string;
  shi?: boolean;

}
/**
 * getColumns 함수에 필요한 props
 * - TData: 테이블에 표시할 행(Row)의 타입
 */
interface GetColumnsProps<TData> {
  columnsJSON: DataTableColumnJSON[];
  setRowAction: React.Dispatch<
    React.SetStateAction<DataTableRowAction<TData> | null>
  >;
  setReportData: React.Dispatch<React.SetStateAction<{ [key: string]: any }[]>>;
  tempCount: number;
}

/**
 * getColumns 함수
 * 1) columnsJSON 배열을 순회하면서 accessorKey / header / cell 등을 설정
 * 2) 마지막에 "Action" 칼럼(예: update 버튼) 추가
 */
export function getColumns<TData extends object>({
  columnsJSON,
  setRowAction,
  setReportData,
  tempCount,
}: GetColumnsProps<TData>): ColumnDef<TData>[] {
  // (1) 기본 컬럼들
  const baseColumns: ColumnDef<TData>[] = columnsJSON.map((col) => ({
    accessorKey: col.key,
    header: ({ column }) => (
      <ClientDataTableColumnHeaderSimple
        column={column}
        title={col.displayLabel || col.label}
      />
    ),

    meta: {
      excelHeader: col.label,
      minWidth: 80,
      paddingFactor: 1.2,
      maxWidth: col.key === "TAG_NO" ? 120 : 150,
      isReadOnly: col.shi === true,  // shi 정보를 메타데이터에 저장
    },
    // (2) 실제 셀(cell) 렌더링: type에 따라 분기 가능
    cell: ({ row }) => {
      const cellValue = row.getValue(col.key);
      
      // shi 속성이 true인 경우 적용할 스타일
      const isReadOnly = col.shi === true;
      const readOnlyClass = isReadOnly ? "read-only-cell" : "";
      
      // 읽기 전용 셀의 스타일 (인라인 스타일과 클래스 동시 적용)
      const cellStyle = isReadOnly 
        ? { backgroundColor: '#f5f5f5', color: '#666', cursor: 'not-allowed' } 
        : {};

      // 데이터 타입별 처리
      switch (col.type) {
        case "NUMBER":
          // 예: number인 경우 콤마 등 표시
          return (
            <div 
              className={readOnlyClass} 
              style={cellStyle} 
              title={isReadOnly ? "읽기 전용 필드입니다" : ""}
            >
              {cellValue ? Number(cellValue).toLocaleString() : ""}
            </div>
          );

        // case "date":
        //   // 예: 날짜 포맷팅
        //   // 실제론 dayjs / date-fns 등으로 포맷
        //   if (!cellValue) return <div></div>
        //   const dateString = cellValue as string
        //   if (!dateString) return null
        //   return formatDate(new Date(dateString))

        case "LIST":
          // 예: select인 경우 label만 표시
          return (
            <div 
              className={readOnlyClass} 
              style={cellStyle}
              title={isReadOnly ? "읽기 전용 필드입니다" : ""}
            >
              {String(cellValue ?? "")}
            </div>
          );

        case "STRING":
        default:
          return (
            <div 
              className={readOnlyClass} 
              style={cellStyle}
              title={isReadOnly ? "읽기 전용 필드입니다" : ""}
            >
              {String(cellValue ?? "")}
            </div>
          );
      }
    },
  }));

  // (3) 액션 칼럼 - update 버튼 예시
  const actionColumn: ColumnDef<TData> = {
    id: "update",
    header: "",
    cell: ({ row }) => (
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            aria-label="Open menu"
            variant="ghost"
            className="flex size-8 p-0 data-[state=open]:bg-muted"
          >
            <Ellipsis className="size-4" aria-hidden="true" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-40">
          <DropdownMenuItem
            onSelect={() => {
              // 행에 있는 모든 필드가 읽기 전용인지 확인할 수도 있습니다 (선택 사항)
              // const allColumnsReadOnly = columnsJSON.every(col => col.shi === true);
              // if(allColumnsReadOnly) {
              //   toast.info("이 항목은 읽기 전용입니다.");
              //   return;
              // }
              setRowAction({ row, type: "update" });
            }}
          >
            Edit
          </DropdownMenuItem>
          <DropdownMenuItem
            onSelect={() => {
              if(tempCount > 0){
              const { original } = row;
              setReportData([original]);
            } else {
              toast.error("업로드된 Template File이 없습니다.");
            }
            }}
          >
            Create Document
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    ),
    minSize: 50,
    enablePinning: true,
  };

  // (4) 최종 반환
  return [...baseColumns, actionColumn];
}