diff options
Diffstat (limited to 'lib/approval-line/table')
7 files changed, 1262 insertions, 0 deletions
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 |
