From e37cce51ccfa3dcb91904b2492df3a29970fadf7 Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Mon, 8 Dec 2025 12:43:42 +0900 Subject: (김준회) 버그 수정 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/vendors/items-table/item-action-dialog.tsx | 477 ++++++++++++++----------- 1 file changed, 259 insertions(+), 218 deletions(-) diff --git a/lib/vendors/items-table/item-action-dialog.tsx b/lib/vendors/items-table/item-action-dialog.tsx index 19df27f8..6bbcc436 100644 --- a/lib/vendors/items-table/item-action-dialog.tsx +++ b/lib/vendors/items-table/item-action-dialog.tsx @@ -1,248 +1,289 @@ -// components/vendor-items/item-actions-dialogs.tsx "use client" import * as React from "react" -import type { DataTableRowAction } from "@/types/table" -import { VendorItemsView } from "@/db/schema/vendors" -import { toast } from "sonner" +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 { - Dialog, - DialogContent, - DialogDescription, - DialogFooter, - DialogHeader, - DialogTitle, -} from "@/components/ui/dialog" + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, -} from "@/components/ui/alert-dialog" -import { Button } from "@/components/ui/button" -import { Label } from "@/components/ui/label" + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover" import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "@/components/ui/select" + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, +} from "@/components/ui/command" +import { cn } from "@/lib/utils" -import { updateVendorItem, deleteVendorItem, getItemsForVendor } from "../service" +import { + createVendorItemSchema, + type CreateVendorItemSchema, +} from "../validations" -interface ItemActionsDialogsProps { +import { createVendorItem, getItemsForVendor, ItemDropdownOption } from "../service" + +interface AddItemDialogProps { vendorId: number - rowAction: DataTableRowAction | null - setRowAction: React.Dispatch | null>> } -export function ItemActionsDialogs({ - vendorId, - rowAction, - setRowAction, -}: ItemActionsDialogsProps) { - const [isUpdatePending, startUpdateTransition] = React.useTransition() - const [isDeletePending, startDeleteTransition] = React.useTransition() - const [availableMaterials, setAvailableMaterials] = React.useState([]) - const [selectedItemCode, setSelectedItemCode] = React.useState("") - - // 사용 가능한 재료 목록 로드 - React.useEffect(() => { - if (rowAction?.type === "update") { - getItemsForVendor(vendorId).then((result) => { - if (result.data) { - setAvailableMaterials(result.data) - } - }) - } - }, [rowAction, vendorId]) - - // Edit Dialog - const EditDialog = () => { - if (!rowAction || rowAction.type !== "update") return null +export function AddItemDialog({ vendorId }: AddItemDialogProps) { + const [open, setOpen] = React.useState(false) + const [commandOpen, setCommandOpen] = React.useState(false) + const [items, setItems] = React.useState([]) + const [filteredItems, setFilteredItems] = React.useState([]) + const [isLoading, setIsLoading] = React.useState(false) + const [searchTerm, setSearchTerm] = React.useState("") + + // 선택된 아이템의 정보를 보여주기 위한 상태 + const [selectedItem, setSelectedItem] = React.useState<{ + itemName: string; + description: string; + } | null>(null) - const item = rowAction.row.original + // react-hook-form 세팅 - 서버로 보낼 값은 vendorId와 itemCode만 + const form = useForm({ + resolver: zodResolver(createVendorItemSchema), + defaultValues: { + vendorId, + itemCode: "", + }, + }) - const handleSubmit = () => { - if (!selectedItemCode) { - toast.error("Please select a new item") - return - } + console.log(vendorId) - if (!item.itemCode) { - toast.error("Invalid item code") - return + // 아이템 목록 가져오기 (한 번만 호출) + 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]) - startUpdateTransition(async () => { - const result = await updateVendorItem(vendorId, item.itemCode, selectedItemCode) - - if (result.error) { - toast.error(result.error) - } else { - toast.success("Item updated successfully") - setRowAction(null) - } - }) + // 팝오버 열릴 때 아이템 목록 로드 + React.useEffect(() => { + if (commandOpen) { + fetchItems() } + }, [commandOpen, fetchItems]) - return ( - !open && setRowAction(null)} - > - - - Change Item - - Select a new item to replace "{item.itemName}" (Code: {item.itemCode || 'N/A'}). - - - -
-
- -
-
{item.itemName}
-
Code: {item.itemCode || 'N/A'}
-
-
- -
- - -
-
- - - - - -
-
+ // 클라이언트 사이드 필터링 + 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)) ) - } - - // Delete Dialog - const DeleteDialog = () => { - if (!rowAction || rowAction.type !== "delete") return null - - const item = rowAction.row.original + + setFilteredItems(filtered) + }, [searchTerm, items]) - const handleDelete = () => { - if (!item.itemCode) { - toast.error("Invalid item code") - return - } + // 선택된 아이템 데이터로 폼 업데이트 + const handleSelectItem = (item: ItemDropdownOption) => { + // 폼에는 itemCode만 설정 + form.setValue("itemCode", item.itemCode) + + // 나머지 정보는 표시용 상태에 저장 + setSelectedItem({ + itemName: item.itemName, + description: item.description || "", + }) + + setCommandOpen(false) + } - startDeleteTransition(async () => { - const result = await deleteVendorItem(vendorId, item.itemCode) - - if (result.error) { - toast.error(result.error) - } else { - toast.success("Item deleted successfully") - setRowAction(null) - } - }) + // 폼 제출 - itemCode만 서버로 전송 + async function onSubmit(data: CreateVendorItemSchema) { + // 서버에는 vendorId와 itemCode만 전송됨 + const result = await createVendorItem(data) + console.log(result) + if (result.error) { + alert(`에러: ${result.error}`) + return } - - return ( - !open && setRowAction(null)} - > - - return ( - !open && setRowAction(null)} - > - - - Are you sure? - - This will permanently delete the item "{item.itemName}" (Code: {item.itemCode || 'N/A'}). - This action cannot be undone. - - - - - Cancel - - - {isDeletePending ? "Deleting..." : "Delete"} - - - - - ) + // 성공 시 모달 닫고 폼 리셋 + form.reset() + setSelectedItem(null) + setOpen(false) } - return ( - <> - - - - ) -} - - - Cancel - - - {isDeletePending ? "Deleting..." : "Delete"} - - - - - ) + // 모달 열림/닫힘 핸들 + 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 ( - <> - - - + + {/* 모달 열기 버튼 */} + + + + + + + Create New Item + + 아이템을 선택한 후 Create 버튼을 누르세요. + + + + {/* shadcn/ui Form + react-hook-form */} +
+ +
+ + {/* 아이템 선택 */} +
+ 아이템 선택 + + + + + + + + + 검색 결과가 없습니다 + {isLoading ? ( +
로딩 중...
+ ) : ( + + {filteredItems.map((item) => ( + handleSelectItem(item)} + > + + {item.itemCode} + - {item.itemName} + + ))} + + )} +
+
+
+
+
+ + {/* 아이템 정보 영역 - 선택된 경우에만 표시 */} + {selectedItem && ( +
+

선택된 아이템 정보

+ + {/* Item Code - readonly (hidden field) */} + ( + + + + + + )} + /> + + {/* Item Name (표시용) */} +
+

Item Name

+

{selectedItem.itemName}

+
+ + {/* Description (표시용) */} + {selectedItem.description && ( +
+

Description

+

{selectedItem.description}

+
+ )} +
+ )} + +
+ + + + + +
+ +
+
) } \ No newline at end of file -- cgit v1.2.3