summaryrefslogtreecommitdiff
path: root/lib/tech-vendors/items-table/add-item-dialog.tsx
blob: e4d742044faf80d2675f4434cab840e03c9e3d85 (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
"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 { useRouter } from "next/navigation"

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,
} 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 { toast } from "sonner"

import {
  createTechVendorItemSchema,
  type CreateTechVendorItemSchema,
} from "@/lib/tech-vendors/validations"

import { createTechVendorItem, getItemsForTechVendor, ItemDropdownOption } from "../service"

interface AddItemDialogProps {
  vendorId: number
  vendorType: string // UI에서 전달하지만 내부적으로는 사용하지 않음
}

export function AddItemDialog({ vendorId }: AddItemDialogProps) {
  const router = useRouter()
  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)

  const form = useForm<CreateTechVendorItemSchema>({
    resolver: zodResolver(createTechVendorItemSchema),
    defaultValues: {
      vendorId,
      itemCode: "",
    },
  })

  const fetchItems = React.useCallback(async () => {
    if (items.length > 0) return
    
    console.log(`[AddItemDialog] fetchItems - 벤더 ID: ${vendorId} 시작`)
    
    setIsLoading(true)
    try {
      console.log(`[AddItemDialog] getItemsForTechVendor 호출 - vendorId: ${vendorId}`)
      const result = await getItemsForTechVendor(vendorId)
      console.log(`[AddItemDialog] getItemsForTechVendor 결과:`, result)
      
      if (result.data) {
        console.log(`[AddItemDialog] 사용 가능한 아이템 목록:`, result.data)
        setItems(result.data)
        setFilteredItems(result.data)
      } else if (result.error) {
        console.error("[AddItemDialog] 아이템 조회 실패:", result.error)
        toast.error(result.error)
      }
    } catch (err) {
      console.error("[AddItemDialog] 아이템 조회 실패:", err)
      toast.error("아이템 목록을 불러오는데 실패했습니다.")
    } finally {
      setIsLoading(false)
      console.log(`[AddItemDialog] fetchItems 완료`)
    }
  }, [items.length, vendorId])

  React.useEffect(() => {
    if (commandOpen) {
      console.log(`[AddItemDialog] Popover 열림 - fetchItems 호출`)
      fetchItems()
    }
  }, [commandOpen, fetchItems])

  React.useEffect(() => {
    if (!items.length) return
    
    if (!searchTerm.trim()) {
      setFilteredItems(items)
      return
    }
    
    console.log(`[AddItemDialog] 검색어로 필터링: "${searchTerm}"`)
    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))
    )
    
    console.log(`[AddItemDialog] 필터링 결과: ${filtered.length}개 아이템`)
    setFilteredItems(filtered)
  }, [searchTerm, items])

  const handleSelectItem = (item: ItemDropdownOption) => {
    console.log(`[AddItemDialog] 아이템 선택: ${item.itemCode}`)
    form.setValue("itemCode", item.itemCode, { shouldValidate: true })
    setSelectedItem({
      itemName: item.itemName,
      description: item.description || "",
    })
    console.log(`[AddItemDialog] 선택된 아이템 정보:`, {
      itemCode: item.itemCode,
      itemName: item.itemName,
      description: item.description || ""
    })
    setCommandOpen(false)
  }

  async function onSubmit(data: CreateTechVendorItemSchema) {
    console.log(`[AddItemDialog] 폼 제출 시작 - 데이터:`, data)
    try {
      if (!data.itemCode) {
        console.error(`[AddItemDialog] itemCode가 없습니다.`)
        toast.error("아이템을 선택해주세요.")
        return
      }

      console.log(`[AddItemDialog] createTechVendorItem 호출 - vendorId: ${data.vendorId}, itemCode: ${data.itemCode}`)
      const submitData = {
        ...data,
        itemName: selectedItem?.itemName || "기술영업"
      }
      console.log(`[AddItemDialog] 최종 제출 데이터:`, submitData)
      
      const result = await createTechVendorItem(submitData)
      console.log(`[AddItemDialog] createTechVendorItem 결과:`, result)
      
      if (result.error) {
        console.error(`[AddItemDialog] 추가 실패:`, result.error)
        toast.error(result.error)
        return
      }
      
      console.log(`[AddItemDialog] 아이템 추가 성공`)
      toast.success("아이템이 추가되었습니다.")
      form.reset()
      setSelectedItem(null)
      setOpen(false)
      console.log(`[AddItemDialog] 화면 새로고침 시작`)
      router.refresh()
      console.log(`[AddItemDialog] 화면 새로고침 완료`)
    } catch (err) {
      console.error("[AddItemDialog] 아이템 추가 오류:", err)
      toast.error("아이템 추가 중 오류가 발생했습니다.")
    }
  }

  function handleDialogOpenChange(nextOpen: boolean) {
    console.log(`[AddItemDialog] 다이얼로그 상태 변경: ${nextOpen ? '열림' : '닫힘'}`)
    if (!nextOpen) {
      form.reset()
      setSelectedItem(null)
    }
    setOpen(nextOpen)
  }

  const selectedItemCode = form.watch("itemCode")
  console.log(`[AddItemDialog] 현재 선택된 itemCode:`, 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>

        <Form {...form}>
          <form onSubmit={(e) => {
            console.log(`[AddItemDialog] 폼 제출 이벤트 발생`)
            form.handleSubmit(onSubmit)(e)
          }} 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>
                  
                  <FormField
                    control={form.control}
                    name="itemCode"
                    render={({ field }) => (
                      <FormItem className="hidden">
                        <FormControl>
                          <Input {...field} />
                        </FormControl>
                      </FormItem>
                    )}
                  />
                  
                  <div className="mb-2">
                    <div className="text-sm font-medium text-gray-500">Item Name</div>
                    <div className="text-sm">{selectedItem.itemName}</div>
                  </div>
                  
                  {selectedItem.description && (
                    <div>
                      <div className="text-sm font-medium text-gray-500">Description</div>
                      <div className="text-sm">{selectedItem.description}</div>
                    </div>
                  )}
                </div>
              )}
            </div>

            <DialogFooter className="pt-4 border-t">
              <Button type="submit" disabled={!selectedItemCode}>
                Create
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}