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
|
"use client"
import * as React from "react"
import { useReactTable, getCoreRowModel, getSortedRowModel, getFilteredRowModel, getPaginationRowModel } from "@tanstack/react-table"
import { DataTableDetail } from "@/components/data-table/data-table-detail"
import { DataTableAdvancedToolbarDetail } from "@/components/data-table/data-table-advanced-toolbar-detail"
import { DragDropTable } from "@/lib/docu-list-rule/number-type-configs/table/drag-drop-table"
import type { DataTableAdvancedFilterField, DataTableRowAction } from "@/types/table"
import { DragEndEvent } from '@dnd-kit/core'
import { arrayMove } from '@dnd-kit/sortable'
import { toast } from "sonner"
import {
Sheet,
SheetContent,
} from "@/components/ui/sheet"
import { getComboBoxOptions, updateComboBoxOption } from "@/lib/docu-list-rule/combo-box-settings/service"
import { getColumns } from "@/lib/docu-list-rule/combo-box-settings/table/combo-box-options-table-columns"
import { ComboBoxOptionsEditSheet } from "@/lib/docu-list-rule/combo-box-settings/table/combo-box-options-edit-sheet"
import { DeleteComboBoxOptionsDialog } from "@/lib/docu-list-rule/combo-box-settings/table/delete-combo-box-options-dialog"
import { ComboBoxOptionsTableToolbarActions } from "@/lib/docu-list-rule/combo-box-settings/table/combo-box-options-table-toolbar"
import { codeGroups } from "@/db/schema/docu-list-rule"
type ComboBoxOption = {
id: number
codeGroupId: number
code: string
description: string
remark: string | null
sdq: number
isActive: boolean
createdAt: Date
updatedAt: Date
}
interface ComboBoxOptionsDetailSheetProps {
open: boolean
onOpenChange: (open: boolean) => void
codeGroup: typeof codeGroups.$inferSelect | null
onSuccess?: () => void
promises?: Promise<[{ data: ComboBoxOption[]; pageCount: number }]>
}
export function ComboBoxOptionsDetailSheet({
open,
onOpenChange,
codeGroup,
onSuccess,
promises,
}: ComboBoxOptionsDetailSheetProps) {
const [rowAction, setRowAction] = React.useState<DataTableRowAction<any> | null>(null)
const [rawData, setRawData] = React.useState<{ data: ComboBoxOption[]; pageCount: number }>({ data: [], pageCount: 0 })
React.useEffect(() => {
if (promises) {
promises.then(([result]) => {
setRawData(result)
})
} else if (open && codeGroup) {
// fallback: 클라이언트에서 직접 fetch (CSR)
(async () => {
try {
const result = await getComboBoxOptions(codeGroup.id, {
page: 1,
perPage: 10,
search: "",
sort: [{ id: "sdq", desc: false }],
filters: [],
joinOperator: "and",
})
console.log("getComboBoxOptions result:", result)
if (result.success && result.data) {
// isActive 필드가 없는 경우 기본값 true로 설정
const optionsWithIsActive = result.data.map(option => ({
...option,
isActive: (option as any).isActive ?? true
}))
console.log("Processed data:", optionsWithIsActive)
setRawData({
data: optionsWithIsActive,
pageCount: result.pageCount || 1
})
} else {
console.log("No data or error:", result)
}
} catch (error) {
console.error("Error refreshing data:", error)
}
})()
}
}, [promises, open, codeGroup])
const refreshData = React.useCallback(async () => {
if (!codeGroup) return
try {
const result = await getComboBoxOptions(codeGroup.id, {
page: 1,
perPage: 10,
sort: [{ id: "sdq", desc: false }],
})
if (result.success && result.data) {
const optionsWithIsActive = result.data.map(option => ({
...option,
isActive: (option as any).isActive ?? true
}))
setRawData({
data: optionsWithIsActive,
pageCount: result.pageCount || 1
})
}
} catch (error) {
console.error("Error refreshing data:", error)
}
}, [codeGroup])
const columns = React.useMemo(() => getColumns({ setRowAction: setRowAction as any }), [setRowAction])
// 고급 필터 필드 설정
const advancedFilterFields: DataTableAdvancedFilterField<any>[] = [
{ id: "code", label: "code", type: "text" },
{ id: "remark", label: "remark", type: "text" },
{ id: "updatedAt", label: "updated_at", type: "date" },
]
const table = useReactTable({
data: rawData.data as any,
columns: columns as any,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getPaginationRowModel: getPaginationRowModel(),
initialState: {
sorting: [{ id: "sdq", desc: false }],
pagination: {
pageSize: 10,
},
},
getRowId: (originalRow) => String((originalRow as any).id),
})
// 드래그 종료 핸들러
const handleDragEnd = React.useCallback(async (event: DragEndEvent) => {
const { active, over } = event
console.log("Drag end event:", { active, over })
if (active.id !== over?.id) {
const oldIndex = rawData.data.findIndex((item) => String(item.id) === active.id)
const newIndex = rawData.data.findIndex((item) => String(item.id) === over?.id)
console.log("Indices:", { oldIndex, newIndex })
if (oldIndex !== -1 && newIndex !== -1) {
const reorderedData = arrayMove(rawData.data, oldIndex, newIndex)
// 새로운 순서로 sdq 값 업데이트
const updatedOptions = reorderedData.map((item, index) => ({
...item,
sdq: index + 1
}))
// 로컬 상태 먼저 업데이트
setRawData(prev => ({ ...prev, data: updatedOptions }))
// 서버에 순서 업데이트 (Number Type Config와 같은 방식)
try {
// 모든 항목을 임시 값으로 먼저 업데이트
for (let i = 0; i < updatedOptions.length; i++) {
const option = updatedOptions[i]
await updateComboBoxOption({
id: option.id,
codeGroupId: option.codeGroupId,
code: option.code,
description: option.description,
remark: option.remark,
sdq: -(i + 1), // 임시 음수 값
})
}
// 최종 순서로 업데이트
for (const option of updatedOptions) {
await updateComboBoxOption({
id: option.id,
codeGroupId: option.codeGroupId,
code: option.code,
description: option.description,
remark: option.remark,
sdq: option.sdq,
})
}
toast.success("순서가 성공적으로 변경되었습니다.")
} catch (error) {
console.error("Error updating order:", error)
toast.error("순서 변경 중 오류가 발생했습니다.")
// 에러 시 원래 데이터로 복원
await refreshData()
}
}
}
}, [rawData.data, codeGroup, refreshData])
if (!codeGroup) return null
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="flex flex-col gap-6 sm:max-w-4xl">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium">{codeGroup.description} 옵션 관리</h3>
<p className="text-sm text-muted-foreground">
{codeGroup.description}의 Combo Box 옵션들을 관리합니다.
</p>
</div>
</div>
<ComboBoxOptionsTableToolbarActions
table={table as any}
codeGroupId={codeGroup.id}
onSuccess={refreshData}
/>
<DragDropTable
table={table as any}
data={rawData.data}
onDragEnd={handleDragEnd}
>
<DataTableAdvancedToolbarDetail
table={table as any}
filterFields={advancedFilterFields}
/>
</DragDropTable>
<DeleteComboBoxOptionsDialog
open={rowAction?.type === "delete"}
onOpenChange={() => setRowAction(null)}
options={rowAction?.row.original ? [rowAction?.row.original] : []}
showTrigger={false}
onSuccess={() => {
rowAction?.row.toggleSelected(false)
refreshData()
}}
/>
<ComboBoxOptionsEditSheet
open={rowAction?.type === "update"}
onOpenChange={() => setRowAction(null)}
data={rowAction?.row.original ?? null}
onSuccess={refreshData}
/>
</SheetContent>
</Sheet>
)
}
|