summaryrefslogtreecommitdiff
path: root/lib/pcr/table/pcr-table.tsx
blob: 6538e820c84fdc6b13319cd79b39bf28c8e857c1 (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
"use client"

import * as React from "react"
import { useSearchParams } from "next/navigation"
import type {
  DataTableRowAction,
} from "@/types/table"
import {
  ResizablePanelGroup,
  ResizablePanel,
  ResizableHandle,
} from "@/components/ui/resizable"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { getColumns } from "./pcr-table-column"
import { useEffect, useMemo } from "react"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { PcrTableToolbarActions } from "./pcr-table-toolbar-actions"
import { getPcrPoList } from "@/lib/pcr/service"
import { useTablePresets } from "@/components/data-table/use-table-presets"
import { PcrDetailTables } from "./detail-table/pcr-detail-table"
import { EditPcrSheet } from "./edit-pcr-sheet"
import { cn } from "@/lib/utils"
import { PcrPoData } from "@/lib/pcr/types"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
} from "@/types/table"

interface PcrTableProps {
  tableData: Awaited<ReturnType<typeof getPcrPoList>>
  className?: string;
  calculatedHeight?: string;
  isEvcpPage?: boolean; // EvcP 페이지인지 여부
  isPartnersPage?: boolean; // Partners 페이지인지 여부
  currentVendorId?: number; // Partners 페이지에서 현재 사용자의 vendorId
}

