diff options
Diffstat (limited to 'lib/welding')
| -rw-r--r-- | lib/welding/repository.ts | 59 | ||||
| -rw-r--r-- | lib/welding/service.ts | 225 | ||||
| -rw-r--r-- | lib/welding/table/ocr-table-columns.tsx | 115 | ||||
| -rw-r--r-- | lib/welding/table/ocr-table-toolbar-actions.tsx | 96 | ||||
| -rw-r--r-- | lib/welding/table/ocr-table.tsx | 16 | ||||
| -rw-r--r-- | lib/welding/table/update-ocr-row-sheet.tsx | 187 | ||||
| -rw-r--r-- | lib/welding/validation.ts | 10 |
7 files changed, 537 insertions, 171 deletions
diff --git a/lib/welding/repository.ts b/lib/welding/repository.ts index 10e64f58..1e96867b 100644 --- a/lib/welding/repository.ts +++ b/lib/welding/repository.ts @@ -1,6 +1,6 @@ // src/lib/tasks/repository.ts import db from "@/db/db"; -import { ocrRows } from "@/db/schema"; +import { ocrRows, users } from "@/db/schema"; import { eq, inArray, @@ -21,24 +21,47 @@ import { PgTransaction } from "drizzle-orm/pg-core"; * - 트랜잭션(tx)을 받아서 사용하도록 구현 */ export async function selectOcrRows( - tx: PgTransaction<any, any, any>, - params: { - where?: any; // drizzle-orm의 조건식 (and, eq...) 등 - orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[]; - offset?: number; - limit?: number; - } - ) { - const { where, orderBy, offset = 0, limit = 10 } = params; - - return tx - .select() - .from(ocrRows) - .where(where) - .orderBy(...(orderBy ?? [])) - .offset(offset) - .limit(limit); + tx: PgTransaction<any, any, any>, + params: { + where?: any; // drizzle-orm의 조건식 (and, eq...) 등 + orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[]; + offset?: number; + limit?: number; } +) { + const { where, orderBy, offset = 0, limit = 10 } = params; + + return tx + .select({ + // ocrRows의 모든 필드 + id: ocrRows.id, + tableId: ocrRows.tableId, + sessionId: ocrRows.sessionId, + rowIndex: ocrRows.rowIndex, + reportNo: ocrRows.reportNo, + no: ocrRows.no, + identificationNo: ocrRows.identificationNo, + tagNo: ocrRows.tagNo, + jointNo: ocrRows.jointNo, + jointType: ocrRows.jointType, + weldingDate: ocrRows.weldingDate, + confidence: ocrRows.confidence, + sourceTable: ocrRows.sourceTable, + sourceRow: ocrRows.sourceRow, + userId: ocrRows.userId, + createdAt: ocrRows.createdAt, + + // users 테이블의 필드 + userName: users.name, + userEmail: users.email, + }) + .from(ocrRows) + .leftJoin(users, eq(ocrRows.userId, users.id)) + .where(where) + .orderBy(...(orderBy ?? [])) + .offset(offset) + .limit(limit); +} /** 총 개수 count */ export async function countOcrRows( tx: PgTransaction<any, any, any>, diff --git a/lib/welding/service.ts b/lib/welding/service.ts index 3dce07f8..b3a69c36 100644 --- a/lib/welding/service.ts +++ b/lib/welding/service.ts @@ -1,87 +1,156 @@ -"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택) +"use server"; import { revalidateTag, unstable_noStore } from "next/cache"; -import db from "@/db/db"; +import db from "@/db/db"; import { unstable_cache } from "@/lib/unstable-cache"; import { filterColumns } from "@/lib/filter-columns"; import { tagClasses } from "@/db/schema/vendorData"; -import { asc, desc, ilike, inArray, and, gte, lte, not, or } from "drizzle-orm"; -import { GetOcrRowSchema } from "./validation"; +import { asc, desc, ilike, inArray, and, gte, lte, not, or, eq } from "drizzle-orm"; +import { GetOcrRowSchema, UpdateOcrRowSchema } from "./validation"; import { ocrRows } from "@/db/schema"; import { countOcrRows, selectOcrRows } from "./repository"; +import { getServerSession } from "next-auth/next" +import { authOptions } from "@/app/api/auth/[...nextauth]/route" + + + +async function checkAdminPermission(email: string): Promise<boolean> { + const adminEmails = [ + 'worldbest212@naver.com', + 'jspwhale@naver.com', + 'supervisor@company.com' + ]; + + return adminEmails.includes(email.toLowerCase()); +} export async function getOcrRows(input: GetOcrRowSchema) { - // return unstable_cache( - // async () => { - try { - const offset = (input.page - 1) * input.perPage; - - // const advancedTable = input.flags.includes("advancedTable"); - const advancedTable = true; - - // advancedTable 모드면 filterColumns()로 where 절 구성 - const advancedWhere = filterColumns({ - table: ocrRows, - filters: input.filters, - joinOperator: input.joinOperator, - }); - - - let globalWhere - if (input.search) { - const s = `%${input.search}%` - globalWhere = or(ilike(ocrRows.reportNo, s), - ilike(ocrRows.identificationNo, s), - ilike(ocrRows.tagNo, s), - ilike(ocrRows.jointNo, s) - ) - // 필요시 여러 칼럼 OR조건 (status, priority, etc) - } - - const conditions = []; - if (advancedWhere) conditions.push(advancedWhere); - if (globalWhere) conditions.push(globalWhere); - - let finalWhere; - if (conditions.length > 0) { - finalWhere = conditions.length > 1 ? and(...conditions) : conditions[0]; - } - - // 아니면 ilike, inArray, gte 등으로 where 절 구성 - const where = finalWhere - - - const orderBy = - input.sort.length > 0 - ? input.sort.map((item) => - item.desc ? desc(ocrRows[item.id]) : asc(ocrRows[item.id]) - ) - : [asc(ocrRows.createdAt)]; - // 트랜잭션 내부에서 Repository 호출 - const { data, total } = await db.transaction(async (tx) => { - const data = await selectOcrRows(tx, { - where, - orderBy, - offset, - limit: input.perPage, - }); - - const total = await countOcrRows(tx, where); - return { data, total }; - }); - - const pageCount = Math.ceil(total / input.perPage); - - return { data, pageCount }; - } catch (err) { - // 에러 발생 시 디폴트 - return { data: [], pageCount: 0 }; - } - // }, - // [JSON.stringify(input)], // 캐싱 키 - // { - // revalidate: 3600, - // tags: ["equip-class"], // revalidateTag("items") 호출 시 무효화 - // } - // )(); - }
\ No newline at end of file + try { + const session = await getServerSession(authOptions); + const requesterId = session?.user?.id ? Number(session.user.id) : null; + const requesterEmail = session?.user?.email || 'worldbest212@naver.com'; + + + // 로그인하지 않은 경우 빈 결과 반환 + if (!requesterId) { + return { data: [], pageCount: 0 }; + } + + const offset = (input.page - 1) * input.perPage; + const advancedTable = true; + + // advancedTable 모드면 filterColumns()로 where 절 구성 + const advancedWhere = filterColumns({ + table: ocrRows, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + ilike(ocrRows.reportNo, s), + ilike(ocrRows.identificationNo, s), + ilike(ocrRows.tagNo, s), + ilike(ocrRows.jointNo, s) + ); + } + + const isAdmin = await checkAdminPermission(requesterEmail); + + + // 기본 userId 필터 (항상 적용) + const userIdWhere = eq(ocrRows.userId, requesterId); + + // 모든 조건을 배열에 추가 + const conditions = []; + if (!isAdmin) { + conditions.push(eq(ocrRows.userId, requesterId)); // 일반 사용자만 필터링 + } + if (advancedWhere) conditions.push(advancedWhere); + if (globalWhere) conditions.push(globalWhere); + + // 모든 조건을 AND로 결합 + const finalWhere = conditions.length > 1 ? and(...conditions) : conditions[0]; + + const orderBy = + input.sort.length > 0 + ? input.sort.map((item) => + item.desc ? desc(ocrRows[item.id]) : asc(ocrRows[item.id]) + ) + : [asc(ocrRows.createdAt)]; + + // 트랜잭션 내부에서 Repository 호출 + const { data, total } = await db.transaction(async (tx) => { + const data = await selectOcrRows(tx, { + where: finalWhere, + orderBy, + offset, + limit: input.perPage, + }); + + const total = await countOcrRows(tx, finalWhere); + return { data, total }; + }); + + const pageCount = Math.ceil(total / input.perPage); + + console.log(pageCount); + + return { data, pageCount }; + } catch (err) { + console.log(err); + // 에러 발생 시 디폴트 + return { data: [], pageCount: 0 }; + } +} + +interface ModifyOcrRowInput extends UpdateOcrRowSchema { + id: string; +} + +export async function modifyOcrRow(input: ModifyOcrRowInput) { + try { + const session = await getServerSession(authOptions); + const requesterId = session?.user?.id ? Number(session.user.id) : null; + + // 로그인하지 않은 경우 권한 없음 + if (!requesterId) { + return { + data: null, + error: "로그인이 필요합니다." + }; + } + + const { id, ...updateData } = input; + + // 빈 문자열을 null로 변환 + const cleanedData = Object.fromEntries( + Object.entries(updateData).map(([key, value]) => [ + key, + value === "" ? null : value + ]) + ); + + // 자신의 데이터만 수정할 수 있도록 userId 조건 추가 + const result = await db + .update(ocrRows) + .set({ + ...cleanedData, + // updatedAt: new Date(), // 필요한 경우 추가 + }) + .where(and( + eq(ocrRows.id, id), + eq(ocrRows.userId, requesterId) // 자신의 데이터만 수정 가능 + )); + + return { data: null, error: null }; + } catch (error) { + console.error("OCR 행 업데이트 오류:", error); + return { + data: null, + error: "OCR 행을 업데이트하는 중 오류가 발생했습니다." + }; + } +}
\ No newline at end of file diff --git a/lib/welding/table/ocr-table-columns.tsx b/lib/welding/table/ocr-table-columns.tsx index 85830405..d1aefe06 100644 --- a/lib/welding/table/ocr-table-columns.tsx +++ b/lib/welding/table/ocr-table-columns.tsx @@ -14,11 +14,11 @@ import { DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" -import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header" import { toast } from "sonner" import { formatDate } from "@/lib/utils" import { OcrRow } from "@/db/schema" import { type DataTableRowAction } from "@/types/table" +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" interface GetColumnsProps { setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<OcrRow> | null>> @@ -56,26 +56,16 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "reportNo", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Report No" /> + <DataTableColumnHeaderSimple column={column} title="Report No" /> ), cell: ({ getValue }) => { const reportNo = getValue() as string return ( <div className="flex items-center gap-2"> - <Badge variant="outline" className="font-mono text-xs"> + {/* <Badge variant="outline" className="font-mono text-xs"> */} {reportNo || "N/A"} - </Badge> - <Button - variant="ghost" - size="icon" - className="size-6" - onClick={() => { - navigator.clipboard.writeText(reportNo || "") - toast.success("Report No copied to clipboard") - }} - > - <Copy className="size-3" /> - </Button> + {/* </Badge> */} + </div> ) }, @@ -87,7 +77,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "no", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="No" /> + <DataTableColumnHeaderSimple column={column} title="No" /> ), cell: ({ getValue }) => { const no = getValue() as string @@ -104,7 +94,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "identificationNo", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Identification No" /> + <DataTableColumnHeaderSimple column={column} title="Identification No" /> ), cell: ({ getValue }) => { const identificationNo = getValue() as string @@ -121,7 +111,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "tagNo", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Tag No" /> + <DataTableColumnHeaderSimple column={column} title="Tag No" /> ), cell: ({ getValue }) => { const tagNo = getValue() as string @@ -138,7 +128,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "jointNo", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Joint No" /> + <DataTableColumnHeaderSimple column={column} title="Joint No" /> ), cell: ({ getValue }) => { const jointNo = getValue() as string @@ -155,7 +145,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "jointType", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Joint Type" /> + <DataTableColumnHeaderSimple column={column} title="Joint Type" /> ), cell: ({ getValue }) => { const jointType = getValue() as string @@ -172,7 +162,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "weldingDate", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Welding Date" /> + <DataTableColumnHeaderSimple column={column} title="Welding Date" /> ), cell: ({ getValue }) => { const weldingDate = getValue() as string @@ -189,7 +179,7 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> { accessorKey: "confidence", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Confidence" /> + <DataTableColumnHeaderSimple column={column} title="Confidence" /> ), cell: ({ getValue }) => { const confidence = parseFloat(getValue() as string) || 0 @@ -209,46 +199,78 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> }, // Source Table 컬럼 + // { + // accessorKey: "sourceTable", + // header: ({ column }) => ( + // <DataTableColumnHeaderSimple column={column} title="Table" /> + // ), + // cell: ({ getValue }) => { + // const sourceTable = getValue() as number + // return ( + // <div className="text-center"> + // <Badge variant="outline" className="text-xs"> + // T{sourceTable} + // </Badge> + // </div> + // ) + // }, + // enableSorting: true, + // }, + + // // Source Row 컬럼 + // { + // accessorKey: "sourceRow", + // header: ({ column }) => ( + // <DataTableColumnHeaderSimple column={column} title="Row" /> + // ), + // cell: ({ getValue }) => { + // const sourceRow = getValue() as number + // return ( + // <div className="text-center text-sm text-muted-foreground"> + // {sourceRow} + // </div> + // ) + // }, + // enableSorting: true, + // }, + + { - accessorKey: "sourceTable", + accessorKey: "userName", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Table" /> + <DataTableColumnHeaderSimple column={column} title="User Name" /> ), cell: ({ getValue }) => { - const sourceTable = getValue() as number + const userName = getValue() as string return ( - <div className="text-center"> - <Badge variant="outline" className="text-xs"> - T{sourceTable} - </Badge> + <div className="text-sm"> + {userName || "-"} </div> ) }, enableSorting: true, }, - // Source Row 컬럼 { - accessorKey: "sourceRow", + accessorKey: "userEmail", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="Row" /> + <DataTableColumnHeaderSimple column={column} title="User Email" /> ), cell: ({ getValue }) => { - const sourceRow = getValue() as number + const userEmail = getValue() as string return ( - <div className="text-center text-sm text-muted-foreground"> - {sourceRow} + <div className="text-sm"> + {userEmail || "-"} </div> ) }, enableSorting: true, }, - // Created At 컬럼 { accessorKey: "createdAt", header: ({ column }) => ( - <DataTableColumnHeader column={column} title="생성일" /> + <DataTableColumnHeaderSimple column={column} title="생성일" /> ), cell: ({ cell }) => { const date = cell.getValue() as Date @@ -276,24 +298,17 @@ export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<OcrRow> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end" className="w-40"> - <DropdownMenuItem + <DropdownMenuItem onClick={() => { - const rowData = row.original - navigator.clipboard.writeText(JSON.stringify(rowData, null, 2)) - toast.success("Row data copied to clipboard") + setRowAction({ type: "update", row }) }} + // className="text-destructive focus:text-destructive" > - <Copy className="mr-2 size-4" aria-hidden="true" /> - Copy Row Data + Update </DropdownMenuItem> + <DropdownMenuSeparator /> - <DropdownMenuItem - onClick={() => { - setRowAction({ type: "view", row }) - }} - > - View Details - </DropdownMenuItem> + <DropdownMenuItem onClick={() => { setRowAction({ type: "delete", row }) diff --git a/lib/welding/table/ocr-table-toolbar-actions.tsx b/lib/welding/table/ocr-table-toolbar-actions.tsx index 001b21cb..6c6d0637 100644 --- a/lib/welding/table/ocr-table-toolbar-actions.tsx +++ b/lib/welding/table/ocr-table-toolbar-actions.tsx @@ -39,6 +39,24 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { const [selectedFile, setSelectedFile] = React.useState<File | null>(null) const fileInputRef = React.useRef<HTMLInputElement>(null) + // 다이얼로그 닫기 핸들러 - 업로드 중에는 닫기 방지 + const handleDialogOpenChange = (open: boolean) => { + // 다이얼로그를 닫으려고 할 때 + if (!open) { + // 업로드가 진행 중이면 닫기를 방지 + if (isUploading && uploadProgress?.stage !== "complete") { + toast.warning("Cannot close while processing. Please wait for completion.", { + description: "OCR processing is in progress..." + }) + return // 다이얼로그를 닫지 않음 + } + + // 업로드가 진행 중이 아니거나 완료되었으면 초기화 후 닫기 + resetUpload() + } + + setIsUploadDialogOpen(open) + } const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => { const file = event.target.files?.[0] @@ -142,11 +160,7 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { // 성공 후 다이얼로그 닫기 및 상태 초기화 setTimeout(() => { setIsUploadDialogOpen(false) - setSelectedFile(null) - setUploadProgress(null) - if (fileInputRef.current) { - fileInputRef.current.value = '' - } + resetUpload() // 테이블 새로고침 window.location.reload() @@ -177,21 +191,60 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { } } + // Cancel 버튼 핸들러 + const handleCancelClick = () => { + if (isUploading && uploadProgress?.stage !== "complete") { + // 업로드 진행 중이면 취소 불가능 메시지 + toast.warning("Cannot cancel while processing. Please wait for completion.", { + description: "OCR processing cannot be interrupted safely." + }) + } else { + // 업로드 중이 아니거나 완료되었으면 다이얼로그 닫기 + setIsUploadDialogOpen(false) + resetUpload() + } + } + return ( <div className="flex items-center gap-2"> {/* OCR 업로드 다이얼로그 */} - <Dialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen}> + <Dialog open={isUploadDialogOpen} onOpenChange={handleDialogOpenChange}> <DialogTrigger asChild> <Button variant="samsung" size="sm" className="gap-2"> <Upload className="size-4" aria-hidden="true" /> <span className="hidden sm:inline">Upload OCR</span> </Button> </DialogTrigger> - <DialogContent className="sm:max-w-md"> + <DialogContent + className="sm:max-w-md" + // 업로드 중에는 ESC 키로도 닫기 방지 + onEscapeKeyDown={(e) => { + if (isUploading && uploadProgress?.stage !== "complete") { + e.preventDefault() + toast.warning("Cannot close while processing. Please wait for completion.") + } + }} + // 업로드 중에는 외부 클릭으로도 닫기 방지 + onInteractOutside={(e) => { + if (isUploading && uploadProgress?.stage !== "complete") { + e.preventDefault() + toast.warning("Cannot close while processing. Please wait for completion.") + } + }} + > <DialogHeader> - <DialogTitle>Upload Document for OCR</DialogTitle> + <DialogTitle className="flex items-center gap-2"> + Upload Document for OCR + {/* 업로드 중일 때 로딩 인디케이터 표시 */} + {isUploading && uploadProgress?.stage !== "complete" && ( + <Loader2 className="size-4 animate-spin text-muted-foreground" /> + )} + </DialogTitle> <DialogDescription> - Upload a PDF or image file to extract table data using OCR technology. + {isUploading && uploadProgress?.stage !== "complete" + ? "Processing in progress. Please do not close this dialog." + : "Upload a PDF or image file to extract table data using OCR technology." + } </DialogDescription> </DialogHeader> @@ -239,6 +292,16 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { <p className="text-xs text-muted-foreground"> {uploadProgress.message} </p> + + {/* 진행 중일 때 안내 메시지 */} + {isUploading && uploadProgress.stage !== "complete" && ( + <div className="flex items-center gap-2 p-2 bg-blue-50 dark:bg-blue-950/20 rounded-md"> + <Loader2 className="size-3 animate-spin text-blue-600" /> + <p className="text-xs text-blue-700 dark:text-blue-300"> + Please wait... This dialog will close automatically when complete. + </p> + </div> + )} </div> )} @@ -247,18 +310,10 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { <Button variant="outline" size="sm" - onClick={() => { - if (isUploading) { - // 업로드 중이면 취소 불가능하다는 메시지 - toast.warning("Cannot cancel while processing. Please wait...") - } else { - setIsUploadDialogOpen(false) - resetUpload() - } - }} - disabled={isUploading && uploadProgress?.stage !== "complete"} + onClick={handleCancelClick} + disabled={false} // 항상 클릭 가능하지만 핸들러에서 처리 > - {isUploading ? "Close" : "Cancel"} + {isUploading && uploadProgress?.stage !== "complete" ? "Close" : "Cancel"} </Button> <Button size="sm" @@ -277,6 +332,7 @@ export function OcrTableToolbarActions({ table }: OcrTableToolbarActionsProps) { </div> </DialogContent> </Dialog> + {/* Export 버튼 */} <Button variant="outline" diff --git a/lib/welding/table/ocr-table.tsx b/lib/welding/table/ocr-table.tsx index 91af1c67..e14c53d1 100644 --- a/lib/welding/table/ocr-table.tsx +++ b/lib/welding/table/ocr-table.tsx @@ -15,6 +15,7 @@ import { OcrTableToolbarActions } from "./ocr-table-toolbar-actions" import { getColumns } from "./ocr-table-columns" import { OcrRow } from "@/db/schema" import { getOcrRows } from "../service" +import { UpdateOcrRowSheet } from "./update-ocr-row-sheet" interface ItemsTableProps { promises: Promise< @@ -74,8 +75,8 @@ export function OcrTable({ promises }: ItemsTableProps) { type: "text", // group: "Basic Info", }, - - + + { id: "identificationNo", label: "Identification No", @@ -88,19 +89,19 @@ export function OcrTable({ promises }: ItemsTableProps) { type: "text", // group: "Metadata", }, - { + { id: "jointNo", label: "Joint No", type: "text", // group: "Metadata", }, - { + { id: "weldingDate", label: "Welding Date", type: "date", // group: "Metadata", }, - { + { id: "createdAt", label: "생성일", type: "date", @@ -138,6 +139,11 @@ export function OcrTable({ promises }: ItemsTableProps) { <OcrTableToolbarActions table={table} /> </DataTableAdvancedToolbar> </DataTable> + <UpdateOcrRowSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + ocrRow={rowAction?.type === "update" ? rowAction.row.original : null} + /> </> ) } diff --git a/lib/welding/table/update-ocr-row-sheet.tsx b/lib/welding/table/update-ocr-row-sheet.tsx new file mode 100644 index 00000000..cbb4f030 --- /dev/null +++ b/lib/welding/table/update-ocr-row-sheet.tsx @@ -0,0 +1,187 @@ +"use client" + +import * as React from "react" +import { OcrRow } from "@/db/schema" +import { zodResolver } from "@hookform/resolvers/zod" +import { Loader } from "lucide-react" +import { useForm } from "react-hook-form" +import { toast } from "sonner" + +import { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" + +import { modifyOcrRow } from "../service" +import { updateOcrRowSchema, type UpdateOcrRowSchema } from "../validation" + +interface UpdateOcrRowSheetProps + extends React.ComponentPropsWithRef<typeof Sheet> { + ocrRow: OcrRow | null +} + +export function UpdateOcrRowSheet({ ocrRow, ...props }: UpdateOcrRowSheetProps) { + const [isUpdatePending, startUpdateTransition] = React.useTransition() + + const form = useForm<UpdateOcrRowSchema>({ + resolver: zodResolver(updateOcrRowSchema), + defaultValues: { + identificationNo: ocrRow?.identificationNo ?? "", + tagNo: ocrRow?.tagNo ?? "", + weldingDate: ocrRow?.weldingDate ?? "", + jointType: ocrRow?.jointType ?? "", + }, + }) + + React.useEffect(() => { + if (ocrRow) { + form.reset({ + identificationNo: ocrRow.identificationNo ?? "", + tagNo: ocrRow.tagNo ?? "", + weldingDate: ocrRow.weldingDate ?? "", + jointType: ocrRow.jointType ?? "", + }) + } + }, [ocrRow, form]) + + function onSubmit(input: UpdateOcrRowSchema) { + startUpdateTransition(async () => { + if (!ocrRow) return + + const { error } = await modifyOcrRow({ + id: ocrRow.id, + ...input, + }) + + if (error) { + toast.error(error) + return + } + + form.reset() + props.onOpenChange?.(false) + toast.success("OCR 행이 업데이트되었습니다") + }) + } + + + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-md"> + <SheetHeader className="text-left"> + <SheetTitle>OCR 행 업데이트</SheetTitle> + <SheetDescription> + OCR 행의 세부 정보를 수정하고 변경 사항을 저장하세요 + </SheetDescription> + </SheetHeader> + <Form {...form}> + <form + onSubmit={form.handleSubmit(onSubmit)} + className="flex flex-col gap-4" + > + <FormField + control={form.control} + name="identificationNo" + render={({ field }) => ( + <FormItem> + <FormLabel>Identification No</FormLabel> + <FormControl> + <Input + placeholder="식별 번호를 입력하세요" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="tagNo" + render={({ field }) => ( + <FormItem> + <FormLabel>Tag No</FormLabel> + <FormControl> + <Input + placeholder="태그 번호를 입력하세요" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="weldingDate" + render={({ field }) => ( + <FormItem> + <FormLabel>Welding Date</FormLabel> + <FormControl> + <Input + placeholder="용접 날짜를 입력하세요 (예: 2024-12-01)" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="jointType" + render={({ field }) => ( + <FormItem> + <FormLabel>Joint Type</FormLabel> + <FormControl> + <Input + placeholder="조인트 타입을 입력하세요" + {...field} + /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <SheetFooter className="gap-2 pt-2 sm:space-x-0"> + <SheetClose asChild> + <Button type="button" variant="outline"> + 취소 + </Button> + </SheetClose> + <Button disabled={isUpdatePending}> + {isUpdatePending && ( + <Loader + className="mr-2 size-4 animate-spin" + aria-hidden="true" + /> + )} + 저장 + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file diff --git a/lib/welding/validation.ts b/lib/welding/validation.ts index fe5b2cbb..969aafdc 100644 --- a/lib/welding/validation.ts +++ b/lib/welding/validation.ts @@ -34,3 +34,13 @@ export const searchParamsCache = createSearchParamsCache({ // 타입 내보내기 export type GetOcrRowSchema = Awaited<ReturnType<typeof searchParamsCache.parse>>; + + +export const updateOcrRowSchema = z.object({ + identificationNo: z.string().optional(), + tagNo: z.string().optional(), + weldingDate: z.string().optional(), + jointType: z.string().optional(), +}) + +export type UpdateOcrRowSchema = z.infer<typeof updateOcrRowSchema>
\ No newline at end of file |
