From 5fea18182821dfcc3203c5ea4bb0548ec995718a Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Wed, 3 Dec 2025 08:30:24 +0900 Subject: (김준회) 서버사이드 페칭 작업을 위한 어댑터 초안 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/table/server-query-builder.ts | 129 -------------------------------------- 1 file changed, 129 deletions(-) delete mode 100644 lib/table/server-query-builder.ts (limited to 'lib') diff --git a/lib/table/server-query-builder.ts b/lib/table/server-query-builder.ts deleted file mode 100644 index 7ea25313..00000000 --- a/lib/table/server-query-builder.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { - ColumnFiltersState, - SortingState, - PaginationState, - GroupingState -} from "@tanstack/react-table"; -import { - SQL, - and, - or, - eq, - ilike, - like, - gt, - lt, - gte, - lte, - inArray, - asc, - desc, - not, - sql -} from "drizzle-orm"; -import { PgTable } from "drizzle-orm/pg-core"; - -/** - * Table State를 Drizzle Query 조건으로 변환하는 유틸리티 - */ -export class TableQueryBuilder { - private table: PgTable; - private searchableColumns: string[]; - - constructor(table: PgTable, searchableColumns: string[] = []) { - this.table = table; - this.searchableColumns = searchableColumns; - } - - /** - * Pagination State -> Limit/Offset - */ - getPagination(pagination: PaginationState) { - return { - limit: pagination.pageSize, - offset: pagination.pageIndex * pagination.pageSize, - }; - } - - /** - * Sorting State -> Order By - */ - getOrderBy(sorting: SortingState) { - if (!sorting.length) return []; - - return sorting.map((sort) => { - // 컬럼 이름이 테이블에 존재하는지 확인 - const column = this.table[sort.id as keyof typeof this.table]; - if (!column) return null; - - return sort.desc ? desc(column) : asc(column); - }).filter(Boolean) as SQL[]; - } - - /** - * Column Filters -> Where Clause - */ - getWhere(columnFilters: ColumnFiltersState, globalFilter?: string) { - const conditions: SQL[] = []; - - // 1. Column Filters - for (const filter of columnFilters) { - const column = this.table[filter.id as keyof typeof this.table]; - if (!column) continue; - - const value = filter.value; - - // 값의 타입에 따라 적절한 연산자 선택 (기본적인 예시) - if (Array.isArray(value)) { - // 범위 필터 (예: 날짜, 숫자 범위) - if (value.length === 2) { - const [min, max] = value; - if (min !== null && max !== null) { - conditions.push(and(gte(column, min), lte(column, max))!); - } else if (min !== null) { - conditions.push(gte(column, min)!); - } else if (max !== null) { - conditions.push(lte(column, max)!); - } - } - // 다중 선택 (Select) - else { - conditions.push(inArray(column, value)!); - } - } else if (typeof value === 'string') { - // 텍스트 검색 (Partial Match) - conditions.push(ilike(column, `%${value}%`)!); - } else if (typeof value === 'boolean') { - conditions.push(eq(column, value)!); - } else if (typeof value === 'number') { - conditions.push(eq(column, value)!); - } - } - - // 2. Global Filter (검색창) - if (globalFilter && this.searchableColumns.length > 0) { - const searchConditions = this.searchableColumns.map(colName => { - const column = this.table[colName as keyof typeof this.table]; - if (!column) return null; - return ilike(column, `%${globalFilter}%`); - }).filter(Boolean) as SQL[]; - - if (searchConditions.length > 0) { - conditions.push(or(...searchConditions)!); - } - } - - return conditions.length > 0 ? and(...conditions) : undefined; - } - - /** - * Grouping State -> Group By & Select - * 주의: Group By 사용 시 집계 함수가 필요할 수 있음 - */ - getGroupBy(grouping: GroupingState) { - return grouping.map(g => { - const column = this.table[g as keyof typeof this.table]; - return column; - }).filter(Boolean); - } -} -- cgit v1.2.3 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(-) (limited to 'lib') 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