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
|
"use client"
import * as React from "react"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Check, ChevronsUpDown } from "lucide-react"
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command"
import { cn } from "@/lib/utils"
import {
createVendorItemSchema,
type CreateVendorItemSchema,
} from "../validations"
import { createVendorItem, getItemsForVendor, ItemDropdownOption } from "../service"
interface AddItemDialogProps {
vendorId: number
}
export function AddItemDialog({ vendorId }: AddItemDialogProps) {
const [open, setOpen] = React.useState(false)
const [commandOpen, setCommandOpen] = React.useState(false)
const [items, setItems] = React.useState<ItemDropdownOption[]>([])
const [filteredItems, setFilteredItems] = React.useState<ItemDropdownOption[]>([])
const [isLoading, setIsLoading] = React.useState(false)
const [searchTerm, setSearchTerm] = React.useState("")
// 선택된 아이템의 정보를 보여주기 위한 상태
const [selectedItem, setSelectedItem] = React.useState<{
itemName: string;
description: string;
} | null>(null)
// react-hook-form 세팅 - 서버로 보낼 값은 vendorId와 itemCode만
const form = useForm<CreateVendorItemSchema>({
resolver: zodResolver(createVendorItemSchema),
defaultValues: {
vendorId,
itemCode: "",
},
})
console.log(vendorId)
// 아이템 목록 가져오기 (한 번만 호출)
const fetchItems = React.useCallback(async () => {
if (items.length > 0) return // 이미 로드된 경우 스킵
setIsLoading(true)
try {
const result = await getItemsForVendor(vendorId)
if (result.data) {
setItems(result.data)
setFilteredItems(result.data)
}
} catch (error) {
console.error("Failed to fetch items:", error)
} finally {
setIsLoading(false)
}
}, [items.length])
// 팝오버 열릴 때 아이템 목록 로드
React.useEffect(() => {
if (commandOpen) {
fetchItems()
}
}, [commandOpen, fetchItems])
// 클라이언트 사이드 필터링
React.useEffect(() => {
if (!items.length) return
if (!searchTerm.trim()) {
setFilteredItems(items)
return
}
const lowerSearch = searchTerm.toLowerCase()
const filtered = items.filter(item =>
item.itemCode.toLowerCase().includes(lowerSearch) ||
item.itemName.toLowerCase().includes(lowerSearch) ||
(item.description && item.description.toLowerCase().includes(lowerSearch))
)
setFilteredItems(filtered)
}, [searchTerm, items])
// 선택된 아이템 데이터로 폼 업데이트
const handleSelectItem = (item: ItemDropdownOption) => {
// 폼에는 itemCode만 설정
form.setValue("itemCode", item.itemCode)
// 나머지 정보는 표시용 상태에 저장
setSelectedItem({
itemName: item.itemName,
description: item.description || "",
})
setCommandOpen(false)
}
// 폼 제출 - itemCode만 서버로 전송
async function onSubmit(data: CreateVendorItemSchema) {
// 서버에는 vendorId와 itemCode만 전송됨
const result = await createVendorItem(data)
console.log(result)
if (result.error) {
alert(`에러: ${result.error}`)
return
}
// 성공 시 모달 닫고 폼 리셋
form.reset()
setSelectedItem(null)
setOpen(false)
}
// 모달 열림/닫힘 핸들
function handleDialogOpenChange(nextOpen: boolean) {
if (!nextOpen) {
// 닫힐 때 폼 리셋
form.reset()
setSelectedItem(null)
}
setOpen(nextOpen)
}
// 현재 선택된 아이템 코드
const selectedItemCode = form.watch("itemCode")
// 선택된 아이템 코드가 있으면 상세 정보 표시를 위한 아이템 찾기
const displayItemCode = selectedItemCode || "아이템 선택..."
const displayItemName = selectedItem?.itemName || ""
return (
<Dialog open={open} onOpenChange={handleDialogOpenChange}>
{/* 모달 열기 버튼 */}
<DialogTrigger asChild>
<Button variant="default" size="sm">
Add Item
</Button>
</DialogTrigger>
<DialogContent className="max-h-[90vh] overflow-hidden flex flex-col">
<DialogHeader>
<DialogTitle>Create New Item</DialogTitle>
<DialogDescription>
아이템을 선택한 후 <b>Create</b> 버튼을 누르세요.
</DialogDescription>
</DialogHeader>
{/* shadcn/ui Form + react-hook-form */}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col flex-1 overflow-hidden">
<div className="space-y-4 py-4 flex-1 overflow-y-auto">
{/* 아이템 선택 */}
<div>
<FormLabel className="text-sm font-medium">아이템 선택</FormLabel>
<Popover open={commandOpen} onOpenChange={setCommandOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={commandOpen}
className="w-full justify-between mt-1"
>
{selectedItemCode
? `${selectedItemCode} - ${displayItemName}`
: "아이템 선택..."}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[400px] p-0">
<Command>
<CommandInput
placeholder="아이템 코드/이름 검색..."
onValueChange={setSearchTerm}
/>
<CommandList className="max-h-[200px]">
<CommandEmpty>검색 결과가 없습니다</CommandEmpty>
{isLoading ? (
<div className="py-6 text-center text-sm">로딩 중...</div>
) : (
<CommandGroup>
{filteredItems.map((item) => (
<CommandItem
key={item.itemCode}
value={`${item.itemCode} ${item.itemName}`}
onSelect={() => handleSelectItem(item)}
>
<Check
className={cn(
"mr-2 h-4 w-4",
selectedItemCode === item.itemCode
? "opacity-100"
: "opacity-0"
)}
/>
<span className="font-medium">{item.itemCode}</span>
<span className="ml-2 text-gray-500 truncate">- {item.itemName}</span>
</CommandItem>
))}
</CommandGroup>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
{/* 아이템 정보 영역 - 선택된 경우에만 표시 */}
{selectedItem && (
<div className="rounded-md border p-3 mt-4 overflow-hidden">
<h3 className="font-medium text-sm mb-2">선택된 아이템 정보</h3>
{/* Item Code - readonly (hidden field) */}
<FormField
control={form.control}
name="itemCode"
render={({ field }) => (
<FormItem className="hidden">
<FormControl>
<Input {...field} />
</FormControl>
</FormItem>
)}
/>
{/* Item Name (표시용) */}
<div className="mb-2">
<p className="text-xs font-medium text-gray-500">Item Name</p>
<p className="text-sm mt-0.5 break-words">{selectedItem.itemName}</p>
</div>
{/* Description (표시용) */}
{selectedItem.description && (
<div>
<p className="text-xs font-medium text-gray-500">Description</p>
<p className="text-sm mt-0.5 break-words max-h-20 overflow-y-auto">{selectedItem.description}</p>
</div>
)}
</div>
)}
</div>
<DialogFooter className="flex-shrink-0 pt-2">
<Button type="button" variant="outline" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
type="submit"
disabled={form.formState.isSubmitting || !selectedItemCode}
>
Create
</Button>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
)
}
|