diff options
Diffstat (limited to 'lib/vendors/items-table/item-action-dialog.tsx')
| -rw-r--r-- | lib/vendors/items-table/item-action-dialog.tsx | 477 |
1 files 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<VendorItemsView> | null - setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<VendorItemsView> | null>> } -export function ItemActionsDialogs({ - vendorId, - rowAction, - setRowAction, -}: ItemActionsDialogsProps) { - const [isUpdatePending, startUpdateTransition] = React.useTransition() - const [isDeletePending, startDeleteTransition] = React.useTransition() - const [availableMaterials, setAvailableMaterials] = React.useState<any[]>([]) - const [selectedItemCode, setSelectedItemCode] = React.useState<string>("") - - // 사용 가능한 재료 목록 로드 - 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<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 item = rowAction.row.original + // react-hook-form 세팅 - 서버로 보낼 값은 vendorId와 itemCode만 + const form = useForm<CreateVendorItemSchema>({ + 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 ( - <Dialog - open={true} - onOpenChange={(open) => !open && setRowAction(null)} - > - <DialogContent className="sm:max-w-[425px]"> - <DialogHeader> - <DialogTitle>Change Item</DialogTitle> - <DialogDescription> - Select a new item to replace "{item.itemName}" (Code: {item.itemCode || 'N/A'}). - </DialogDescription> - </DialogHeader> - - <div className="space-y-4"> - <div className="space-y-2"> - <Label>Current Item</Label> - <div className="p-2 bg-muted rounded-md"> - <div className="font-medium">{item.itemName}</div> - <div className="text-sm text-muted-foreground">Code: {item.itemCode || 'N/A'}</div> - </div> - </div> - - <div className="space-y-2"> - <Label htmlFor="newItem">New Item</Label> - <Select value={selectedItemCode} onValueChange={setSelectedItemCode}> - <SelectTrigger> - <SelectValue placeholder="Select a new item" /> - </SelectTrigger> - <SelectContent> - {availableMaterials.map((material) => ( - <SelectItem key={material.itemCode} value={material.itemCode}> - <div> - <div className="font-medium">{material.itemName}</div> - <div className="text-sm text-muted-foreground">Code: {material.itemCode}</div> - </div> - </SelectItem> - ))} - </SelectContent> - </Select> - </div> - </div> - - <DialogFooter> - <Button - type="button" - variant="outline" - onClick={() => setRowAction(null)} - disabled={isUpdatePending} - > - Cancel - </Button> - <Button - onClick={handleSubmit} - disabled={isUpdatePending || !selectedItemCode} - > - {isUpdatePending ? "Updating..." : "Update Item"} - </Button> - </DialogFooter> - </DialogContent> - </Dialog> + // 클라이언트 사이드 필터링 + 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 ( - <AlertDialog - open={true} - onOpenChange={(open) => !open && setRowAction(null)} - > - <AlertDialogContent> - return ( - <AlertDialog - open={true} - onOpenChange={(open) => !open && setRowAction(null)} - > - <AlertDialogContent> - <AlertDialogHeader> - <AlertDialogTitle>Are you sure?</AlertDialogTitle> - <AlertDialogDescription> - This will permanently delete the item "{item.itemName}" (Code: {item.itemCode || 'N/A'}). - This action cannot be undone. - </AlertDialogDescription> - </AlertDialogHeader> - <AlertDialogFooter> - <AlertDialogCancel disabled={isDeletePending}> - Cancel - </AlertDialogCancel> - <AlertDialogAction - onClick={handleDelete} - disabled={isDeletePending} - className="bg-destructive text-destructive-foreground hover:bg-destructive/90" - > - {isDeletePending ? "Deleting..." : "Delete"} - </AlertDialogAction> - </AlertDialogFooter> - </AlertDialogContent> - </AlertDialog> - ) + // 성공 시 모달 닫고 폼 리셋 + form.reset() + setSelectedItem(null) + setOpen(false) } - return ( - <> - <EditDialog /> - <DeleteDialog /> - </> - ) -} - <AlertDialogFooter> - <AlertDialogCancel disabled={isDeletePending}> - Cancel - </AlertDialogCancel> - <AlertDialogAction - onClick={handleDelete} - disabled={isDeletePending} - className="bg-destructive text-destructive-foreground hover:bg-destructive/90" - > - {isDeletePending ? "Deleting..." : "Delete"} - </AlertDialogAction> - </AlertDialogFooter> - </AlertDialogContent> - </AlertDialog> - ) + // 모달 열림/닫힘 핸들 + 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 ( - <> - <EditDialog /> - <DeleteDialog /> - </> + <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> ) }
\ No newline at end of file |