export function PcrTable({
  tableData,
  className,
  calculatedHeight,
  isEvcpPage = false,
  isPartnersPage = false,
  currentVendorId,
}: PcrTableProps) {
  const searchParams = useSearchParams()


  // 선택된 PCR_PO 상태
  const [selectedPcrPo, setSelectedPcrPo] = React.useState<PcrPoData | null>(null)

  // Edit sheet 상태
  const [editSheetOpen, setEditSheetOpen] = React.useState(false)
  const [editingPcr, setEditingPcr] = React.useState<PcrPoData | null>(null)


  // 패널 collapse 상태
  const [panelHeight, setPanelHeight] = React.useState<number>(55)

  // RFQListTable 컴포넌트 내부의 rowAction 처리 부분 수정
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<PcrPoData> | null>(null)

  // 고정 높이 설정을 위한 상수 (실제 측정값으로 조정 필요)
  const LAYOUT_HEADER_HEIGHT = 64 // Layout Header 높이
  const LAYOUT_FOOTER_HEIGHT = 60 // Layout Footer 높이 (있다면 실제 값)
  const LOCAL_HEADER_HEIGHT = 72 // 로컬 헤더 바 높이 (p-4 + border)

  console.log(calculatedHeight)

  // 테이블 컨텐츠 높이 - 전달받은 높이에서 로컬 헤더 제외
  const FIXED_TABLE_HEIGHT = calculatedHeight
    ? `calc(${calculatedHeight} - ${LOCAL_HEADER_HEIGHT}px)`
    : `calc(100vh - ${LAYOUT_HEADER_HEIGHT + LAYOUT_FOOTER_HEIGHT + LOCAL_HEADER_HEIGHT+76}px)` // fallback

  // 데이터는 props로 직접 전달받음

  // 초기 설정 정의
  const initialSettings = React.useMemo(() => ({
    page: parseInt(searchParams?.get('page') || '1'),
    perPage: parseInt(searchParams?.get('perPage') || '10'),
    sort: searchParams?.get('sort') ? JSON.parse(searchParams.get('sort')!) : [{ id: "createdAt", desc: true }],
    columnVisibility: {},
    columnOrder: [],
    pinnedColumns: { left: [], right: [] },
    filters: [],
    joinOperator: "and" as const,
    basicFilters: [],
    basicJoinOperator: "and" as const,
    search: "",
  }), [searchParams])

  // DB 기반 프리셋 훅 사용
  const {
    getCurrentSettings,
  } = useTablePresets<PcrPoData>('pcr-po-table', initialSettings)


  // 행 액션 처리
  useEffect(() => {
    if (rowAction) {
      switch (rowAction.type) {
        case "select":
          // 객체 참조 안정화를 위해 필요한 필드만 추출
          const pcrPoData = rowAction.row.original;
          console.log("Row action select - PCR_PO 데이터:", pcrPoData)
        setSelectedPcrPo({
          id: pcrPoData.id,
          no: pcrPoData.no,
          pcrApprovalStatus: pcrPoData.pcrApprovalStatus,
          changeType: pcrPoData.changeType,
          details: pcrPoData.details || undefined,
          project: pcrPoData.project || undefined,
          pcrRequestDate: pcrPoData.pcrRequestDate,
          poContractNumber: pcrPoData.poContractNumber,
          revItemNumber: pcrPoData.revItemNumber || undefined,
          purchaseContractManager: pcrPoData.purchaseContractManager || undefined,
          pcrCreator: pcrPoData.pcrCreator || undefined,
          poContractAmountBefore: pcrPoData.poContractAmountBefore ? Number(pcrPoData.poContractAmountBefore) : undefined as number | undefined,
          poContractAmountAfter: pcrPoData.poContractAmountAfter ? Number(pcrPoData.poContractAmountAfter) : undefined as number | undefined,
          contractCurrency: pcrPoData.contractCurrency || "KRW",
          pcrReason: pcrPoData.pcrReason || undefined,
          detailsReason: pcrPoData.detailsReason || undefined,
          rejectionReason: pcrPoData.rejectionReason || undefined,
          pcrResponseDate: pcrPoData.pcrResponseDate || undefined,
          vendorId: pcrPoData.vendorId || undefined,
          vendorName: pcrPoData.vendorName || undefined,
          createdBy: pcrPoData.createdBy,
          updatedBy: pcrPoData.updatedBy,
          createdAt: pcrPoData.createdAt,
          updatedAt: pcrPoData.updatedAt,
        });
          break;
        case "update":
          // PCR_PO 수정 시트 열기
          setEditingPcr(rowAction.row.original)
          setEditSheetOpen(true)
          break;
        case "delete":
          console.log("Delete PCR_PO:", rowAction.row.original)
          break;
      }
      setRowAction(null)
    }
  }, [rowAction])

  const columns = React.useMemo(
    () => getColumns({
      setRowAction,
      isEvcpPage,
    }),
    [setRowAction, isEvcpPage]
  )

  // 필터 필드 정의
  const filterFields: DataTableFilterField<PcrPoData>[] = []

  const advancedFilterFields: DataTableAdvancedFilterField<PcrPoData>[] = [
    {
      id: "pcrApprovalStatus",
      label: "PCR 승인상태",
      type: "multi-select",
      options: [
        { label: "승인대기", value: "승인대기" },
        { label: "승인완료", value: "승인완료" },
        { label: "거절", value: "거절" },
        { label: "취소", value: "취소" },
      ],
    },
    {
      id: "changeType",
      label: "변경구분",
      type: "multi-select",
      options: [
        { label: "수량변경", value: "QUANTITY" },
        { label: "금액변경", value: "AMOUNT" },
        { label: "기간변경", value: "PERIOD" },
        { label: "품목변경", value: "ITEM" },
        { label: "기타", value: "OTHER" },
      ],
    },
    {
      id: "poContractNumber",
      label: "PO/계약번호",
      type: "text",
    },
    {
      id: "project",
      label: "프로젝트",
      type: "text",
    },
    ...(isEvcpPage ? [{
      id: "vendorName" as const,
      label: "협력업체",
      type: "text" as const,
    }] : []),
    {
      id: "pcrRequestDate",
      label: "PCR 요청일자",
      type: "date",
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
  ]


  // 현재 설정 가져오기
  const currentSettings = useMemo(() => {
    return getCurrentSettings()
  }, [getCurrentSettings])

  // useDataTable 초기 상태 설정
  const initialState = useMemo(() => {
    return {
      sorting: initialSettings.sort.filter((sortItem: any) => {
        const columnExists = columns.some((col: any) => col.accessorKey === sortItem.id)
        return columnExists
      }) as any,
      columnVisibility: currentSettings.columnVisibility,
      columnPinning: currentSettings.pinnedColumns,
    }
  }, [currentSettings, initialSettings.sort, columns])

  // useDataTable 훅 설정
  const { table } = useDataTable({
    data: tableData?.data || [],
    columns: columns as any,
    pageCount: tableData?.pageCount || 0,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState,
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
    columnResizeMode: "onEnd",
  })

  // 선택된 행들 감시하여 selectedPcrPo 설정 (checkbox selection)
  React.useEffect(() => {
    if (table) {
      const selectedRows = table.getSelectedRowModel().rows
      if (selectedRows.length === 1) {
        const pcrPoData = selectedRows[0].original
        const selectedData = {
          id: pcrPoData.id,
          no: (pcrPoData as any).no,
          pcrApprovalStatus: pcrPoData.pcrApprovalStatus || "",
          changeType: pcrPoData.changeType || "",
          details: pcrPoData.details || undefined,
          project: pcrPoData.project || undefined,
          pcrRequestDate: pcrPoData.pcrRequestDate,
          poContractNumber: pcrPoData.poContractNumber,
          revItemNumber: pcrPoData.revItemNumber || undefined,
          purchaseContractManager: pcrPoData.purchaseContractManager || undefined,
          pcrCreator: pcrPoData.pcrCreator || undefined,
          poContractAmountBefore: pcrPoData.poContractAmountBefore ? Number(pcrPoData.poContractAmountBefore) : undefined as number | undefined,
          poContractAmountAfter: pcrPoData.poContractAmountAfter ? Number(pcrPoData.poContractAmountAfter) : undefined as number | undefined,
          contractCurrency: pcrPoData.contractCurrency || "KRW",
          pcrReason: pcrPoData.pcrReason || undefined,
          detailsReason: pcrPoData.detailsReason || undefined,
          rejectionReason: pcrPoData.rejectionReason || undefined,
          pcrResponseDate: pcrPoData.pcrResponseDate || undefined,
          vendorId: pcrPoData.vendorId || undefined,
          vendorName: pcrPoData.vendorName || undefined,
          createdBy: pcrPoData.createdBy,
          updatedBy: pcrPoData.updatedBy,
          createdAt: pcrPoData.createdAt,
          updatedAt: pcrPoData.updatedAt,
        }
        setSelectedPcrPo(selectedData)
      } else if (selectedRows.length === 0) {
        // 선택이 해제되었을 때는 selectedPcrPo를 null로 설정하지 않음
        // row action select가 우선권을 가짐
      }
    }
  }, [table?.getSelectedRowModel().rows])


  return (
    <div
      className={cn("flex flex-col relative", className)}
      style={{ height: calculatedHeight }}
    >

      {/* Main Content */}
      <div
        className="flex flex-col"
        style={{
          height: '100%'
        }}
      >
        {/* Header Bar - 고정 높이 */}
        <div
          className="flex items-center justify-between p-4 bg-background border-b"
          style={{
            height: `${LOCAL_HEADER_HEIGHT}px`,
            flexShrink: 0
          }}
        >

          {/* Right side info */}
          <div className="text-sm text-muted-foreground">
            {tableData && (
              <span>총 {tableData.totalCount || 0}건</span>
            )}
          </div>
        </div>

        {/* Table Content Area - 계산된 높이 사용 */}
        <div
          className="relative bg-background"
          style={{
            height: FIXED_TABLE_HEIGHT,
            display: 'grid',
            gridTemplateRows: '1fr',
            gridTemplateColumns: '1fr'
          }}
        >
          <ResizablePanelGroup
            direction="vertical"
            className="w-full h-full"
          >
            <ResizablePanel
              defaultSize={60}
              minSize={25}
              maxSize={75}
              collapsible={false}
              onResize={(size) => {
                setPanelHeight(size)
              }}
              className="flex flex-col overflow-hidden"
            >
              {/* 상단 테이블 영역 */}
              <div className="flex-1 min-h-0 overflow-hidden">
                <DataTable
                  table={table}
                  maxHeight={`${panelHeight*0.5}vh`}
                >
                  <DataTableAdvancedToolbar
                    table={table as any}
                    filterFields={advancedFilterFields}
                    shallow={false}
                  >
                    <div className="flex items-center gap-2">
                      <PcrTableToolbarActions
                        selection={table}
                        onRefresh={() => {}}
                        isEvcpPage={isEvcpPage}
                        isPartnersPage={isPartnersPage}
                        currentVendorId={currentVendorId}
                      />
                    </div>
                  </DataTableAdvancedToolbar>
                </DataTable>
              </div>
            </ResizablePanel>

            <ResizableHandle withHandle />

            <ResizablePanel
              minSize={25}
              defaultSize={40}
              collapsible={false}
              className="flex flex-col overflow-hidden"
            >
              {/* 하단 상세 테이블 영역 */}
              <div className="flex-1 min-h-0 overflow-hidden bg-background">
                <PcrDetailTables
                  selectedPcrPo={selectedPcrPo}
                  maxHeight={`${(100-panelHeight)*0.4}vh`}
                  isPartnersPage={isPartnersPage}
                />
              </div>
            </ResizablePanel>
          </ResizablePanelGroup>
        </div>
      </div>

      {/* PCR 수정 시트 */}
      <EditPcrSheet
        open={editSheetOpen}
        onOpenChange={setEditSheetOpen}
        pcrData={editingPcr}
        onSuccess={() => {
          // 데이터 새로고침
          window.location.reload()
        }}
      />
    </div>
  )
}