diff options
| author | joonhoekim <26rote@gmail.com> | 2025-08-11 09:34:40 +0000 |
|---|---|---|
| committer | joonhoekim <26rote@gmail.com> | 2025-08-11 09:34:40 +0000 |
| commit | bcd462d6e60871b86008e072f4b914138fc5c328 (patch) | |
| tree | c22876fd6c6e7e48254587848b9dff50cdb8b032 /lib | |
| parent | cbb4c7fe0b94459162ad5e998bc05cd293e0ff96 (diff) | |
(김준회) 리치텍스트에디터 (결재템플릿을 위한 공통컴포넌트), command-menu 에러 수정, 결재 템플릿 관리, 결재선 관리, ECC RFQ+PR Item 수신시 비즈니스테이블(ProcurementRFQ) 데이터 적재, WSDL 오류 수정
Diffstat (limited to 'lib')
26 files changed, 3758 insertions, 27 deletions
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<string, unknown>[]; + 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<typeof v, null> => 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<Array<{ id: string; name: string; aplns: any[]; category: string | null }>> { + 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<string[]> { + 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<ApprovalLine | null> { + 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<ApprovalLine> { + // 중복 이름 체크 + 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<ApprovalLine> { + 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<React.SetStateAction<{ + type: "update" | "delete" | "duplicate"; + row: { original: ApprovalLine }; + } | null>>; +} + + +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ApprovalLine>[] { + return [ + { + id: "select", + header: ({ table }) => ( + <Checkbox + checked={ + table.getIsAllPageRowsSelected() || + (table.getIsSomePageRowsSelected() && "indeterminate") + } + onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-[2px]" + /> + ), + cell: ({ row }) => ( + <Checkbox + checked={row.getIsSelected()} + onCheckedChange={(value) => row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-[2px]" + /> + ), + enableSorting: false, + enableHiding: false, + }, + { + accessorKey: "name", + header: ({ column }) => ( + <DataTableColumnHeader column={column} title="결재선 이름" /> + ), + cell: ({ row }) => { + return ( + <div className="flex space-x-2"> + <span className="max-w-[500px] truncate font-medium"> + {row.getValue("name")} + </span> + </div> + ) + }, + }, + { + accessorKey: "description", + header: ({ column }) => ( + <DataTableColumnHeader column={column} title="설명" /> + ), + cell: ({ row }) => { + return ( + <div className="flex space-x-2"> + <span className="max-w-[500px] truncate"> + {row.getValue("description") || "-"} + </span> + </div> + ) + }, + }, + { + accessorKey: "aplns", + header: ({ column }) => ( + <DataTableColumnHeader column={column} title="결재선" /> + ), + cell: ({ row }) => { + const aplns = row.getValue("aplns") as unknown as Array<{ + seq: string; + name?: string; + emailAddress?: string; + role: string; + }>; + const approvalLineText = formatApprovalLine(aplns); + + return ( + <div className="flex space-x-2"> + <div className="flex flex-col gap-1"> + <div className="max-w-[400px] truncate text-sm"> + {approvalLineText} + <Badge variant="secondary" className="w-fit"> + {aplns?.length || 0}명 + </Badge> + </div> + </div> + </div> + ) + }, + }, + { + accessorKey: "createdAt", + header: ({ column }) => ( + <DataTableColumnHeader column={column} title="생성일" /> + ), + cell: ({ row }) => { + return ( + <div className="flex space-x-2"> + <span className="max-w-[500px] truncate"> + {formatDate(row.getValue("createdAt"))} + </span> + </div> + ) + }, + }, + { + accessorKey: "updatedAt", + header: ({ column }) => ( + <DataTableColumnHeader column={column} title="수정일" /> + ), + cell: ({ row }) => { + return ( + <div className="flex space-x-2"> + <span className="max-w-[500px] truncate"> + {formatDate(row.getValue("updatedAt"))} + </span> + </div> + ) + }, + }, + { + id: "actions", + cell: ({ row }) => { + + return ( + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + aria-label="Open menu" + variant="ghost" + className="flex size-8 p-0 data-[state=open]:bg-muted" + > + <MoreHorizontal className="size-4" aria-hidden="true" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end" className="w-40"> + <DropdownMenuItem + onClick={() => { + setRowAction({ type: "update", row }); + }} + > + <Edit className="mr-2 size-4" aria-hidden="true" /> + 수정하기 + </DropdownMenuItem> + + <DropdownMenuItem + onClick={() => { + setRowAction({ type: "duplicate", row }); + }} + > + <Copy className="mr-2 size-4" aria-hidden="true" /> + 복제하기 + </DropdownMenuItem> + + <DropdownMenuSeparator /> + + <DropdownMenuItem + onClick={() => { + setRowAction({ type: "delete", row }); + }} + className="text-destructive focus:text-destructive" + > + <Trash2 className="mr-2 size-4" aria-hidden="true" /> + 삭제하기 + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + ); + }, + 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<ApprovalLine> + onCreateLine: () => void +} + +export function ApprovalLineTableToolbarActions({ + table, + onCreateLine, +}: ApprovalLineTableToolbarActionsProps) { + const isFiltered = table.getState().columnFilters.length > 0 + + return ( + <div className="flex items-center justify-between"> + <div className="flex flex-1 items-center space-x-2"> + <Input + placeholder="결재선 검색..." + value={(table.getColumn("name")?.getFilterValue() as string) ?? ""} + onChange={(event) => + table.getColumn("name")?.setFilterValue(event.target.value) + } + className="h-8 w-[150px] lg:w-[250px]" + /> + {isFiltered && ( + <Button + variant="ghost" + onClick={() => table.resetColumnFilters()} + className="h-8 px-2 lg:px-3" + > + 초기화 + </Button> + )} + </div> + <div className="flex items-center space-x-2"> + <Button + variant="outline" + size="sm" + className="ml-auto hidden h-8 lg:flex" + > + <Upload className="mr-2 h-4 w-4" /> + 가져오기 + </Button> + <Button + variant="outline" + size="sm" + className="ml-auto hidden h-8 lg:flex" + > + <Download className="mr-2 h-4 w-4" /> + 내보내기 + </Button> + <DataTableViewOptions table={table} /> + <Button + variant="outline" + size="sm" + className="ml-auto h-8" + onClick={onCreateLine} + > + <Plus className="mr-2 h-4 w-4" /> + 결재선 생성 + </Button> + </div> + </div> + ) +}
\ 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<ReturnType<typeof getApprovalLineList>>, + ]>; +} + +export function ApprovalLineTable({ promises }: ApprovalLineTableProps) { + const [{ data, pageCount }] = React.use(promises); + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<ApprovalLine> | null>(null); + + const [showCreateSheet, setShowCreateSheet] = React.useState(false); + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ); + + // 기본 & 고급 필터 필드 + const filterFields: DataTableFilterField<ApprovalLine>[] = []; + const advancedFilterFields: DataTableAdvancedFilterField<ApprovalLine>[] = [ + { + 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 ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <ApprovalLineTableToolbarActions + table={table} + onCreateLine={() => setShowCreateSheet(true)} + /> + </DataTableAdvancedToolbar> + </DataTable> + + {/* 새 결재선 생성 Sheet */} + <CreateApprovalLineSheet + open={showCreateSheet} + onOpenChange={setShowCreateSheet} + /> + + {/* 결재선 수정 Sheet */} + <UpdateApprovalLineSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + line={rowAction?.type === "update" ? rowAction.row.original : null} + /> + + {/* 결재선 복제 Sheet */} + <DuplicateApprovalLineSheet + open={rowAction?.type === "duplicate"} + onOpenChange={() => setRowAction(null)} + line={rowAction?.type === "duplicate" ? rowAction.row.original : null} + /> + + {/* 결재선 삭제 Dialog */} + <DeleteApprovalLineDialog + open={rowAction?.type === "delete"} + onOpenChange={() => 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<ApprovalLineFormData>({ + 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 ( + <Sheet open={open} onOpenChange={onOpenChange}> + <SheetContent className="w-full sm:max-w-4xl overflow-y-auto"> + <SheetHeader> + <SheetTitle>결재선 생성</SheetTitle> + <SheetDescription> + 새로운 결재선을 생성합니다. 결재자를 추가하고 순서를 조정할 수 있습니다. + </SheetDescription> + </SheetHeader> + + <div className="mt-6"> + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> + {/* 기본 정보 */} + <div className="space-y-4"> + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>결재선 이름 *</FormLabel> + <FormControl> + <Input placeholder="결재선 이름을 입력하세요" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="description" + render={({ field }) => ( + <FormItem> + <FormLabel>설명</FormLabel> + <FormControl> + <Textarea placeholder="결재선에 대한 설명을 입력하세요" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + </div> + + <Separator /> + + {/* 결재 경로 */} + <div className="space-y-4"> + <h3 className="text-lg font-semibold">결재 경로</h3> + + <ApprovalLineSelector + value={aplns} + onChange={(next) => form.setValue("aplns", next, { shouldDirty: true })} + placeholder="결재자를 검색하세요..." + domainFilter={{ type: "exclude", domains: ["partners"] }} + maxSelections={10} + /> + + {/* 조직 관리자 추가 (선택 사항) */} + {/* <div className="p-4 border border-dashed border-gray-300 rounded-lg"> + <div className="mb-2"> + <label className="text-sm font-medium text-gray-700">조직 관리자로 추가</label> + <p className="text-xs text-gray-500">조직별 책임자를 검색하여 추가하세요</p> + </div> + <OrganizationManagerSelector + selectedManagers={[]} + onManagersChange={addOrganizationManagers} + placeholder="조직 관리자를 검색하세요..." + maxSelections={10} + /> + </div> */} + </div> + + <Separator /> + + {/* 제출 버튼 */} + <div className="flex justify-end space-x-3"> + <Button + type="button" + variant="outline" + onClick={() => onOpenChange(false)} + disabled={isSubmitting} + > + 취소 + </Button> + <Button type="submit" disabled={isSubmitting}> + {isSubmitting ? ( + <> + <Loader2 className="w-4 h-4 mr-2 animate-spin" /> + 생성 중... + </> + ) : ( + "결재선 생성" + )} + </Button> + </div> + </form> + </Form> + </div> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file diff --git a/lib/approval-line/table/delete-approval-line-dialog.tsx b/lib/approval-line/table/delete-approval-line-dialog.tsx new file mode 100644 index 00000000..aa1d8949 --- /dev/null +++ b/lib/approval-line/table/delete-approval-line-dialog.tsx @@ -0,0 +1,168 @@ +"use client" + +import * as React from "react" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { Badge } from "@/components/ui/badge" +import { toast } from "sonner" +import { Loader2, Trash2, AlertTriangle } from "lucide-react" +import { deleteApprovalLine, getApprovalLineUsage } from "../service" +import { type ApprovalLine } from "../service" + +interface DeleteApprovalLineDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + lines: ApprovalLine[] + showTrigger?: boolean + onSuccess?: () => void +} + +export function DeleteApprovalLineDialog({ + open, + onOpenChange, + lines, + showTrigger = true, + onSuccess, +}: DeleteApprovalLineDialogProps) { + const [isDeleting, setIsDeleting] = React.useState(false) + const [usageInfo, setUsageInfo] = React.useState<{ templateCount: number } | null>(null) + + // 사용량 정보 조회 + React.useEffect(() => { + if (open && lines.length === 1) { + getApprovalLineUsage(lines[0].id).then(setUsageInfo) + } + }, [open, lines]) + + const handleDelete = async () => { + setIsDeleting(true) + + try { + const deletePromises = lines.map((line) => deleteApprovalLine(line.id)) + const results = await Promise.all(deletePromises) + + const successCount = results.filter((r) => r.success).length + const errorCount = results.length - successCount + + if (successCount > 0) { + toast.success(`${successCount}개의 결재선이 삭제되었습니다.`) + onSuccess?.() + onOpenChange(false) + } + + if (errorCount > 0) { + toast.error(`${errorCount}개의 결재선 삭제에 실패했습니다.`) + } + } catch (error) { + toast.error("삭제 중 오류가 발생했습니다.") + } finally { + setIsDeleting(false) + } + } + + const isSingleLine = lines.length === 1 + const line = isSingleLine ? lines[0] : null + + return ( + <Dialog open={open} onOpenChange={onOpenChange}> + <DialogContent> + <DialogHeader> + <DialogTitle className="flex items-center gap-2"> + <Trash2 className="h-5 w-5 text-destructive" /> + 결재선 삭제 + </DialogTitle> + <DialogDescription> + {isSingleLine + ? `"${line?.name}" 결재선을 삭제하시겠습니까?` + : `${lines.length}개의 결재선을 삭제하시겠습니까?`} + </DialogDescription> + </DialogHeader> + + <div className="space-y-4"> + {/* 사용량 정보 표시 */} + {isSingleLine && usageInfo && ( + <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg"> + <div className="flex items-center gap-2 text-yellow-700"> + <AlertTriangle className="w-4 h-4" /> + <span className="font-medium">사용 중인 결재선</span> + </div> + <p className="text-sm text-yellow-600 mt-1"> + 이 결재선은 {usageInfo.templateCount}개의 템플릿에서 사용되고 있습니다. + </p> + </div> + )} + + {/* 삭제할 결재선 목록 */} + <div className="space-y-2"> + <h4 className="text-sm font-medium">삭제할 결재선:</h4> + <div className="space-y-2 max-h-40 overflow-y-auto"> + {lines.map((line) => ( + <div + key={line.id} + className="flex items-center justify-between p-3 border rounded-lg" + > + <div className="flex-1"> + <div className="font-medium">{line.name}</div> + {line.description && ( + <div className="text-sm text-gray-500"> + {line.description} + </div> + )} + <div className="text-xs text-gray-400 mt-1"> + 결재자 {(line.aplns as any[])?.length || 0}명 + </div> + </div> + </div> + ))} + </div> + </div> + + {/* 경고 메시지 */} + <div className="p-4 bg-red-50 border border-red-200 rounded-lg"> + <div className="flex items-center gap-2 text-red-700"> + <AlertTriangle className="w-4 h-4" /> + <span className="font-medium">주의</span> + </div> + <p className="text-sm text-red-600 mt-1"> + 삭제된 결재선은 복구할 수 없습니다. 이 작업은 되돌릴 수 없습니다. + </p> + </div> + </div> + + <DialogFooter> + <Button + variant="outline" + onClick={() => onOpenChange(false)} + disabled={isDeleting} + > + 취소 + </Button> + <Button + variant="destructive" + onClick={handleDelete} + disabled={isDeleting} + > + {isDeleting ? ( + <> + <Loader2 className="w-4 h-4 mr-2 animate-spin" /> + 삭제 중... + </> + ) : ( + <> + <Trash2 className="w-4 h-4 mr-2" /> + 삭제 + </> + )} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ) +}
\ No newline at end of file diff --git a/lib/approval-line/table/duplicate-approval-line-sheet.tsx b/lib/approval-line/table/duplicate-approval-line-sheet.tsx new file mode 100644 index 00000000..0bb3ab2c --- /dev/null +++ b/lib/approval-line/table/duplicate-approval-line-sheet.tsx @@ -0,0 +1,206 @@ +"use client" + +import * as React from "react" +import { useForm } from "react-hook-form" +import { zodResolver } from "@hookform/resolvers/zod" +import { z } from "zod" +import { Button } from "@/components/ui/button" +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { Textarea } from "@/components/ui/textarea" +import { toast } from "sonner" +import { Loader2, Copy } from "lucide-react" +import { duplicateApprovalLine } from "../service" +import { type ApprovalLine } from "../service" +import { useSession } from "next-auth/react" + +const duplicateSchema = z.object({ + name: z.string().min(1, "결재선 이름은 필수입니다"), + description: z.string().optional(), +}) + +type DuplicateFormData = z.infer<typeof duplicateSchema> + +interface DuplicateApprovalLineSheetProps { + open: boolean + onOpenChange: (open: boolean) => void + line: ApprovalLine | null +} + +export function DuplicateApprovalLineSheet({ + open, + onOpenChange, + line, +}: DuplicateApprovalLineSheetProps) { + const { data: session } = useSession() + const [isSubmitting, setIsSubmitting] = React.useState(false) + + const form = useForm<DuplicateFormData>({ + resolver: zodResolver(duplicateSchema), + defaultValues: { + name: line ? `${line.name} (복사본)` : "", + description: line?.description ? `${line.description} (복사본)` : "", + }, + }) + + // line이 변경될 때 폼 초기화 + React.useEffect(() => { + if (line) { + form.reset({ + name: `${line.name} (복사본)`, + description: line.description ? `${line.description} (복사본)` : "", + }) + } + }, [line, form]) + + const onSubmit = async (data: DuplicateFormData) => { + if (!line || !session?.user?.id) { + toast.error("복제할 결재선이 없거나 로그인이 필요합니다.") + return + } + + setIsSubmitting(true) + + try { + const result = await duplicateApprovalLine( + line.id, + data.name, + session.user.id + ) + + if (result.success) { + toast.success("결재선이 성공적으로 복제되었습니다.") + form.reset() + onOpenChange(false) + } else { + toast.error(result.error || "복제에 실패했습니다.") + } + } catch (error) { + toast.error("복제 중 오류가 발생했습니다.") + } finally { + setIsSubmitting(false) + } + } + + if (!line) return null + + return ( + <Sheet open={open} onOpenChange={onOpenChange}> + <SheetContent> + <SheetHeader> + <SheetTitle className="flex items-center gap-2"> + <Copy className="h-5 w-5" /> + 결재선 복제 + </SheetTitle> + <SheetDescription> + "{line.name}" 결재선을 복제하여 새로운 결재선을 만듭니다. + </SheetDescription> + </SheetHeader> + + <div className="mt-6"> + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> + {/* 원본 정보 표시 */} + <div className="p-4 bg-gray-50 border rounded-lg"> + <h4 className="font-medium text-sm mb-2">원본 결재선 정보</h4> + <div className="space-y-2 text-sm"> + <div> + <span className="font-medium">이름:</span> {line.name} + </div> + {line.description && ( + <div> + <span className="font-medium">설명:</span> {line.description} + </div> + )} + <div> + <span className="font-medium">결재자:</span> {(line.aplns as any[])?.length || 0}명 + </div> + </div> + </div> + + {/* 새 결재선 정보 */} + <div className="space-y-4"> + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>새 결재선 이름 *</FormLabel> + <FormControl> + <Input placeholder="새 결재선 이름을 입력하세요" {...field} /> + </FormControl> + <FormDescription> + 원본과 구분할 수 있는 이름을 입력하세요. + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="description" + render={({ field }) => ( + <FormItem> + <FormLabel>설명</FormLabel> + <FormControl> + <Textarea + placeholder="새 결재선에 대한 설명을 입력하세요" + {...field} + /> + </FormControl> + <FormDescription> + 선택사항입니다. 결재선의 용도나 특징을 설명할 수 있습니다. + </FormDescription> + <FormMessage /> + </FormItem> + )} + /> + </div> + + {/* 제출 버튼 */} + <div className="flex justify-end space-x-3"> + <Button + type="button" + variant="outline" + onClick={() => onOpenChange(false)} + disabled={isSubmitting} + > + 취소 + </Button> + <Button type="submit" disabled={isSubmitting}> + {isSubmitting ? ( + <> + <Loader2 className="w-4 h-4 mr-2 animate-spin" /> + 복제 중... + </> + ) : ( + <> + <Copy className="w-4 h-4 mr-2" /> + 결재선 복제 + </> + )} + </Button> + </div> + </form> + </Form> + </div> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file diff --git a/lib/approval-line/table/update-approval-line-sheet.tsx b/lib/approval-line/table/update-approval-line-sheet.tsx new file mode 100644 index 00000000..efc720de --- /dev/null +++ b/lib/approval-line/table/update-approval-line-sheet.tsx @@ -0,0 +1,264 @@ +"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, Edit } from "lucide-react" +import { updateApprovalLine, type ApprovalLine } from "../service" +import { type ApprovalLineFormData, ApprovalLineSchema } from "../validations" +import { OrganizationManagerSelector, type OrganizationManagerItem } from "@/components/common/organization/organization-manager-selector" +import { useSession } from "next-auth/react" +import { ApprovalLineSelector } from "@/components/knox/approval/ApprovalLineSelector" + +interface UpdateApprovalLineSheetProps { + open: boolean + onOpenChange: (open: boolean) => void + line: ApprovalLine | null +} + +// 최소 형태의 Apln 아이템 타입 (line.aplns JSON 구조 대응) +interface MinimalAplnItem { + id: string + epId?: string + userId?: string + emailAddress?: string + name?: string + deptName?: string + role: "0" | "1" | "2" | "3" | "4" | "7" | "9" + seq: string + opinion?: string + [key: string]: unknown +} + +export function UpdateApprovalLineSheet({ open, onOpenChange, line }: UpdateApprovalLineSheetProps) { + 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<ApprovalLineFormData>({ + resolver: zodResolver(ApprovalLineSchema), + defaultValues: { + name: "", + description: "", + aplns: [], + }, + }); + + // line이 변경될 때 폼 초기화 + React.useEffect(() => { + if (line) { + const existingAplns = (line.aplns as unknown as MinimalAplnItem[]) || []; + + // 기안자가 없으면 추가 + const hasDraft = existingAplns.some((a) => String(a.seq) === "0"); + let nextAplns: MinimalAplnItem[] = existingAplns; + + if (!hasDraft) { + nextAplns = [ + { + id: generateUniqueId(), + epId: undefined, + userId: undefined, + emailAddress: undefined, + name: "기안자", + deptName: undefined, + role: "0", + seq: "0", + opinion: "", + }, + ...existingAplns, + ]; + } + + form.reset({ + name: line.name, + description: line.description || "", + aplns: nextAplns as ApprovalLineFormData["aplns"], + }); + } + }, [line, form]); + + 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) => { + if (!line || !session?.user?.id) { + toast.error("수정할 결재선이 없거나 로그인이 필요합니다."); + return; + } + + setIsSubmitting(true); + try { + await updateApprovalLine(line.id, { + name: data.name, + description: data.description, + aplns: data.aplns, + updatedBy: Number(session.user.id), + }); + + toast.success("결재선이 성공적으로 수정되었습니다."); + onOpenChange(false); + } catch { + toast.error("결재선 수정 중 오류가 발생했습니다."); + } finally { + setIsSubmitting(false); + } + }; + + if (!line) return null; + + return ( + <Sheet open={open} onOpenChange={onOpenChange}> + <SheetContent className="w-full sm:max-w-4xl overflow-y-auto"> + <SheetHeader> + <SheetTitle className="flex items-center gap-2"> + <Edit className="h-5 w-5" /> + 결재선 수정 + </SheetTitle> + <SheetDescription> + "{line.name}" 결재선을 수정합니다. 결재자를 추가하고 순서를 조정할 수 있습니다. + </SheetDescription> + </SheetHeader> + + <div className="mt-6"> + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6"> + {/* 기본 정보 */} + <div className="space-y-4"> + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>결재선 이름 *</FormLabel> + <FormControl> + <Input placeholder="결재선 이름을 입력하세요" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="description" + render={({ field }) => ( + <FormItem> + <FormLabel>설명</FormLabel> + <FormControl> + <Textarea placeholder="결재선에 대한 설명을 입력하세요" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + </div> + + <Separator /> + + {/* 결재 경로 */} + <div className="space-y-4"> + <h3 className="text-lg font-semibold">결재 경로</h3> + + <ApprovalLineSelector + value={aplns} + onChange={(next) => form.setValue("aplns", next, { shouldDirty: true })} + placeholder="결재자를 검색하세요..." + domainFilter={{ type: "exclude", domains: ["partners"] }} + maxSelections={10} + /> + + {/* 조직 관리자 추가 (선택 사항) */} + {/* <div className="p-4 border border-dashed border-gray-300 rounded-lg"> + <div className="mb-2"> + <label className="text-sm font-medium text-gray-700">조직 관리자로 추가</label> + <p className="text-xs text-gray-500">조직별 책임자를 검색하여 추가하세요</p> + </div> + <OrganizationManagerSelector + selectedManagers={[]} + onManagersChange={addOrganizationManagers} + placeholder="조직 관리자를 검색하세요..." + maxSelections={10} + /> + </div> */} + </div> + + <Separator /> + + {/* 제출 버튼 */} + <div className="flex justify-end space-x-3"> + <Button + type="button" + variant="outline" + onClick={() => onOpenChange(false)} + disabled={isSubmitting} + > + 취소 + </Button> + <Button type="submit" disabled={isSubmitting}> + {isSubmitting ? ( + <> + <Loader2 className="w-4 h-4 mr-2 animate-spin" /> + 수정 중... + </> + ) : ( + "결재선 수정" + )} + </Button> + </div> + </form> + </Form> + </div> + </SheetContent> + </Sheet> + ) +}
\ No newline at end of file diff --git a/lib/approval-line/utils/format.ts b/lib/approval-line/utils/format.ts new file mode 100644 index 00000000..d74c7d1e --- /dev/null +++ b/lib/approval-line/utils/format.ts @@ -0,0 +1,53 @@ +export interface SimpleApln { + seq: string + name?: string + emailAddress?: string + role: string +} + +export function formatApprovalLine(aplns: SimpleApln[]): string { + if (!aplns || aplns.length === 0) return '결재자 없음' + + const roleMap: Record<string, string> = { + '0': '기안', + '1': '결재', + '2': '합의', + '3': '후결', + '4': '병렬합의', + '7': '병렬결재', + '9': '통보', + } + + const groupedBySeq = aplns.reduce<Record<string, SimpleApln[]>>((groups, apln) => { + const seq = apln.seq + if (!groups[seq]) groups[seq] = [] + groups[seq].push(apln) + return groups + }, {}) + + const sortedSeqs = Object.keys(groupedBySeq).sort((a, b) => parseInt(a) - parseInt(b)) + + return sortedSeqs + .map((seq) => { + const group = groupedBySeq[seq] + const isParallel = group.length > 1 || group.some((apln) => apln.role === '4' || apln.role === '7') + if (isParallel) { + const parallelMembers = group + .map((apln) => { + const name = apln.name || apln.emailAddress || '이름없음' + const role = roleMap[apln.role] || '알수없음' + return `${name}(${role})` + }) + .join(', ') + return `[${parallelMembers}]` + } else { + const apln = group[0] + const name = apln.name || apln.emailAddress || '이름없음' + const role = roleMap[apln.role] || '알수없음' + return `${name}(${role})` + } + }) + .join(' → ') +} + + diff --git a/lib/approval-line/validations.ts b/lib/approval-line/validations.ts new file mode 100644 index 00000000..4f55454a --- /dev/null +++ b/lib/approval-line/validations.ts @@ -0,0 +1,24 @@ +import { z } from 'zod'; +import { SearchParamsApprovalTemplateCache } from '@/lib/approval-template/validations'; + +// 결재선 검색 파라미터 스키마 (기존 템플릿 검증 스키마 재사용) +export const SearchParamsApprovalLineCache = SearchParamsApprovalTemplateCache; + +// 결재선 생성/수정 스키마 +export const ApprovalLineSchema = z.object({ + name: z.string().min(1, '결재선 이름은 필수입니다'), + description: z.string().optional(), + aplns: z.array(z.object({ + id: z.string(), + epId: z.string().optional(), + userId: z.string().optional(), + emailAddress: z.string().email('유효한 이메일 주소를 입력해주세요').optional(), + name: z.string().optional(), + deptName: z.string().optional(), + role: z.enum(['0', '1', '2', '3', '4', '7', '9']), + seq: z.string(), + opinion: z.string().optional() + })).min(1, '최소 1개의 결재 경로가 필요합니다'), +}); + +export type ApprovalLineFormData = z.infer<typeof ApprovalLineSchema>;
\ No newline at end of file diff --git a/lib/approval-template/editor/approval-template-editor.tsx b/lib/approval-template/editor/approval-template-editor.tsx new file mode 100644 index 00000000..f23ac4bd --- /dev/null +++ b/lib/approval-template/editor/approval-template-editor.tsx @@ -0,0 +1,257 @@ +"use client" + +import * as React from "react" +import { toast } from "sonner" +import { Loader, Save, ArrowLeft } from "lucide-react" +import Link from "next/link" + +import { Button } from "@/components/ui/button" +import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card" +import { Input } from "@/components/ui/input" +import RichTextEditor from "@/components/rich-text-editor/RichTextEditor" +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" +import { Separator } from "@/components/ui/separator" +import { Badge } from "@/components/ui/badge" +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" +import { formatApprovalLine } from "@/lib/approval-line/utils/format" +import { getApprovalLineOptionsAction } from "@/lib/approval-line/service" + +import { type ApprovalTemplate } from "@/lib/approval-template/service" +import { type Editor } from "@tiptap/react" +import { updateApprovalTemplateAction } from "@/lib/approval-template/service" +import { useSession } from "next-auth/react" + +interface ApprovalTemplateEditorProps { + templateId: string + initialTemplate: ApprovalTemplate + staticVariables?: Array<{ variableName: string }> + approvalLineOptions: Array<{ id: string; name: string }> + approvalLineCategories: string[] +} + +export function ApprovalTemplateEditor({ templateId, initialTemplate, staticVariables = [], approvalLineOptions, approvalLineCategories }: ApprovalTemplateEditorProps) { + const { data: session } = useSession() + const [rte, setRte] = React.useState<Editor | null>(null) + const [template, setTemplate] = React.useState(initialTemplate) + const [isSaving, startSaving] = React.useTransition() + + // 편집기에 전달할 변수 목록 + // 템플릿(DB) 변수 + 정적(config) 변수 병합 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const dbVariables: string[] = Array.isArray((template as any).variables) + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + (template as any).variables.map((v: any) => v.variableName) + : [] + + const mergedVariables = Array.from(new Set([...dbVariables, ...staticVariables.map((v) => v.variableName)])) + + const variableOptions = mergedVariables.map((name) => ({ label: name, html: `{{${name}}}` })) + + const [form, setForm] = React.useState({ + name: template.name, + subject: template.subject, + content: template.content, + description: template.description ?? "", + category: template.category ?? "", + approvalLineId: (template as { approvalLineId?: string | null }).approvalLineId ?? "", + }) + + const [category, setCategory] = React.useState(form.category ?? (approvalLineCategories[0] ?? "")) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const [lineOptions, setLineOptions] = React.useState(approvalLineOptions as Array<{ id: string; name: string; aplns?: any[]; category?: string | null }>) + const [isLoadingLines, setIsLoadingLines] = React.useState(false) + + React.useEffect(() => { + let active = true + const run = async () => { + setIsLoadingLines(true) + const { success, data } = await getApprovalLineOptionsAction(category || undefined) + if (active) { + setIsLoadingLines(false) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (success && data) setLineOptions(data as any) + // 카테고리 바뀌면 결재선 선택 초기화 + setForm((prev) => ({ ...prev, category, approvalLineId: "" })) + } + } + run() + return () => { + active = false + } + }, [category]) + + function handleChange(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) { + const { name, value } = e.target + setForm((prev) => ({ ...prev, [name]: value })) + } + + function handleSave() { + startSaving(async () => { + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const { success, error, data } = await updateApprovalTemplateAction(templateId, { + name: form.name, + subject: form.subject, + content: form.content, + description: form.description, + category: form.category || undefined, + approvalLineId: form.approvalLineId ? form.approvalLineId : null, + updatedBy: Number(session.user.id), + }) + + if (!success || error || !data) { + toast.error(error ?? "저장에 실패했습니다") + return + } + + setTemplate(data) + toast.success("저장되었습니다") + }) + } + + return ( + <div className="flex flex-1 flex-col gap-4 p-4 md:gap-8 md:p-8"> + {/* Header */} + <div className="flex items-center gap-4"> + <Button variant="ghost" size="icon" asChild> + <Link href="/evcp/approval/template"> + <ArrowLeft className="h-4 w-4" /> + </Link> + </Button> + <div className="flex-1"> + <div className="flex items-center gap-3"> + <h1 className="text-2xl font-semibold">{template.name}</h1> + <Badge variant="outline" className="text-xs"> + 최근 수정: {new Date(template.updatedAt).toLocaleDateString("ko-KR")} + </Badge> + {template.category && ( + <Badge variant="secondary" className="text-xs">{template.category}</Badge> + )} + </div> + <p className="text-sm text-muted-foreground">{template.description || "결재 템플릿 편집"}</p> + </div> + <Button onClick={handleSave} disabled={isSaving}> + {isSaving && <Loader className="mr-2 h-4 w-4 animate-spin" />} + <Save className="mr-2 h-4 w-4" /> 저장 + </Button> + </div> + + <Separator /> + + <Tabs defaultValue="editor" className="flex-1"> + <TabsList className="grid w-full grid-cols-2"> + <TabsTrigger value="editor">편집</TabsTrigger> + <TabsTrigger value="preview">미리보기</TabsTrigger> + </TabsList> + + <TabsContent value="editor" className="mt-4 flex flex-col gap-4"> + <Card> + <CardHeader> + <CardTitle>기본 정보</CardTitle> + </CardHeader> + <CardContent className="space-y-4"> + <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> + <div className="space-y-2"> + <label className="text-sm font-medium">이름</label> + <Input name="name" value={form.name} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">카테고리</label> + <Select + value={category} + onValueChange={(value) => setCategory(value)} + > + <SelectTrigger> + <SelectValue placeholder="카테고리를 선택하세요" /> + </SelectTrigger> + <SelectContent> + {approvalLineCategories.map((cat) => ( + <SelectItem key={cat} value={cat}> + {cat} + </SelectItem> + ))} + </SelectContent> + </Select> + </div> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">설명 (선택)</label> + <Input name="description" value={form.description} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">제목</label> + <Input name="subject" value={form.subject} onChange={handleChange} /> + </div> + <div className="space-y-2"> + <label className="text-sm font-medium">결재선</label> + <Select + value={form.approvalLineId} + onValueChange={(value) => setForm((prev) => ({ ...prev, approvalLineId: value }))} + disabled={!category || isLoadingLines} + > + <SelectTrigger> + <SelectValue placeholder={category ? (isLoadingLines ? "불러오는 중..." : "결재선을 선택하세요") : "카테고리를 먼저 선택하세요"} /> + </SelectTrigger> + <SelectContent> + {lineOptions.map((opt) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const label = opt.aplns ? `${opt.name} — ${formatApprovalLine(opt.aplns as any)}` : opt.name + return ( + <SelectItem key={opt.id} value={opt.id}> + {label} + </SelectItem> + ) + })} + </SelectContent> + </Select> + </div> + </CardContent> + </Card> + + <Card> + <CardHeader> + <CardTitle>HTML 내용</CardTitle> + <CardDescription>표, 이미지, 변수 등을 자유롭게 편집하세요.</CardDescription> + </CardHeader> + <CardContent> + {variableOptions.length > 0 && ( + <div className="mb-4 flex flex-wrap gap-2"> + {variableOptions.map((v: { label: string; html: string }) => ( + <Button + key={v.label} + variant="outline" + size="sm" + onClick={() => rte?.chain().focus().insertContent(v.html).run()} + > + {`{{${v.label}}}`} + </Button> + ))} + </div> + )} + <RichTextEditor + value={form.content} + onChange={(val) => setForm((prev) => ({ ...prev, content: val }))} + onReady={(editor) => setRte(editor)} + height="400px" + /> + </CardContent> + </Card> + </TabsContent> + + <TabsContent value="preview" className="mt-4"> + <Card> + <CardHeader> + <CardTitle>미리보기</CardTitle> + </CardHeader> + <CardContent className="border rounded-md p-4 overflow-auto bg-background"> + <div dangerouslySetInnerHTML={{ __html: form.content }} /> + </CardContent> + </Card> + </TabsContent> + </Tabs> + </div> + ) +} diff --git a/lib/approval-template/service.ts b/lib/approval-template/service.ts new file mode 100644 index 00000000..5dc989d9 --- /dev/null +++ b/lib/approval-template/service.ts @@ -0,0 +1,330 @@ +'use server'; + +import db from '@/db/db'; +import { + and, + asc, + count, + desc, + eq, + ilike, + or, +} from 'drizzle-orm'; + +import { + approvalTemplates, + approvalTemplateVariables, + approvalTemplateHistory, +} from '@/db/schema/knox/approvals'; + +import { filterColumns } from '@/lib/filter-columns'; + +// --------------------------------------------- +// Types +// --------------------------------------------- + +export type ApprovalTemplate = typeof approvalTemplates.$inferSelect; +export type ApprovalTemplateVariable = + typeof approvalTemplateVariables.$inferSelect; +export type ApprovalTemplateHistory = + typeof approvalTemplateHistory.$inferSelect; + +export interface ApprovalTemplateWithVariables extends ApprovalTemplate { + variables: ApprovalTemplateVariable[]; +} + +// --------------------------------------------- +// List & read helpers +// --------------------------------------------- + +interface ListInput { + page: number; + perPage: number; + search?: string; + filters?: Record<string, unknown>[]; + joinOperator?: 'and' | 'or'; + sort?: Array<{ id: string; desc: boolean }>; +} + +export async function getApprovalTemplateList(input: ListInput) { + const offset = (input.page - 1) * input.perPage; + + /* ------------------------------------------------------------------ + * WHERE 절 구성 + * ----------------------------------------------------------------*/ + const advancedWhere = filterColumns({ + table: approvalTemplates, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + // 전역 검색 (name, subject, description, category) + let globalWhere; + if (input.search) { + const s = `%${input.search}%`; + globalWhere = or( + ilike(approvalTemplates.name, s), + ilike(approvalTemplates.subject, s), + ilike(approvalTemplates.description, s), + ilike(approvalTemplates.category, 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 approvalTemplates)) return null; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + const col = approvalTemplates[item.id]; + return item.desc ? desc(col) : asc(col); + }) + .filter((v): v is Exclude<typeof v, null> => v !== null) + : [desc(approvalTemplates.updatedAt)]; + } catch { + orderBy = [desc(approvalTemplates.updatedAt)]; + } + + /* ------------------------------------------------------------------ + * 데이터 조회 + * ----------------------------------------------------------------*/ + const data = await db + .select() + .from(approvalTemplates) + .where(where) + .orderBy(...orderBy) + .limit(input.perPage) + .offset(offset); + + const totalResult = await db + .select({ count: count() }) + .from(approvalTemplates) + .where(where); + + const total = totalResult[0]?.count ?? 0; + const pageCount = Math.ceil(total / input.perPage); + + return { + data, + pageCount, + }; +} + +// ---------------------------------------------------- +// Get single template + variables +// ---------------------------------------------------- +export async function getApprovalTemplate(id: string): Promise<ApprovalTemplateWithVariables | null> { + const [template] = await db + .select() + .from(approvalTemplates) + .where(eq(approvalTemplates.id, id)) + .limit(1); + + if (!template) return null; + + const variables = await db + .select() + .from(approvalTemplateVariables) + .where(eq(approvalTemplateVariables.approvalTemplateId, id)) + .orderBy(approvalTemplateVariables.variableName); + + return { + ...template, + variables, + }; +} + +// ---------------------------------------------------- +// Create template +// ---------------------------------------------------- +interface CreateInput { + name: string; + subject: string; + content: string; + category?: string; + description?: string; + createdBy: number; + approvalLineId?: string | null; + variables?: Array<{ + variableName: string; + variableType: string; + defaultValue?: string; + description?: string; + }>; +} + +export async function createApprovalTemplate(data: CreateInput): Promise<ApprovalTemplateWithVariables> { + // 중복 이름 체크 (옵션) + const existing = await db + .select({ id: approvalTemplates.id }) + .from(approvalTemplates) + .where(eq(approvalTemplates.name, data.name)) + .limit(1); + + if (existing.length > 0) { + throw new Error('이미 존재하는 템플릿 이름입니다.'); + } + + const [newTemplate] = await db + .insert(approvalTemplates) + .values({ + name: data.name, + subject: data.subject, + content: data.content, + category: data.category, + description: data.description, + approvalLineId: data.approvalLineId ?? null, + createdBy: data.createdBy, + }) + .returning(); + + if (data.variables?.length) { + const variableRows = data.variables.map((v) => ({ + approvalTemplateId: newTemplate.id, + variableName: v.variableName, + variableType: v.variableType, + defaultValue: v.defaultValue, + description: v.description, + createdBy: data.createdBy, + })); + await db.insert(approvalTemplateVariables).values(variableRows); + } + + const result = await getApprovalTemplate(newTemplate.id); + if (!result) throw new Error('생성된 템플릿을 조회할 수 없습니다.'); + return result; +} + +// ---------------------------------------------------- +// Update template +// ---------------------------------------------------- +interface UpdateInput { + name?: string; + subject?: string; + content?: string; + description?: string; + category?: string; + approvalLineId?: string | null; + updatedBy: number; +} + +export async function updateApprovalTemplate(id: string, data: UpdateInput): Promise<ApprovalTemplateWithVariables> { + const existing = await getApprovalTemplate(id); + if (!existing) throw new Error('템플릿을 찾을 수 없습니다.'); + + // 버전 계산 - 현재 히스토리 카운트 + 1 + const versionResult = await db + .select({ count: count() }) + .from(approvalTemplateHistory) + .where(eq(approvalTemplateHistory.templateId, id)); + const nextVersion = Number(versionResult[0]?.count ?? 0) + 1; + + // 히스토리 저장 + await db.insert(approvalTemplateHistory).values({ + templateId: id, + version: nextVersion, + subject: existing.subject, + content: existing.content, + changeDescription: '템플릿 업데이트', + changedBy: data.updatedBy, + }); + + // 템플릿 업데이트 + await db + .update(approvalTemplates) + .set({ + name: data.name ?? existing.name, + subject: data.subject ?? existing.subject, + content: data.content ?? existing.content, + description: data.description ?? existing.description, + category: data.category ?? existing.category, + approvalLineId: data.approvalLineId === undefined ? existing.approvalLineId : data.approvalLineId, + updatedAt: new Date(), + }) + .where(eq(approvalTemplates.id, id)); + + const result = await getApprovalTemplate(id); + if (!result) throw new Error('업데이트된 템플릿을 조회할 수 없습니다.'); + return result; +} + +// ---------------------------------------------------- +// Server Actions +// ---------------------------------------------------- +export async function updateApprovalTemplateAction(id: string, data: UpdateInput) { + try { + const updated = await updateApprovalTemplate(id, data) + return { success: true, data: updated } + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '업데이트에 실패했습니다.' + } + } +} + +// ---------------------------------------------------- +// Duplicate template +// ---------------------------------------------------- +export async function duplicateApprovalTemplate( + id: string, + newName: string, + createdBy: number, +): Promise<{ success: boolean; error?: string; data?: ApprovalTemplate }> { + try { + const existing = await getApprovalTemplate(id) + if (!existing) return { success: false, error: '템플릿을 찾을 수 없습니다.' } + + // 새 템플릿 생성 + const duplicated = await createApprovalTemplate({ + name: newName, + subject: existing.subject, + content: existing.content, + category: existing.category ?? undefined, + description: existing.description ? `${existing.description} (복사본)` : undefined, + createdBy, + variables: existing.variables?.map((v) => ({ + variableName: v.variableName, + variableType: v.variableType, + defaultValue: v.defaultValue, + description: v.description, + })), + }) + + return { success: true, data: duplicated } + } catch (error) { + return { success: false, error: error instanceof Error ? error.message : '복제에 실패했습니다.' } + } +} + +// ---------------------------------------------------- +// Delete (soft delete X -> 실제 삭제) +// ---------------------------------------------------- +export async function deleteApprovalTemplate(id: string): Promise<{ success: boolean; error?: string }> { + try { + await db.delete(approvalTemplates).where(eq(approvalTemplates.id, id)); + return { success: true }; + } catch (error) { + return { + success: false, + error: error instanceof Error ? error.message : '삭제에 실패했습니다.', + }; + } +}
\ No newline at end of file diff --git a/lib/approval-template/table/approval-template-table-columns.tsx b/lib/approval-template/table/approval-template-table-columns.tsx new file mode 100644 index 00000000..8447c7d2 --- /dev/null +++ b/lib/approval-template/table/approval-template-table-columns.tsx @@ -0,0 +1,165 @@ +"use client" + +import * as React from 'react'; +import { type ColumnDef } from '@tanstack/react-table'; +import { MoreHorizontal, Copy, Trash, Eye } from 'lucide-react'; +import Link from 'next/link'; + +import { Checkbox } from '@/components/ui/checkbox'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { formatDate } from '@/lib/utils'; +import { DataTableColumnHeaderSimple } from '@/components/data-table/data-table-column-simple-header'; +import { type ApprovalTemplate } from '@/lib/approval-template/service'; +import { type DataTableRowAction } from '@/types/table'; + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<ApprovalTemplate> | null>> +} + +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ApprovalTemplate>[] { + return [ + { + id: 'select', + header: ({ table }) => ( + <Checkbox + checked={ + table.getIsAllPageRowsSelected() || + (table.getIsSomePageRowsSelected() && 'indeterminate') + } + onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + <Checkbox + checked={row.getIsSelected()} + onCheckedChange={(value) => row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + enableSorting: false, + enableHiding: false, + }, + { + accessorKey: 'name', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="템플릿 이름" />, + cell: ({ row: _row }) => { + const t = _row.original; + return ( + <div className="flex flex-col gap-1"> + <span className="font-medium">{t.name}</span> + {t.description && ( + <div className="text-xs text-muted-foreground line-clamp-2">{t.description}</div> + )} + </div> + ); + }, + enableSorting: true, + enableHiding: false, + size: 220, + }, + { + accessorKey: 'subject', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="제목" />, + cell: ({ getValue }) => { + const subject = getValue() as string; + return <div className="text-sm text-muted-foreground">{subject}</div>; + }, + enableSorting: true, + size: 250, + }, + { + accessorKey: 'category', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="카테고리" />, + cell: ({ getValue }) => { + const category = getValue() as string | null; + if (!category) return <div>-</div>; + return <Badge variant="outline">{category}</Badge>; + }, + enableSorting: true, + size: 120, + }, + { + accessorKey: 'createdAt', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />, + cell: ({ cell }) => { + const date = cell.getValue() as Date; + return <div className="text-sm text-muted-foreground">{formatDate(date)}</div>; + }, + enableSorting: true, + size: 200, + }, + { + accessorKey: 'updatedAt', + header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="수정일" />, + cell: ({ cell }) => { + const date = cell.getValue() as Date; + return <div className="text-sm text-muted-foreground">{formatDate(date)}</div>; + }, + enableSorting: true, + size: 200, + }, + { + id: 'actions', + cell: ({ row }) => { + const template = row.original; + + return ( + <DropdownMenu> + <DropdownMenuTrigger asChild> + <Button + aria-label="Open menu" + variant="ghost" + className="flex size-8 p-0 data-[state=open]:bg-muted" + > + <MoreHorizontal className="size-4" aria-hidden="true" /> + </Button> + </DropdownMenuTrigger> + <DropdownMenuContent align="end" className="w-40"> + <DropdownMenuItem asChild> + <Link href={`/evcp/approval/template/${template.id}`}> + <Eye className="mr-2 size-4" aria-hidden="true" /> + 상세 보기 + </Link> + </DropdownMenuItem> + + <DropdownMenuItem + onClick={() => { + setRowAction({ type: 'duplicate', row }); + }} + > + <Copy className="mr-2 size-4" aria-hidden="true" /> + 복제하기 + </DropdownMenuItem> + + <DropdownMenuSeparator /> + + <DropdownMenuItem + onClick={() => { + setRowAction({ type: 'delete', row }); + }} + className="text-destructive focus:text-destructive" + > + <Trash className="mr-2 size-4" aria-hidden="true" /> + 삭제하기 + </DropdownMenuItem> + </DropdownMenuContent> + </DropdownMenu> + ); + }, + enableSorting: false, + enableHiding: false, + size: 80, + }, + ]; +}
\ No newline at end of file diff --git a/lib/approval-template/table/approval-template-table-toolbar-actions.tsx b/lib/approval-template/table/approval-template-table-toolbar-actions.tsx new file mode 100644 index 00000000..08aba97a --- /dev/null +++ b/lib/approval-template/table/approval-template-table-toolbar-actions.tsx @@ -0,0 +1,114 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download, Plus, Trash } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { type ApprovalTemplate } from "@/lib/approval-template/service" +import { toast } from "sonner" +import { DeleteApprovalTemplateDialog } from "./delete-approval-template-dialog" + +interface ApprovalTemplateTableToolbarActionsProps { + table: Table<ApprovalTemplate> + onCreateTemplate: () => void +} + +export function ApprovalTemplateTableToolbarActions({ + table, + onCreateTemplate, +}: ApprovalTemplateTableToolbarActionsProps) { + const [showDeleteDialog, setShowDeleteDialog] = React.useState(false) + + const selectedRows = table.getFilteredSelectedRowModel().rows + const selectedTemplates = selectedRows.map((row) => row.original) + + // CSV 내보내기 + const exportToCsv = React.useCallback(() => { + const headers = [ + "이름", + "제목", + "카테고리", + "생성일", + "수정일", + ] + + const csvData = [ + headers, + ...table.getFilteredRowModel().rows.map((row) => { + const t = row.original + return [ + t.name, + t.subject, + t.category ?? "-", + new Date(t.createdAt).toLocaleDateString("ko-KR"), + new Date(t.updatedAt).toLocaleDateString("ko-KR"), + ] + }), + ] + + const csvContent = csvData + .map((row) => row.map((field) => `"${field}"`).join(",")) + .join("\n") + + const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }) + const link = document.createElement("a") + + if (link.download !== undefined) { + const url = URL.createObjectURL(blob) + link.setAttribute("href", url) + link.setAttribute( + "download", + `approval_templates_${new Date().toISOString().split("T")[0]}.csv`, + ) + link.style.visibility = "hidden" + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + } + + toast.success("템플릿 목록이 CSV로 내보내졌습니다.") + }, [table]) + + return ( + <div className="flex items-center gap-2"> + {/* 새 템플릿 버튼 */} + <Button variant="default" size="sm" onClick={onCreateTemplate}> + <Plus className="mr-2 size-4" aria-hidden="true" /> + 새 템플릿 + </Button> + + {/* CSV 내보내기 */} + <Button variant="outline" size="sm" onClick={exportToCsv}> + <Download className="mr-2 size-4" aria-hidden="true" /> + 내보내기 + </Button> + + {/* 일괄 삭제 */} + {selectedTemplates.length > 0 && ( + <> + <Button + variant="outline" + size="sm" + onClick={() => setShowDeleteDialog(true)} + className="text-destructive hover:text-destructive" + > + <Trash className="mr-2 size-4" aria-hidden="true" /> + 삭제 ({selectedTemplates.length}) + </Button> + + <DeleteApprovalTemplateDialog + open={showDeleteDialog} + onOpenChange={setShowDeleteDialog} + templates={selectedTemplates} + showTrigger={false} + onSuccess={() => { + table.toggleAllRowsSelected(false) + setShowDeleteDialog(false) + }} + /> + </> + )} + </div> + ) +} diff --git a/lib/approval-template/table/approval-template-table.tsx b/lib/approval-template/table/approval-template-table.tsx new file mode 100644 index 00000000..d7f0e478 --- /dev/null +++ b/lib/approval-template/table/approval-template-table.tsx @@ -0,0 +1,135 @@ +"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-template-table-columns'; +import { getApprovalTemplateList } from '../service'; +import { type ApprovalTemplate } from '../service'; +import { ApprovalTemplateTableToolbarActions } from './approval-template-table-toolbar-actions'; +import { CreateApprovalTemplateSheet } from './create-approval-template-sheet'; +import { UpdateApprovalTemplateSheet } from './update-approval-template-sheet'; +import { DuplicateApprovalTemplateSheet } from './duplicate-approval-template-sheet'; +import { DeleteApprovalTemplateDialog } from './delete-approval-template-dialog'; + +interface ApprovalTemplateTableProps { + promises: Promise<[ + Awaited<ReturnType<typeof getApprovalTemplateList>>, + ]>; +} + +export function ApprovalTemplateTable({ promises }: ApprovalTemplateTableProps) { + const [{ data, pageCount }] = React.use(promises); + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<ApprovalTemplate> | null>(null); + + const [showCreateSheet, setShowCreateSheet] = React.useState(false); + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ); + + // 기본 & 고급 필터 필드 (추후 확장 가능) + const filterFields: DataTableFilterField<ApprovalTemplate>[] = []; + const advancedFilterFields: DataTableAdvancedFilterField<ApprovalTemplate>[] = [ + { + id: 'name', + label: '템플릿 이름', + type: 'text', + }, + { + id: 'subject', + label: '제목', + type: 'text', + }, + { + id: 'category', + 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 ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <ApprovalTemplateTableToolbarActions + table={table} + onCreateTemplate={() => setShowCreateSheet(true)} + /> + </DataTableAdvancedToolbar> + </DataTable> + + {/* 새 템플릿 생성 Sheet */} + <CreateApprovalTemplateSheet + open={showCreateSheet} + onOpenChange={setShowCreateSheet} + /> + + {/* 템플릿 수정 Sheet */} + <UpdateApprovalTemplateSheet + open={rowAction?.type === "update"} + onOpenChange={() => setRowAction(null)} + template={rowAction?.type === "update" ? rowAction.row.original : null} + /> + + {/* 템플릿 복제 Sheet */} + <DuplicateApprovalTemplateSheet + open={rowAction?.type === "duplicate"} + onOpenChange={() => setRowAction(null)} + template={rowAction?.type === "duplicate" ? rowAction.row.original : null} + /> + + {/* 템플릿 삭제 Dialog */} + <DeleteApprovalTemplateDialog + open={rowAction?.type === "delete"} + onOpenChange={() => setRowAction(null)} + templates={rowAction?.type === "delete" ? [rowAction.row.original] : []} + showTrigger={false} + onSuccess={() => { + setRowAction(null) + // 테이블 새로고침은 server action에서 자동으로 처리됨 + }} + /> + </> + ); +}
\ No newline at end of file diff --git a/lib/approval-template/table/create-approval-template-sheet.tsx b/lib/approval-template/table/create-approval-template-sheet.tsx new file mode 100644 index 00000000..7e899175 --- /dev/null +++ b/lib/approval-template/table/create-approval-template-sheet.tsx @@ -0,0 +1,174 @@ +"use client" + +import * as React from "react" +import { zodResolver } from "@hookform/resolvers/zod" +import { Loader } from "lucide-react" +import { useForm } from "react-hook-form" +import { toast } from "sonner" +import { z } from "zod" +import { useRouter } from "next/navigation" +import { useSession } from "next-auth/react" + +import { Button } from "@/components/ui/button" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, + FormDescription, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { + Sheet, + SheetClose, + SheetContent, + SheetDescription, + SheetFooter, + SheetHeader, + SheetTitle, +} from "@/components/ui/sheet" + +import { createApprovalTemplate } from "../service" + +const createSchema = z.object({ + name: z.string().min(1, "이름은 필수입니다").max(100, "100자 이하"), + subject: z.string().min(1, "제목은 필수입니다").max(200, "200자 이하"), + category: z.string().optional(), + description: z.string().optional(), +}) + +type CreateSchema = z.infer<typeof createSchema> + +interface CreateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> {} + +export function CreateApprovalTemplateSheet({ ...props }: CreateApprovalTemplateSheetProps) { + const [isPending, startTransition] = React.useTransition() + const router = useRouter() + const { data: session } = useSession() + + const form = useForm<CreateSchema>({ + resolver: zodResolver(createSchema), + defaultValues: { + name: "", + subject: "", + category: undefined, + description: "", + }, + }) + + function onSubmit(values: CreateSchema) { + startTransition(async () => { + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const defaultContent = `<p>{{content}}</p>` + + try { + const template = await createApprovalTemplate({ + name: values.name, + subject: values.subject, + content: defaultContent, + category: values.category || undefined, + description: values.description || undefined, + createdBy: Number(session.user.id), + variables: [], + }) + + toast.success("템플릿이 생성되었습니다") + props.onOpenChange?.(false) + + router.push(`/evcp/approval/template/${template.id}`) + } catch (error) { + toast.error(error instanceof Error ? error.message : "생성에 실패했습니다") + } + }) + } + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-md"> + <SheetHeader className="text-left"> + <SheetTitle>새 템플릿 생성</SheetTitle> + <SheetDescription>새로운 결재 템플릿을 생성합니다.</SheetDescription> + </SheetHeader> + + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4"> + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>템플릿 이름</FormLabel> + <FormControl> + <Input placeholder="예: 견적 승인 요청" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="subject" + render={({ field }) => ( + <FormItem> + <FormLabel>제목</FormLabel> + <FormControl> + <Input placeholder="예: 견적 승인 요청" {...field} /> + </FormControl> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="category" + render={({ field }) => ( + <FormItem> + <FormLabel>카테고리 (선택)</FormLabel> + <FormControl> + <Input placeholder="카테고리" {...field} /> + </FormControl> + <FormDescription>카테고리를 입력하지 않으면 미분류로 저장됩니다.</FormDescription> + <FormMessage /> + </FormItem> + )} + /> + + <FormField + control={form.control} + name="description" + render={({ field }) => ( + <FormItem> + <FormLabel>설명 (선택)</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={isPending}> + {isPending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />} + 생성 후 편집하기 + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +} diff --git a/lib/approval-template/table/delete-approval-template-dialog.tsx b/lib/approval-template/table/delete-approval-template-dialog.tsx new file mode 100644 index 00000000..9fa0a078 --- /dev/null +++ b/lib/approval-template/table/delete-approval-template-dialog.tsx @@ -0,0 +1,123 @@ +"use client" + +import * as React from "react" +import { Loader, Trash } from "lucide-react" +import { toast } from "sonner" + +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { type ApprovalTemplate } from "@/lib/approval-template/service" + +import { deleteApprovalTemplate } from "../service" + +interface DeleteApprovalTemplateDialogProps extends React.ComponentPropsWithRef<typeof Dialog> { + templates: ApprovalTemplate[] + showTrigger?: boolean + onSuccess?: () => void +} + +export function DeleteApprovalTemplateDialog({ + templates, + showTrigger = true, + onSuccess, + ...props +}: DeleteApprovalTemplateDialogProps) { + const [isDeletePending, startDeleteTransition] = React.useTransition() + + const isMultiple = templates.length > 1 + const templateName = isMultiple ? `${templates.length}개 템플릿` : templates[0]?.name + + function onDelete() { + startDeleteTransition(async () => { + if (templates.length === 0) return + + // 여러 개면 순차 삭제 (간단히 처리) + for (const t of templates) { + const result = await deleteApprovalTemplate(t.id) + if (result.error) { + toast.error(result.error) + return + } + } + + props.onOpenChange?.(false) + onSuccess?.() + toast.success( + isMultiple ? `${templates.length}개 템플릿이 삭제되었습니다` : "템플릿이 삭제되었습니다", + ) + + // 새로고침으로 반영 + window.location.reload() + }) + } + + return ( + <Dialog {...props}> + {showTrigger && ( + <DialogTrigger asChild> + <Button + variant="outline" + size="sm" + className="text-destructive hover:text-destructive" + > + <Trash className="mr-2 size-4" aria-hidden="true" /> + 삭제 + </Button> + </DialogTrigger> + )} + <DialogContent> + <DialogHeader> + <DialogTitle>템플릿 삭제 확인</DialogTitle> + <DialogDescription> + 정말로 <strong>{templateName}</strong>을(를) 삭제하시겠습니까? + {!isMultiple && ( + <> + <br />이 작업은 되돌릴 수 없습니다. + </> + )} + </DialogDescription> + </DialogHeader> + + {templates.length > 0 && ( + <div className="rounded-lg bg-muted p-3 max-h-40 overflow-y-auto"> + <h4 className="text-sm font-medium mb-2">삭제될 템플릿</h4> + <div className="space-y-1"> + {templates.map((t) => ( + <div key={t.id} className="text-xs text-muted-foreground"> + <div className="font-medium">{t.name}</div> + <div>ID: <code className="bg-background px-1 rounded">{t.id}</code></div> + </div> + ))} + </div> + </div> + )} + + <DialogFooter> + <Button + variant="outline" + onClick={() => props.onOpenChange?.(false)} + disabled={isDeletePending} + > + 취소 + </Button> + <Button + variant="destructive" + onClick={onDelete} + disabled={isDeletePending} + > + {isDeletePending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />} + {isMultiple ? `${templates.length}개 삭제` : "삭제"} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ) +} diff --git a/lib/approval-template/table/duplicate-approval-template-sheet.tsx b/lib/approval-template/table/duplicate-approval-template-sheet.tsx new file mode 100644 index 00000000..e49000ff --- /dev/null +++ b/lib/approval-template/table/duplicate-approval-template-sheet.tsx @@ -0,0 +1,143 @@ +"use client" + +import * as React from "react" +import { zodResolver } from "@hookform/resolvers/zod" +import { Loader } from "lucide-react" +import { useForm } from "react-hook-form" +import { toast } from "sonner" +import { z } from "zod" +import { useRouter } from "next/navigation" + +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 { type ApprovalTemplate } from "@/lib/approval-template/service" +import { duplicateApprovalTemplate } from "../service" +import { useSession } from "next-auth/react" + +const duplicateSchema = z.object({ + name: z.string().min(1, "템플릿 이름은 필수입니다").max(100, "100자 이내여야 합니다"), +}) + +type DuplicateSchema = z.infer<typeof duplicateSchema> + +interface DuplicateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + template: ApprovalTemplate | null +} + +export function DuplicateApprovalTemplateSheet({ template, ...props }: DuplicateApprovalTemplateSheetProps) { + const [isPending, startTransition] = React.useTransition() + const router = useRouter() + const { data: session } = useSession() + + const form = useForm<DuplicateSchema>({ + resolver: zodResolver(duplicateSchema), + defaultValues: { name: "" }, + }) + + React.useEffect(() => { + if (template) { + form.reset({ name: `${template.name} (복사본)` }) + } + }, [template, form]) + + function onSubmit(values: DuplicateSchema) { + startTransition(async () => { + if (!template) return + if (!session?.user?.id) { + toast.error("로그인이 필요합니다") + return + } + + const { success, error, data } = await duplicateApprovalTemplate( + template.id, + values.name, + Number(session.user.id), + ) + + if (!success || error) { + toast.error(error ?? "복제에 실패했습니다") + return + } + + toast.success("템플릿이 복제되었습니다") + props.onOpenChange?.(false) + + // 상세 페이지로 이동 (id 기반) + if (data?.id) { + router.push(`/evcp/approval/template/${data.id}`) + } else { + window.location.reload() + } + }) + } + + return ( + <Sheet {...props}> + <SheetContent className="flex flex-col gap-6 sm:max-w-md"> + <SheetHeader className="text-left"> + <SheetTitle>템플릿 복제</SheetTitle> + <SheetDescription>기존 템플릿을 복사하여 새로운 템플릿을 생성합니다.</SheetDescription> + </SheetHeader> + + {template && ( + <div className="rounded-lg bg-muted p-3"> + <h4 className="text-sm font-medium mb-2">원본 템플릿</h4> + <div className="space-y-1 text-xs text-muted-foreground"> + <div>이름: {template.name}</div> + <div>ID: <code className="bg-background px-1 rounded">{template.id}</code></div> + <div>카테고리: {template.category ?? "-"}</div> + </div> + </div> + )} + + <Form {...form}> + <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-4"> + <FormField + control={form.control} + name="name" + render={({ field }) => ( + <FormItem> + <FormLabel>새 템플릿 이름</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={isPending}> + {isPending && <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />} + 복제하기 + </Button> + </SheetFooter> + </form> + </Form> + </SheetContent> + </Sheet> + ) +} diff --git a/lib/approval-template/table/update-approval-template-sheet.tsx b/lib/approval-template/table/update-approval-template-sheet.tsx new file mode 100644 index 00000000..05f4069c --- /dev/null +++ b/lib/approval-template/table/update-approval-template-sheet.tsx @@ -0,0 +1,23 @@ +"use client" + +import * as React from "react" +import { Sheet } from "@/components/ui/sheet" +import { type ApprovalTemplate } from "@/lib/approval-template/service" + +interface UpdateApprovalTemplateSheetProps extends React.ComponentPropsWithRef<typeof Sheet> { + template: ApprovalTemplate | null +} + +export function UpdateApprovalTemplateSheet({ template, ...props }: UpdateApprovalTemplateSheetProps) { + // 현재 프로젝트 요구사항 범위 내에서는 상세 편집 페이지 또는 별도 에디터가 준비되지 않았으므로 + // 업데이트 시트는 추후 구현합니다. (이메일 템플릿에서는 사용되지 않아 주석 처리되어 있었음) + // 이를 사용하려 할 경우 안내 문구만 표시합니다. + + return ( + <Sheet {...props}> + <div className="p-6 text-sm text-muted-foreground"> + 템플릿 편집 기능은 아직 구현되지 않았습니다. + </div> + </Sheet> + ) +} diff --git a/lib/approval-template/validations.ts b/lib/approval-template/validations.ts new file mode 100644 index 00000000..3b60e478 --- /dev/null +++ b/lib/approval-template/validations.ts @@ -0,0 +1,27 @@ +import { + createSearchParamsCache, + parseAsArrayOf, + parseAsInteger, + parseAsString, + parseAsStringEnum, +} from 'nuqs/server'; +import { z } from 'zod'; + +import { getFiltersStateParser, getSortingStateParser } from '@/lib/parsers'; +import { approvalTemplates } from '@/db/schema/knox/approvals'; + +export const SearchParamsApprovalTemplateCache = createSearchParamsCache({ + flags: parseAsArrayOf(z.enum(['advancedTable', 'floatingBar'])).withDefault([]), + page: parseAsInteger.withDefault(1), + perPage: parseAsInteger.withDefault(10), + sort: getSortingStateParser<typeof approvalTemplates>().withDefault([ + { id: 'updatedAt', desc: true }, + ]), + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(['and', 'or']).withDefault('and'), + search: parseAsString.withDefault(''), +}); + +export type GetApprovalTemplateSchema = Awaited< + ReturnType<typeof SearchParamsApprovalTemplateCache.parse> +>;
\ No newline at end of file diff --git a/lib/knox-api/approval/service.ts b/lib/knox-api/approval/service.ts index 6ef1b1f6..0bd817a6 100644 --- a/lib/knox-api/approval/service.ts +++ b/lib/knox-api/approval/service.ts @@ -1,7 +1,7 @@ "use server" import db from '@/db/db'; import { ApprovalLine } from "./approval"; -import { approval } from '@/db/schema/knox/approvals'; +import { approvalLogs } from '@/db/schema/knox/approvals'; import { eq, and } from 'drizzle-orm'; // ========== 데이터베이스 서비스 함수들 ========== @@ -21,7 +21,7 @@ export async function saveApprovalToDatabase( aplns: ApprovalLine[] ): Promise<void> { try { - await db.insert(approval).values({ + await db.insert(approvalLogs).values({ apInfId, userId, epId, @@ -51,12 +51,12 @@ export async function updateApprovalStatus( ): Promise<void> { try { await db - .update(approval) + .update(approvalLogs) .set({ status, updatedAt: new Date(), }) - .where(eq(approval.apInfId, apInfId)); + .where(eq(approvalLogs.apInfId, apInfId)); } catch (error) { console.error('결재 상태 업데이트 실패:', error); throw new Error('결재 상태를 업데이트하는 중 오류가 발생했습니다.'); @@ -69,15 +69,15 @@ export async function updateApprovalStatus( export async function getApprovalFromDatabase( apInfId: string, includeDeleted: boolean = false -): Promise<typeof approval.$inferSelect | null> { +): Promise<typeof approvalLogs.$inferSelect | null> { try { const whereCondition = includeDeleted - ? eq(approval.apInfId, apInfId) - : and(eq(approval.apInfId, apInfId), eq(approval.isDeleted, false)); + ? eq(approvalLogs.apInfId, apInfId) + : and(eq(approvalLogs.apInfId, apInfId), eq(approvalLogs.isDeleted, false)); const result = await db .select() - .from(approval) + .from(approvalLogs) .where(whereCondition) .limit(1); @@ -96,17 +96,17 @@ export async function getApprovalsByUser( limit: number = 50, offset: number = 0, includeDeleted: boolean = false -): Promise<typeof approval.$inferSelect[]> { +): Promise<typeof approvalLogs.$inferSelect[]> { try { const whereCondition = includeDeleted - ? eq(approval.userId, userId) - : and(eq(approval.userId, userId), eq(approval.isDeleted, false)); + ? eq(approvalLogs.userId, userId) + : and(eq(approvalLogs.userId, userId), eq(approvalLogs.isDeleted, false)); const result = await db .select() - .from(approval) + .from(approvalLogs) .where(whereCondition) - .orderBy(approval.createdAt) + .orderBy(approvalLogs.createdAt) .limit(limit) .offset(offset); @@ -125,12 +125,12 @@ export async function deleteApprovalFromDatabase( ): Promise<void> { try { await db - .update(approval) + .update(approvalLogs) .set({ isDeleted: true, updatedAt: new Date(), }) - .where(eq(approval.apInfId, apInfId)); + .where(eq(approvalLogs.apInfId, apInfId)); } catch (error) { console.error('결재 데이터 삭제 실패:', error); throw new Error('결재 데이터를 삭제하는 중 오류가 발생했습니다.'); diff --git a/lib/knox-api/organization-service.ts b/lib/knox-api/organization-service.ts new file mode 100644 index 00000000..c90b00f7 --- /dev/null +++ b/lib/knox-api/organization-service.ts @@ -0,0 +1,95 @@ +'use server'; + +import db from '@/db/db'; +import { organization as organizationTable } from '@/db/schema/knox/organization'; +import { count, ilike, isNotNull } from 'drizzle-orm'; + + +// ---------------------------------------------------- +// 조직 관리자 검색 함수 +// ---------------------------------------------------- + +interface SearchOrganizationsForManagerInput { + search: string; + page: number; + perPage: number; +} + +interface SearchOrganizationsForManagerResult { + data: Array<{ + id: string; + departmentCode: string; + departmentName: string; + managerId: string; + managerName: string; + managerTitle: string; + companyCode: string; + companyName: string; + }>; + total: number; + pageCount: number; +} + +export async function searchOrganizationsForManager( + input: SearchOrganizationsForManagerInput +): Promise<SearchOrganizationsForManagerResult> { + const offset = (input.page - 1) * input.perPage; + + // 검색 조건 구성 + const searchTerm = `%${input.search}%`; + + const results = await db + .select({ + id: organizationTable.departmentCode, + departmentCode: organizationTable.departmentCode, + departmentName: organizationTable.departmentName, + managerId: organizationTable.managerId, + managerName: organizationTable.managerName, + managerTitle: organizationTable.managerTitle, + companyCode: organizationTable.companyCode, + companyName: organizationTable.companyName, + }) + .from(organizationTable) + .where( + // 관리자가 있고, 부서명 또는 관리자명으로 검색 + isNotNull(organizationTable.managerId) + ) + .having( + // 부서명 또는 관리자명으로 검색 + ilike(organizationTable.departmentName, searchTerm) || + ilike(organizationTable.managerName, searchTerm) + ) + .orderBy(organizationTable.departmentName) + .limit(input.perPage) + .offset(offset); + + // 전체 개수 조회 + const totalResult = await db + .select({ count: count() }) + .from(organizationTable) + .where( + isNotNull(organizationTable.managerId) + ) + .having( + ilike(organizationTable.departmentName, searchTerm) || + ilike(organizationTable.managerName, searchTerm) + ); + + const total = totalResult[0]?.count ?? 0; + const pageCount = Math.ceil(total / input.perPage); + + return { + data: results as Array<{ + id: string; + departmentCode: string; + departmentName: string; + managerId: string; + managerName: string; + managerTitle: string; + companyCode: string; + companyName: string; + }>, + total, + pageCount, + }; +}
\ No newline at end of file diff --git a/lib/nonsap-sync/procurement-sync-service.ts b/lib/nonsap-sync/procurement-sync-service.ts index 1f719526..c8365a1c 100644 --- a/lib/nonsap-sync/procurement-sync-service.ts +++ b/lib/nonsap-sync/procurement-sync-service.ts @@ -25,7 +25,7 @@ const logger = { async function testOracleConnection(): Promise<boolean> { try { const result = await oracleKnex.raw('SELECT 1 FROM DUAL'); - return result.rows && result.rows.length > 0; + return result && result.length > 0; } catch (error) { logger.error('Oracle DB 연결 테스트 실패:', error); return false; @@ -46,7 +46,7 @@ async function syncPaymentTerms(): Promise<void> { WHERE stc.cd = 'PAYT' `); - const paymentTermsData = oracleData.rows || []; + const paymentTermsData = oracleData || []; logger.info(`Oracle에서 ${paymentTermsData.length}개의 지불조건 데이터 조회`); if (paymentTermsData.length === 0) { @@ -64,7 +64,7 @@ async function syncPaymentTerms(): Promise<void> { // 업데이트할 데이터 준비 const upsertData = paymentTermsData.map((item: { CODE: string; DESCRIPTION: string }) => ({ code: item.CODE, - description: item.DESCRIPTION, + description: item.DESCRIPTION || 'NONSAP에서 설명 기입 요망', isActive: true // 기본값 true })); @@ -112,7 +112,7 @@ async function syncIncoterms(): Promise<void> { WHERE stc.cd = 'INCO' `); - const incotermsData = oracleData.rows || []; + const incotermsData = oracleData || []; logger.info(`Oracle에서 ${incotermsData.length}개의 인코텀즈 데이터 조회`); if (incotermsData.length === 0) { @@ -130,7 +130,7 @@ async function syncIncoterms(): Promise<void> { // 업데이트할 데이터 준비 const upsertData = incotermsData.map((item: { CODE: string; DESCRIPTION: string }) => ({ code: item.CODE, - description: item.DESCRIPTION, + description: item.DESCRIPTION || 'NONSAP에서 설명 기입 요망', isActive: true // 기본값 true })); @@ -181,7 +181,7 @@ async function syncPlaceOfShipping(): Promise<void> { ORDER BY cd.CD asc, cdnm.CDNM asc `); - const placeOfShippingData = oracleData.rows || []; + const placeOfShippingData = oracleData || []; logger.info(`Oracle에서 ${placeOfShippingData.length}개의 선적/하역지 데이터 조회`); if (placeOfShippingData.length === 0) { @@ -199,7 +199,7 @@ async function syncPlaceOfShipping(): Promise<void> { // 업데이트할 데이터 준비 (isActive = "Y"인 경우 true, 그 외는 기본값 true) const upsertData = placeOfShippingData.map((item: { CODE: string; DESCRIPTION: string; ISACTIVE: string }) => ({ code: item.CODE, - description: item.DESCRIPTION, + description: item.DESCRIPTION || 'NONSAP에서 설명 기입 요망', isActive: item.ISACTIVE === 'Y' ? true : true // 기본값 true })); diff --git a/lib/pdftron/serverSDK/createBasicContractPdf.ts b/lib/pdftron/serverSDK/createBasicContractPdf.ts index 706508e6..6b7a4baf 100644 --- a/lib/pdftron/serverSDK/createBasicContractPdf.ts +++ b/lib/pdftron/serverSDK/createBasicContractPdf.ts @@ -1,17 +1,16 @@ -const { PDFNet } = require("@pdftron/pdfnet-node"); -const fs = require('fs').promises; -const path = require('path'); +import { PDFNet } from "@pdftron/pdfnet-node"; +import { promises as fs } from "fs"; import { file as tmpFile } from "tmp-promise"; type CreateBasicContractPdf = ( templateBuffer: Buffer, templateData: { - [key: string]: any; + [key: string]: unknown; } ) => Promise<{ result: boolean; buffer?: ArrayBuffer; - error?: any; + error?: unknown; }>; export const createBasicContractPdf: CreateBasicContractPdf = async ( diff --git a/lib/soap/ecc-mapper.ts b/lib/soap/ecc-mapper.ts new file mode 100644 index 00000000..030d6973 --- /dev/null +++ b/lib/soap/ecc-mapper.ts @@ -0,0 +1,429 @@ +import { debugLog, debugSuccess, debugError } from '@/lib/debug-utils'; +import db from '@/db/db'; +import { + procurementRfqs, + prItems, + procurementRfqDetails, +} from '@/db/schema/procurementRFQ'; +import { + PR_INFORMATION_T_BID_HEADER, + PR_INFORMATION_T_BID_ITEM, +} from '@/db/schema/ECC/ecc'; +import { users } from '@/db/schema'; +import { employee } from '@/db/schema/knox/employee'; +import { eq, inArray } from 'drizzle-orm'; + +// NON-SAP 데이터 처리 +import { oracleKnex } from '@/lib/oracle-db/db'; +import { findUserIdByEmployeeNumber } from '../users/knox-service'; + +// ECC 데이터 타입 정의 +export type ECCBidHeader = typeof PR_INFORMATION_T_BID_HEADER.$inferInsert; +export type ECCBidItem = typeof PR_INFORMATION_T_BID_ITEM.$inferInsert; + +// 비즈니스 테이블 데이터 타입 정의 +export type ProcurementRfqData = typeof procurementRfqs.$inferInsert; +export type PrItemData = typeof prItems.$inferInsert; +export type ProcurementRfqDetailData = + typeof procurementRfqDetails.$inferInsert; + +/** + * 시리즈 판단: 관련 PR 아이템들의 PSPID를 기반으로 결정 + * - 아이템이 1개 이하: null + * - 아이템이 2개 이상이고 PSPID가 모두 동일: "SS" + * - 아이템이 2개 이상이고 PSPID가 서로 다름: "||" + */ +function computeSeriesFromItems(items: ECCBidItem[]): string | null { + if (items.length <= 1) return null; + + const normalize = (v: unknown): string | null => { + if (typeof v !== 'string') return null; + const trimmed = v.trim(); + return trimmed.length > 0 ? trimmed : null; + }; + + const uniquePspids = new Set<string | null>( + items.map((it) => normalize(it.PSPID as string | null | undefined)) + ); + + return uniquePspids.size === 1 ? 'SS' : '||'; +} + +/** + * PERNR(사번)을 기준으로 사용자 ID를 찾는 함수 + */ +async function findUserIdByPernr(pernr: string): Promise<number | null> { + try { + debugLog('PERNR로 사용자 ID 찾기 시작', { pernr }); + + // 현재 users 테이블에 사번을 따로 저장하지 않으므로 knox 기준으로 사번 --> epId --> user.id 순으로 찾기 + // 1. employee 테이블에서 employeeNumber로 epId 찾기 + const employeeResult = await db + .select({ epId: employee.epId }) + .from(employee) + .where(eq(employee.employeeNumber, pernr)) + .limit(1); + + if (employeeResult.length === 0) { + debugError('사번에 해당하는 직원 정보를 찾을 수 없음', { pernr }); + return null; + } + + const epId = employeeResult[0].epId; + debugLog('직원 epId 찾음', { pernr, epId }); + + // 2. users 테이블에서 epId로 사용자 ID 찾기 + const userResult = await db + .select({ id: users.id }) + .from(users) + .where(eq(users.epId, epId)) + .limit(1); + + if (userResult.length === 0) { + debugError('epId에 해당하는 사용자 정보를 찾을 수 없음', { epId }); + return null; + } + + const userId = userResult[0].id; + debugSuccess('사용자 ID 찾음', { pernr, epId, userId }); + return userId; + } catch (error) { + debugError('사용자 ID 찾기 중 오류 발생', { pernr, error }); + return null; + } +} + + + +/** + * 담당자 찾는 함수 (Non-SAP 데이터를 기준으로 찾음) + * Puchasing Group을 CMCTB_CD 에서 CD_CLF='MMA070' 조건으로, CD=EKGRP 조건으로 찾으면, USR_DF_CHAR_9 컬럼이 담당자 사번임. 기준으로 유저를 넣어줄 예정임 + */ +async function findInChargeUserIdByEKGRP(EKGRP: string | null): Promise<number | null> { + try { + debugLog('담당자 찾기 시작', { EKGRP }); + // NonSAP에서 담당자 사번 찾기 + + const result = await oracleKnex + .select('USR_DF_CHAR_9') + .from('CMCTB_CD') + .where('CD_CLF', 'MMA070') + .andWhere('CD', EKGRP) + .limit(1); + + if (result.length === 0) { + debugError('담당자 찾기 중 오류 발생', { EKGRP }); + return null; + } + + const employeeNumber = result[0].USR_DF_CHAR_9; + + // 임시 : Knox API 기준으로 사번에 해당하는 userId 찾기 (nonsap에서 제공하는 유저테이블로 변경 예정) + const userId = await findUserIdByEmployeeNumber(employeeNumber); + + debugSuccess('담당자 찾음', { EKGRP, userId }); + return userId; + } catch (error) { + debugError('담당자 찾기 중 오류 발생', { EKGRP, error }); + return null; + } +} + +// *****************************mapping functions********************************* + +/** + * ECC RFQ 헤더 데이터를 비즈니스 테이블로 매핑 + */ +export async function mapECCRfqHeaderToBusiness( + eccHeader: ECCBidHeader +): Promise<ProcurementRfqData> { + debugLog('ECC RFQ 헤더 매핑 시작', { anfnr: eccHeader.ANFNR }); + + // 날짜 파싱 (실패시 현재 Date 들어감) + let interfacedAt: Date = new Date(); + + if (eccHeader.ZRFQ_TRS_DT != null && eccHeader.ZRFQ_TRS_TM != null) { + try { + // SAP 날짜 형식 (YYYYMMDD) 파싱 + const dateStr = eccHeader.ZRFQ_TRS_DT; + if (dateStr.length === 8) { + const year = parseInt(dateStr.substring(0, 4)); + const month = parseInt(dateStr.substring(4, 6)) - 1; // 0-based + const day = parseInt(dateStr.substring(6, 8)); + const hour = parseInt(eccHeader.ZRFQ_TRS_TM.substring(0, 2)); + const minute = parseInt(eccHeader.ZRFQ_TRS_TM.substring(2, 4)); + const second = parseInt(eccHeader.ZRFQ_TRS_TM.substring(4, 6)); + interfacedAt = new Date(year, month, day, hour, minute, second); + } + } catch (error) { + debugError('날짜 파싱 오류', { + date: eccHeader.ZRFQ_TRS_DT, + time: eccHeader.ZRFQ_TRS_TM, + error, + }); + } + } + + // 담당자 찾기 + const inChargeUserId = await findInChargeUserIdByEKGRP(eccHeader.EKGRP || null); + + // 시리즈는 3가지의 케이스만 온다고 가정한다. (다른 케이스는 잘못된 것) + // 케이스 1. 한 RFQ에서 PR Item이 여러 개고, PSPID 값이 모두 같은 경우 => series 값은 "SS" + // 케이스 2. 한 RFQ에서 PR Item이 여러 개고, PSPID 값이 여러개인 경우 => series 값은 "||"" + // 케이스 3. 한 RFQ에서 PR Item이 하나인 경우 => seires 값은 null + // 만약 위 케이스에 모두 속하지 않는 경우 케이스 3처럼 null 값을 넣는다. + + // 매핑 + const mappedData: ProcurementRfqData = { + rfqCode: eccHeader.ANFNR, // rfqCode=rfqNumber(ANFNR), 혼선이 있을 수 있으나 ECC에는 rfqCode라는 게 별도로 없음. rfqCode=rfqNumber + projectId: null, // PR 아이템 처리 후 업데이트. (로직은 추후 작성) + series: null, // PR 아이템 처리 후 업데이트. (로직은 추후 작성) + // itemGroup: null, // 대표 자재그룹: PR 아이템 처리 후 업데이트. (로직은 추후 작성) + itemCode: null, // 대표 자재코드: PR 아이템 처리 후 업데이트. (로직은 추후 작성) + itemName: null, // 대표 자재명: PR 아이템 처리 후 업데이트. (로직은 추후 작성) + dueDate: null, // eVCP에서 사용하는 컬럼이므로 불필요. + rfqSendDate: null, // eVCP에서 사용하는 컬럼이므로 불필요. + createdAt: interfacedAt, + status: 'RFQ Created', // eVCP에서 사용하는 컬럼, 기본값 RFQ Created 처리 + rfqSealedYn: false, // eVCP에서 사용하는 컬럼, 기본값 false 처리 + picCode: eccHeader.EKGRP || null, // Purchasing Group을 PIC로 사용 (구매측 임직원과 연계된 코드임) + remark: null, // remark 컬럼은 담당자 메모용으로 넣어줄 필요 없음. + sentBy: null, // 보내기 전의 RFQ를 대상으로 하므로 넣어줄 필요 없음. + createdBy: inChargeUserId || 1, + updatedBy: inChargeUserId || 1, + }; + + debugSuccess('ECC RFQ 헤더 매핑 완료', { anfnr: eccHeader.ANFNR }); + return mappedData; +} + +/** + * ECC RFQ 아이템 데이터를 비즈니스 테이블로 매핑 + */ +export function mapECCRfqItemToBusiness( + eccItem: ECCBidItem, + rfqId: number +): PrItemData { + debugLog('ECC RFQ 아이템 매핑 시작', { + anfnr: eccItem.ANFNR, + anfps: eccItem.ANFPS, + }); + + // 날짜 파싱 + let deliveryDate: Date | null = null; + if (eccItem.LFDAT) { + try { + const dateStr = eccItem.LFDAT; + if (dateStr.length === 8) { + const year = parseInt(dateStr.substring(0, 4)); + const month = parseInt(dateStr.substring(4, 6)) - 1; + const day = parseInt(dateStr.substring(6, 8)); + deliveryDate = new Date(year, month, day); + } + } catch (error) { + debugError('아이템 날짜 파싱 오류', { date: eccItem.LFDAT, error }); + } + } + + // TODO: 시리즈인 경우 EBELP(Series PO Item Seq) 를 참조하는 로직 필요? 이 컬럼의 의미 확인 필요 + + + const mappedData: PrItemData = { + procurementRfqsId: rfqId, // PR Item의 부모 RFQ ID [ok] + rfqItem: eccItem.ANFPS || null, // itemNo [ok] + prItem: eccItem.BANPO || null, // ECC PR No [ok] + prNo: eccItem.BANFN || null, // ECC PR No [ok] + materialCode: eccItem.MATNR || null, // ECC Material Number [ok] + materialCategory: eccItem.MATKL || null, // ECC Material Group [ok] + acc: eccItem.SAKTO || null, // ECC G/L Account Number [ok] + materialDescription: eccItem.TXZ01 || null, // ECC Short Text [ok] // TODO: 자재 테이블 참조해서 자재명 넣어주기 ? + size: null, // ECC에서 해당 정보 없음 // TODO: 이시원 프로에게 확인 + deliveryDate, // ECC PR Delivery Date (parsed) + quantity: eccItem.MENGE ? Number(eccItem.MENGE) : null, // ECC PR Quantity [ok] + uom: eccItem.MEINS || null, // ECC PR UOM [ok] + grossWeight: eccItem.BRGEW ? Number(eccItem.BRGEW) : null, // ECC PR Gross Weight [ok] + gwUom: eccItem.GEWEI || null, // ECC PR Gross Weight UOM [ok] + specNo: null, // ECC에서 해당 정보 없음, TODO: 이시원 프로 - material 참조해서 넣어주는건지, PR 마다 고유한건지 확인 + specUrl: null, // ECC에서 해당 정보 없음, TODO: 이시원 프로에게 material 참조해서 넣어주는건지, PR 마다 고유한건지 확인 + trackingNo: null, // TODO: 이시원 프로에게 확인 필요. I/F 정의서 어느 항목인지 추정 불가 + majorYn: false, // 기본값 false 할당, 필요시 eVCP에서 수정 + projectDef: eccItem.PSPID || null, // Project Key 로 처리. // TODO: 프로젝트 테이블 참조해 코드로 처리하기 + projectSc: null, // ECC에서 해당 정보 없음 // TODO: pspid 기준으로 찾아 넣어주기 + projectKl: null, // ECC에서 해당 정보 없음 // TODO: pspid 기준으로 찾아 넣어주기 + projectLc: null, // ECC에서 해당 정보 없음 // TODO: pspid 기준으로 찾아 넣어주기 + projectDl: null, // ECC에서 해당 정보 없음 // TODO: pspid 기준으로 찾아 넣어주기 + remark: null, // remark 컬럼은 담당자 메모용으로 넣어줄 필요 없음. + }; + + debugSuccess('ECC RFQ 아이템 매핑 완료', { + rfqItem: eccItem.ANFPS, + materialCode: eccItem.MATNR, + }); + return mappedData; +} + +/** + * ECC 데이터를 비즈니스 테이블로 일괄 매핑 및 저장 + */ +export async function mapAndSaveECCRfqData( + eccHeaders: ECCBidHeader[], + eccItems: ECCBidItem[] +): Promise<{ success: boolean; message: string; processedCount: number }> { + debugLog('ECC 데이터 일괄 매핑 및 저장 시작', { + headerCount: eccHeaders.length, + itemCount: eccItems.length, + }); + + try { + const result = await db.transaction(async (tx) => { + // 1) 헤더별 관련 아이템 그룹핑 + 시리즈 계산 + 헤더 매핑을 병렬로 수행 + const rfqGroups = await Promise.all( + eccHeaders.map(async (eccHeader) => { + const relatedItems = eccItems.filter((item) => item.ANFNR === eccHeader.ANFNR); + const series = computeSeriesFromItems(relatedItems); + const rfqData = await mapECCRfqHeaderToBusiness(eccHeader); + rfqData.series = series; + return { rfqCode: rfqData.rfqCode, rfqData, relatedItems }; + }) + ); + + const rfqRecords = rfqGroups.map((g) => g.rfqData); + + // 2) RFQ 다건 삽입 (중복은 무시). 반환된 레코드로 일부 ID 매핑 + const inserted = await tx + .insert(procurementRfqs) + .values(rfqRecords) + .onConflictDoNothing() + .returning({ id: procurementRfqs.id, rfqCode: procurementRfqs.rfqCode }); + + const rfqCodeToId = new Map<string, number>(); + for (const row of inserted) { + if (row.rfqCode) { + rfqCodeToId.set(row.rfqCode, row.id); + } + } + + // 3) 반환되지 않은 기존 RFQ 들의 ID 조회하여 매핑 보완 + const allCodes = rfqRecords + .map((r) => r.rfqCode) + .filter((c): c is string => typeof c === 'string' && c.length > 0); + const missingCodes = allCodes.filter((c) => !rfqCodeToId.has(c)); + if (missingCodes.length > 0) { + const existing = await tx + .select({ id: procurementRfqs.id, rfqCode: procurementRfqs.rfqCode }) + .from(procurementRfqs) + .where(inArray(procurementRfqs.rfqCode, missingCodes)); + for (const row of existing) { + if (row.rfqCode) { + rfqCodeToId.set(row.rfqCode, row.id); + } + } + } + + // 4) 모든 아이템을 한 번에 생성할 데이터로 변환 + const allItemsToInsert: PrItemData[] = []; + for (const group of rfqGroups) { + const rfqCode = group.rfqCode; + if (!rfqCode) continue; + const rfqId = rfqCodeToId.get(rfqCode); + if (!rfqId) { + debugError('RFQ ID 매핑 누락', { rfqCode }); + throw new Error(`RFQ ID를 찾을 수 없습니다: ${rfqCode}`); + } + + for (const eccItem of group.relatedItems) { + const itemData = mapECCRfqItemToBusiness(eccItem, rfqId); + allItemsToInsert.push(itemData); + } + } + + // 5) 아이템 일괄 삽입 (chunk 처리로 파라미터 제한 회피) + const ITEM_CHUNK_SIZE = 1000; + for (let i = 0; i < allItemsToInsert.length; i += ITEM_CHUNK_SIZE) { + const chunk = allItemsToInsert.slice(i, i + ITEM_CHUNK_SIZE); + await tx.insert(prItems).values(chunk); + } + + return { processedCount: rfqRecords.length }; + }); + + debugSuccess('ECC 데이터 일괄 처리 완료', { + processedCount: result.processedCount, + }); + + return { + success: true, + message: `${result.processedCount}개의 RFQ 데이터가 성공적으로 처리되었습니다.`, + processedCount: result.processedCount, + }; + } catch (error) { + debugError('ECC 데이터 처리 중 오류 발생', error); + return { + success: false, + message: + error instanceof Error + ? error.message + : '알 수 없는 오류가 발생했습니다.', + processedCount: 0, + }; + } +} + +/** + * ECC 데이터 유효성 검증 + */ +export function validateECCRfqData( + eccHeaders: ECCBidHeader[], + eccItems: ECCBidItem[] +): { isValid: boolean; errors: string[] } { + const errors: string[] = []; + + // 헤더 데이터 검증 + for (const header of eccHeaders) { + if (!header.ANFNR) { + errors.push(`필수 필드 누락: ANFNR (Bidding/RFQ Number)`); + } + if (!header.ZBSART) { + errors.push( + `필수 필드 누락: ZBSART (Bidding Type) - ANFNR: ${header.ANFNR}` + ); + } + } + + // 아이템 데이터 검증 + for (const item of eccItems) { + if (!item.ANFNR) { + errors.push( + `필수 필드 누락: ANFNR (Bidding/RFQ Number) - Item: ${item.ANFPS}` + ); + } + if (!item.ANFPS) { + errors.push(`필수 필드 누락: ANFPS (Item Number) - ANFNR: ${item.ANFNR}`); + } + if (!item.BANFN) { + errors.push( + `필수 필드 누락: BANFN (Purchase Requisition Number) - ANFNR: ${item.ANFNR}, ANFPS: ${item.ANFPS}` + ); + } + if (!item.BANPO) { + errors.push( + `필수 필드 누락: BANPO (Item Number of Purchase Requisition) - ANFNR: ${item.ANFNR}, ANFPS: ${item.ANFPS}` + ); + } + } + + // 헤더와 아이템 간의 관계 검증 + const headerAnfnrs = new Set(eccHeaders.map((h) => h.ANFNR)); + const itemAnfnrs = new Set(eccItems.map((i) => i.ANFNR)); + + for (const anfnr of itemAnfnrs) { + if (!headerAnfnrs.has(anfnr)) { + errors.push(`아이템의 ANFNR이 헤더에 존재하지 않음: ${anfnr}`); + } + } + + return { + isValid: errors.length === 0, + errors, + }; +} diff --git a/lib/users/knox-service.ts b/lib/users/knox-service.ts index d5453072..d6755022 100644 --- a/lib/users/knox-service.ts +++ b/lib/users/knox-service.ts @@ -4,6 +4,8 @@ import { unstable_cache } from "next/cache"; import db from "@/db/db"; import { organization } from "@/db/schema/knox/organization"; import { eq, and, asc } from "drizzle-orm"; +import { users } from "@/db/schema/users"; +import { employee } from "@/db/schema/knox/employee"; // 조직 트리 노드 타입 export interface DepartmentNode { @@ -375,3 +377,38 @@ export async function getCurrentCompanyInfo(): Promise<{ code: string; name: str name: "삼성중공업" }; } + +// 사번으로 user Id 찾기 +export async function findUserIdByEmployeeNumber(employeeNumber: string): Promise<number | null> { + + try { + // 1. 사번 기준으로 email 찾기 + const userEmail = await db + .select({ email: employee.emailAddress }) + .from(employee) + .where(eq(employee.employeeNumber, employeeNumber)) + .limit(1); + + if (userEmail.length === 0) { + console.error('사번에 해당하는 이메일 찾기 실패', { employeeNumber }); + return null; + } + + // 2. 이메일 기준으로 userId 찾기 + const userId = await db + .select({ id: users.id }) + .from(users) + .where(eq(users.email, userEmail[0].email)); + + if (userId.length === 0) { + console.error('이메일에 해당하는 사용자 찾기 실패', { email: userEmail[0].email }); + return null; + } + + return userId[0].id; + + } catch (error) { + console.error('사번에 해당하는 이메일 찾기 실패', { employeeNumber, error }); + return null; + } +}
\ No newline at end of file |
