diff options
Diffstat (limited to 'lib/approval-line/table/create-approval-line-sheet.tsx')
| -rw-r--r-- | lib/approval-line/table/create-approval-line-sheet.tsx | 224 |
1 files changed, 224 insertions, 0 deletions
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 |
