From bcd462d6e60871b86008e072f4b914138fc5c328 Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Mon, 11 Aug 2025 09:34:40 +0000 Subject: (김준회) 리치텍스트에디터 (결재템플릿을 위한 공통컴포넌트), command-menu 에러 수정, 결재 템플릿 관리, 결재선 관리, ECC RFQ+PR Item 수신시 비즈니스테이블(ProcurementRFQ) 데이터 적재, WSDL 오류 수정 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/approval-line/service.ts | 341 +++++++++++++++++++++ .../table/approval-line-table-columns.tsx | 197 ++++++++++++ .../table/approval-line-table-toolbar-actions.tsx | 73 +++++ lib/approval-line/table/approval-line-table.tsx | 130 ++++++++ .../table/create-approval-line-sheet.tsx | 224 ++++++++++++++ .../table/delete-approval-line-dialog.tsx | 168 ++++++++++ .../table/duplicate-approval-line-sheet.tsx | 206 +++++++++++++ .../table/update-approval-line-sheet.tsx | 264 ++++++++++++++++ lib/approval-line/utils/format.ts | 53 ++++ lib/approval-line/validations.ts | 24 ++ 10 files changed, 1680 insertions(+) create mode 100644 lib/approval-line/service.ts create mode 100644 lib/approval-line/table/approval-line-table-columns.tsx create mode 100644 lib/approval-line/table/approval-line-table-toolbar-actions.tsx create mode 100644 lib/approval-line/table/approval-line-table.tsx create mode 100644 lib/approval-line/table/create-approval-line-sheet.tsx create mode 100644 lib/approval-line/table/delete-approval-line-dialog.tsx create mode 100644 lib/approval-line/table/duplicate-approval-line-sheet.tsx create mode 100644 lib/approval-line/table/update-approval-line-sheet.tsx create mode 100644 lib/approval-line/utils/format.ts create mode 100644 lib/approval-line/validations.ts (limited to 'lib/approval-line') diff --git a/lib/approval-line/service.ts b/lib/approval-line/service.ts new file mode 100644 index 00000000..3000e25f --- /dev/null +++ b/lib/approval-line/service.ts @@ -0,0 +1,341 @@ +'use server'; + +import db from '@/db/db'; +import { + and, + asc, + count, + desc, + eq, + ilike, + or, +} from 'drizzle-orm'; + +import { sql } from 'drizzle-orm'; +import { approvalLines } from '@/db/schema/knox/approvals'; + +import { filterColumns } from '@/lib/filter-columns'; + +// --------------------------------------------- +// Types +// --------------------------------------------- + +export type ApprovalLine = typeof approvalLines.$inferSelect; + +export interface ApprovalLineWithUsage extends ApprovalLine { + templateCount: number; // 사용 중인 템플릿 수 +} + +// --------------------------------------------- +// List & read helpers +// --------------------------------------------- + +interface ListInput { + page: number; + perPage: number; + search?: string; + filters?: Record[]; + joinOperator?: 'and' | 'or'; + sort?: Array<{ id: string; desc: boolean }>; +} + +export async function getApprovalLineList(input: ListInput) { + const offset = (input.page - 1) * input.perPage; + + /* ------------------------------------------------------------------ + * WHERE 절 구성 + * ----------------------------------------------------------------*/ + const advancedWhere = filterColumns({ + table: approvalLines, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + filters: (input.filters ?? []) as any, + joinOperator: (input.joinOperator ?? 'and') as 'and' | 'or', + }); + + // 전역 검색 (name, description) + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + ilike(approvalLines.name, s), + ilike(approvalLines.description, s), + ); + } + + const conditions = []; + if (advancedWhere) conditions.push(advancedWhere); + if (globalWhere) conditions.push(globalWhere); + + const where = + conditions.length === 0 + ? undefined + : conditions.length === 1 + ? conditions[0] + : and(...conditions); + + /* ------------------------------------------------------------------ + * ORDER BY 절 구성 + * ----------------------------------------------------------------*/ + let orderBy; + try { + orderBy = input.sort && input.sort.length > 0 + ? input.sort + .map((item) => { + if (!item || !item.id || typeof item.id !== 'string') return null; + if (!(item.id in approvalLines)) return null; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const col = approvalLines[item.id]; + return item.desc ? desc(col) : asc(col); + }) + .filter((v): v is Exclude => v !== null) + : [desc(approvalLines.updatedAt)]; + } catch { + orderBy = [desc(approvalLines.updatedAt)]; + } + + /* ------------------------------------------------------------------ + * 데이터 조회 + * ----------------------------------------------------------------*/ + const data = await db + .select() + .from(approvalLines) + .where(where) + .orderBy(...orderBy) + .limit(input.perPage) + .offset(offset); + + const totalResult = await db + .select({ count: count() }) + .from(approvalLines) + .where(where); + + const total = totalResult[0]?.count ?? 0; + const pageCount = Math.ceil(total / input.perPage); + + return { + data, + pageCount, + }; +} + +// ---------------------------------------------------- +// Simple list for options (id, name) +// ---------------------------------------------------- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export async function getApprovalLineOptions(category?: string): Promise> { + const where = category + ? eq(approvalLines.category, category) + : undefined; + const rows = await db + .select({ id: approvalLines.id, name: approvalLines.name, aplns: approvalLines.aplns, category: approvalLines.category }) + .from(approvalLines) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .where(where as any) + .orderBy(asc(approvalLines.name)); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return rows as Array<{ id: string; name: string; aplns: any[]; category: string | null }>; +} + +// ---------------------------------------------------- +// Distinct categories for filter +// ---------------------------------------------------- +export async function getApprovalLineCategories(): Promise { + const rows = await db + .select({ category: approvalLines.category }) + .from(approvalLines) + .where(sql`${approvalLines.category} IS NOT NULL AND ${approvalLines.category} <> ''`) + .groupBy(approvalLines.category) + .orderBy(asc(approvalLines.category)); + return rows.map((r) => r.category!).filter(Boolean); +} + +// ---------------------------------------------------- +// Server Action for fetching options by category +// ---------------------------------------------------- +export async function getApprovalLineOptionsAction(category?: string) { + try { + const data = await getApprovalLineOptions(category) + return { success: true, data } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : '조회에 실패했습니다.' } + } +} + +// ---------------------------------------------------- +// Server Action for fetching distinct categories +// ---------------------------------------------------- +export async function getApprovalLineCategoriesAction() { + try { + const data = await getApprovalLineCategories() + return { success: true, data } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : '카테고리 조회에 실패했습니다.' } + } +} + +// ---------------------------------------------------- +// Get single approval line +// ---------------------------------------------------- +export async function getApprovalLine(id: string): Promise { + const [line] = await db + .select() + .from(approvalLines) + .where(eq(approvalLines.id, id)) + .limit(1); + + return line || null; +} + +// ---------------------------------------------------- +// Create approval line +// ---------------------------------------------------- +interface CreateInput { + name: string; + description?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aplns: any[]; // 결재선 구성 (JSON) + createdBy: number; +} + +export async function createApprovalLine(data: CreateInput): Promise { + // 중복 이름 체크 + const existing = await db + .select({ id: approvalLines.id }) + .from(approvalLines) + .where(eq(approvalLines.name, data.name)) + .limit(1); + + if (existing.length > 0) { + throw new Error('이미 존재하는 결재선 이름입니다.'); + } + + const [newLine] = await db + .insert(approvalLines) + .values({ + name: data.name, + description: data.description, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aplns: data.aplns as any, + createdBy: data.createdBy, + }) + .returning(); + + return newLine; +} + +// ---------------------------------------------------- +// Update approval line +// ---------------------------------------------------- +interface UpdateInput { + name?: string; + description?: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aplns?: any[]; // 결재선 구성 (JSON) + updatedBy: number; +} + +export async function updateApprovalLine(id: string, data: UpdateInput): Promise { + const existing = await getApprovalLine(id); + if (!existing) throw new Error('결재선을 찾을 수 없습니다.'); + + // 이름 중복 체크 (자신 제외) + if (data.name && data.name !== existing.name) { + const duplicate = await db + .select({ id: approvalLines.id }) + .from(approvalLines) + .where( + and( + eq(approvalLines.name, data.name), + eq(approvalLines.id, id) + ) + ) + .limit(1); + + if (duplicate.length > 0) { + throw new Error('이미 존재하는 결재선 이름입니다.'); + } + } + + // 결재선 업데이트 + await db + .update(approvalLines) + .set({ + name: data.name ?? existing.name, + description: data.description ?? existing.description, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aplns: (data.aplns as any) ?? (existing.aplns as any), + updatedAt: new Date(), + }) + .where(eq(approvalLines.id, id)); + + const result = await getApprovalLine(id); + if (!result) throw new Error('업데이트된 결재선을 조회할 수 없습니다.'); + return result; +} + +// ---------------------------------------------------- +// Server Actions +// ---------------------------------------------------- +export async function updateApprovalLineAction(id: string, data: UpdateInput) { + try { + const updated = await updateApprovalLine(id, data) + return { success: true, data: updated } + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '업데이트에 실패했습니다.' + } + } +} + +// ---------------------------------------------------- +// Duplicate approval line +// ---------------------------------------------------- +export async function duplicateApprovalLine( + id: string, + newName: string, + createdBy: number, +): Promise<{ success: boolean; error?: string; data?: ApprovalLine }> { + try { + const existing = await getApprovalLine(id) + if (!existing) return { success: false, error: '결재선을 찾을 수 없습니다.' } + + // 새 결재선 생성 + const duplicated = await createApprovalLine({ + name: newName, + description: existing.description ? `${existing.description} (복사본)` : undefined, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + aplns: existing.aplns as any, + createdBy, + }) + + return { success: true, data: duplicated } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : '복제에 실패했습니다.' } + } +} + +// ---------------------------------------------------- +// Delete (soft delete X -> 실제 삭제) +// ---------------------------------------------------- +export async function deleteApprovalLine(id: string): Promise<{ success: boolean; error?: string }> { + try { + await db.delete(approvalLines).where(eq(approvalLines.id, id)); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '삭제에 실패했습니다.', + }; + } +} + +// ---------------------------------------------------- +// Get approval line usage (템플릿에서 사용 중인지 확인) +// ---------------------------------------------------- +export async function getApprovalLineUsage(): Promise<{ templateCount: number }> { + // 현재는 approvalLines가 템플릿과 직접 연결되지 않으므로 0 반환 + // 추후 템플릿에서 결재선을 참조하는 구조로 변경 시 실제 사용량 계산 + return { templateCount: 0 }; +} \ No newline at end of file diff --git a/lib/approval-line/table/approval-line-table-columns.tsx b/lib/approval-line/table/approval-line-table-columns.tsx new file mode 100644 index 00000000..5b35b92c --- /dev/null +++ b/lib/approval-line/table/approval-line-table-columns.tsx @@ -0,0 +1,197 @@ +"use client" + +import * as React from "react" +import { ColumnDef } from "@tanstack/react-table" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { DataTableColumnHeader } from "@/components/data-table/data-table-column-header" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { type ApprovalLine } from "../service" +import { formatApprovalLine } from "../utils/format" +import { formatDate } from "@/lib/utils" +import { MoreHorizontal, Copy, Edit, Trash2 } from "lucide-react" + +interface GetColumnsProps { + setRowAction: React.Dispatch>; +} + + +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { + return [ + { + id: "select", + header: ({ table }) => ( + table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-[2px]" + /> + ), + cell: ({ row }) => ( + row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-[2px]" + /> + ), + enableSorting: false, + enableHiding: false, + }, + { + accessorKey: "name", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + return ( +
+ + {row.getValue("name")} + +
+ ) + }, + }, + { + accessorKey: "description", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + return ( +
+ + {row.getValue("description") || "-"} + +
+ ) + }, + }, + { + accessorKey: "aplns", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + const aplns = row.getValue("aplns") as unknown as Array<{ + seq: string; + name?: string; + emailAddress?: string; + role: string; + }>; + const approvalLineText = formatApprovalLine(aplns); + + return ( +
+
+
+ {approvalLineText} + + {aplns?.length || 0}명 + +
+
+
+ ) + }, + }, + { + accessorKey: "createdAt", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + return ( +
+ + {formatDate(row.getValue("createdAt"))} + +
+ ) + }, + }, + { + accessorKey: "updatedAt", + header: ({ column }) => ( + + ), + cell: ({ row }) => { + return ( +
+ + {formatDate(row.getValue("updatedAt"))} + +
+ ) + }, + }, + { + id: "actions", + cell: ({ row }) => { + + return ( + + + + + + { + setRowAction({ type: "update", row }); + }} + > + + + { + setRowAction({ type: "duplicate", row }); + }} + > + + + + + { + setRowAction({ type: "delete", row }); + }} + className="text-destructive focus:text-destructive" + > + + + + ); + }, + enableSorting: false, + enableHiding: false, + size: 80, + }, + ] +} \ No newline at end of file diff --git a/lib/approval-line/table/approval-line-table-toolbar-actions.tsx b/lib/approval-line/table/approval-line-table-toolbar-actions.tsx new file mode 100644 index 00000000..6b6600fe --- /dev/null +++ b/lib/approval-line/table/approval-line-table-toolbar-actions.tsx @@ -0,0 +1,73 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { DataTableViewOptions } from "@/components/data-table/data-table-view-options" +import { Plus, Download, Upload } from "lucide-react" +import { type ApprovalLine } from "../service" + +interface ApprovalLineTableToolbarActionsProps { + table: Table + onCreateLine: () => void +} + +export function ApprovalLineTableToolbarActions({ + table, + onCreateLine, +}: ApprovalLineTableToolbarActionsProps) { + const isFiltered = table.getState().columnFilters.length > 0 + + return ( +
+
+ + table.getColumn("name")?.setFilterValue(event.target.value) + } + className="h-8 w-[150px] lg:w-[250px]" + /> + {isFiltered && ( + + )} +
+
+ + + + +
+
+ ) +} \ No newline at end of file diff --git a/lib/approval-line/table/approval-line-table.tsx b/lib/approval-line/table/approval-line-table.tsx new file mode 100644 index 00000000..21b9972c --- /dev/null +++ b/lib/approval-line/table/approval-line-table.tsx @@ -0,0 +1,130 @@ +"use client"; + +import * as React from 'react'; +import { useDataTable } from '@/hooks/use-data-table'; +import { DataTable } from '@/components/data-table/data-table'; +import { DataTableAdvancedToolbar } from '@/components/data-table/data-table-advanced-toolbar'; +import type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from '@/types/table'; + +import { getColumns } from './approval-line-table-columns'; +import { getApprovalLineList } from '../service'; +import { type ApprovalLine } from '../service'; +import { ApprovalLineTableToolbarActions } from './approval-line-table-toolbar-actions'; +import { CreateApprovalLineSheet } from './create-approval-line-sheet'; +import { UpdateApprovalLineSheet } from './update-approval-line-sheet'; +import { DuplicateApprovalLineSheet } from './duplicate-approval-line-sheet'; +import { DeleteApprovalLineDialog } from './delete-approval-line-dialog'; + +interface ApprovalLineTableProps { + promises: Promise<[ + Awaited>, + ]>; +} + +export function ApprovalLineTable({ promises }: ApprovalLineTableProps) { + const [{ data, pageCount }] = React.use(promises); + + const [rowAction, setRowAction] = + React.useState | null>(null); + + const [showCreateSheet, setShowCreateSheet] = React.useState(false); + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ); + + // 기본 & 고급 필터 필드 + const filterFields: DataTableFilterField[] = []; + const advancedFilterFields: DataTableAdvancedFilterField[] = [ + { + id: 'name', + label: '결재선 이름', + type: 'text', + }, + { + id: 'description', + label: '설명', + type: 'text', + }, + { + id: 'createdAt', + label: '생성일', + type: 'date', + }, + { + id: 'updatedAt', + label: '수정일', + type: 'date', + }, + ]; + + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: 'updatedAt', desc: true }], + columnPinning: { right: ['actions'] }, + }, + getRowId: (row) => String(row.id), + shallow: false, + clearOnDefault: true, + }); + + return ( + <> + + + setShowCreateSheet(true)} + /> + + + + {/* 새 결재선 생성 Sheet */} + + + {/* 결재선 수정 Sheet */} + setRowAction(null)} + line={rowAction?.type === "update" ? rowAction.row.original : null} + /> + + {/* 결재선 복제 Sheet */} + setRowAction(null)} + line={rowAction?.type === "duplicate" ? rowAction.row.original : null} + /> + + {/* 결재선 삭제 Dialog */} + setRowAction(null)} + lines={rowAction?.type === "delete" ? [rowAction.row.original] : []} + showTrigger={false} + onSuccess={() => { + setRowAction(null) + // 테이블 새로고침은 server action에서 자동으로 처리됨 + }} + /> + + ); +} \ No newline at end of file diff --git a/lib/approval-line/table/create-approval-line-sheet.tsx b/lib/approval-line/table/create-approval-line-sheet.tsx new file mode 100644 index 00000000..fdc8cc64 --- /dev/null +++ b/lib/approval-line/table/create-approval-line-sheet.tsx @@ -0,0 +1,224 @@ +"use client" + +import * as React from "react" +import { useForm } from "react-hook-form" +import { zodResolver } from "@hookform/resolvers/zod" +import { Button } from "@/components/ui/button" +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { Textarea } from "@/components/ui/textarea" +import { Separator } from "@/components/ui/separator" +import { toast } from "sonner" +import { Loader2 } from "lucide-react" +import { createApprovalLine } from "../service" +import { type ApprovalLineFormData, ApprovalLineSchema } from "../validations" +import { ApprovalLineSelector } from "@/components/knox/approval/ApprovalLineSelector" +import { OrganizationManagerSelector, type OrganizationManagerItem } from "@/components/common/organization/organization-manager-selector" +import { useSession } from "next-auth/react" + +interface CreateApprovalLineSheetProps { + open: boolean + onOpenChange: (open: boolean) => void +} + +export function CreateApprovalLineSheet({ open, onOpenChange }: CreateApprovalLineSheetProps) { + const { data: session } = useSession(); + const [isSubmitting, setIsSubmitting] = React.useState(false); + + // 고유 ID 생성 함수 (조직 관리자 추가 시 사용) + const generateUniqueId = () => `apln-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`; + + const form = useForm({ + resolver: zodResolver(ApprovalLineSchema), + defaultValues: { + name: "", + description: "", + aplns: [ + // 기안자는 항상 첫 번째로 고정 (플레이스홀더) + { + id: generateUniqueId(), + epId: undefined, + userId: undefined, + emailAddress: undefined, + name: "기안자", + deptName: undefined, + role: "0", + seq: "0", + opinion: "", + }, + ], + }, + }); + + const aplns = form.watch("aplns"); + + // 조직 관리자 추가 (공용 선택기 외 보조 입력 경로) + const addOrganizationManagers = (managers: OrganizationManagerItem[]) => { + const next = [...aplns]; + const uniqueSeqs = Array.from(new Set(next.map((a) => parseInt(a.seq)))); + const maxSeq = uniqueSeqs.length ? Math.max(...uniqueSeqs) : 0; + + managers.forEach((manager, idx) => { + const exists = next.findIndex((a) => a.epId === manager.managerId); + if (exists === -1) { + const newSeqNum = Math.max(1, maxSeq + 1 + idx); + const newSeq = newSeqNum.toString(); + next.push({ + id: generateUniqueId(), + epId: manager.managerId, + userId: undefined, + emailAddress: undefined, + name: manager.managerName, + deptName: manager.departmentName, + role: "1", + seq: newSeq, + opinion: "", + }); + } + }); + + form.setValue("aplns", next, { shouldDirty: true }); + }; + + const onSubmit = async (data: ApprovalLineFormData) => { + setIsSubmitting(true); + try { + if (!session?.user?.id) { + toast.error("로그인이 필요합니다."); + return; + } + + await createApprovalLine({ + name: data.name, + description: data.description, + aplns: data.aplns, + createdBy: Number(session.user.id), + }); + + toast.success("결재선이 성공적으로 생성되었습니다."); + form.reset(); + onOpenChange(false); + } catch { + toast.error("결재선 생성 중 오류가 발생했습니다."); + } finally { + setIsSubmitting(false); + } + }; + + return ( + + + + 결재선 생성 + + 새로운 결재선을 생성합니다. 결재자를 추가하고 순서를 조정할 수 있습니다. + + + +
+
+ + {/* 기본 정보 */} +
+ ( + + 결재선 이름 * + + + + + + )} + /> + + ( + + 설명 + +