summaryrefslogtreecommitdiff
path: root/lib/po/vendor-table/shi-vendor-po-table.tsx
blob: 6c5f62ef7a11c50b5d2a6acbff8bbf042e5b671c (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
"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { toast } from "sonner"

import { getVendorPOs, handleVendorPOAction } from "./service"
import { getShiVendorColumns, type ShiVendorPORowAction } from "./shi-vendor-po-columns"
import { VendorPO, VendorPOActionType } from "./types"
import { VendorPOItemsDialog } from "./vendor-po-items-dialog"
import { ShiVendorPOToolbarActions } from "./shi-vendor-po-toolbar-actions"

interface ShiVendorPoTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getVendorPOs>>,
    ]
  >
}


export function ShiVendorPoTable({ promises }: ShiVendorPoTableProps) {
  const [data, setData] = React.useState<{
    data: VendorPO[];
    pageCount: number;
  }>({ data: [], pageCount: 0 });

  const [selectedRows, setSelectedRows] = React.useState<number[]>([])

  // 데이터 로딩
  React.useEffect(() => {
    promises.then(([result]) => {
      console.log("Vendor PO data:", result.data)
      setData(result);
    });
  }, [promises]);

  const [rowAction, setRowAction] =
    React.useState<ShiVendorPORowAction | null>(null)

  // 다이얼로그 상태
  const [itemsDialogOpen, setItemsDialogOpen] = React.useState(false)
  const [selectedPO, setSelectedPO] = React.useState<VendorPO | null>(null)

  // 행 선택 처리 (1개만 선택 가능)
  const handleRowSelect = (id: number, selected: boolean) => {
    if (selected) {
      setSelectedRows([id]) // 1개만 선택
    } else {
      setSelectedRows([])
    }
  }

  // 행 액션 처리
  React.useEffect(() => {
    if (!rowAction) return

    const po = rowAction.row.original
    setSelectedPO(po)

    switch (rowAction.type as VendorPOActionType) {
      case "view-items":
        setItemsDialogOpen(true)
        break
      case "item-status":
        setItemsDialogOpen(true)
        break
      default:
        toast.info("해당 기능은 개발 중입니다.")
    }

    setRowAction(null)
  }, [rowAction])

  // 액션 처리 함수
  const handleAction = async (poId: number, action: string) => {
    try {
      const result = await handleVendorPOAction(poId, action)
      if (result.success) {
        toast.success(result.message)
        // 필요시 데이터 새로고침
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      console.error("Action error:", error)
      toast.error("액션 처리 중 오류가 발생했습니다.")
    }
  }


  const columns = React.useMemo(
    () => getShiVendorColumns({ 
      setRowAction, 
      selectedRows, 
      onRowSelect: handleRowSelect 
    }),
    [selectedRows]
  )

  const filterFields: DataTableFilterField<VendorPO>[] = [
    {
      id: "contractStatus",
      label: "계약상태",
      options: [
        { label: "승인대기", value: "승인대기" },
        { label: "계약완료", value: "계약완료" },
        { label: "진행중", value: "진행중" },
        { label: "수정요청", value: "수정요청" },
        { label: "거절됨", value: "거절됨" },
      ]
    },
    {
      id: "contractType",
      label: "계약종류",
      options: [
        { label: "구매계약", value: "구매계약" },
        { label: "서비스계약", value: "서비스계약" },
        { label: "임가공계약", value: "임가공계약" },
      ]
    },
    {
      id: "currency",
      label: "계약통화",
      options: [
        { label: "KRW", value: "KRW" },
        { label: "USD", value: "USD" },
        { label: "EUR", value: "EUR" },
        { label: "JPY", value: "JPY" },
      ]
    }
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<VendorPO>[] = [
    {
      id: "contractNo",
      label: "PO/계약번호",
      type: "text",
    },
    {
      id: "contractName",
      label: "계약명/자재내역",
      type: "text",
    },
    {
      id: "projectName",
      label: "프로젝트",
      type: "text",
    },
    {
      id: "purchaseManager",
      label: "구매/계약담당",
      type: "text",
    },
    {
      id: "poReceiveDate",
      label: "PO/계약수신일",
      type: "date",
    },
    {
      id: "contractDate",
      label: "계약체결일",
      type: "date",
    },
    {
      id: "lastModifiedDate",
      label: "최종수정일",
      type: "date",
    },
  ]

  const { table } = useDataTable({
    data: data.data,
    columns,
    pageCount: data.pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "lastModifiedDate", desc: true }],
      columnPinning: { right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  return (
    <>
      <DataTable
        table={table}
      >
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <ShiVendorPOToolbarActions 
            table={table} 
            selectedRows={selectedRows}
            onAction={handleAction}
            onViewItems={(po) => {
              setSelectedPO(po)
              setItemsDialogOpen(true)
            }}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      <VendorPOItemsDialog
        open={itemsDialogOpen}
        onOpenChange={setItemsDialogOpen}
        po={selectedPO}
      />

    </>
  )
}