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/approval-line/table/update-approval-line-sheet.tsx | |
| parent | cbb4c7fe0b94459162ad5e998bc05cd293e0ff96 (diff) | |
(김준회) 리치텍스트에디터 (결재템플릿을 위한 공통컴포넌트), command-menu 에러 수정, 결재 템플릿 관리, 결재선 관리, ECC RFQ+PR Item 수신시 비즈니스테이블(ProcurementRFQ) 데이터 적재, WSDL 오류 수정
Diffstat (limited to 'lib/approval-line/table/update-approval-line-sheet.tsx')
| -rw-r--r-- | lib/approval-line/table/update-approval-line-sheet.tsx | 264 |
1 files changed, 264 insertions, 0 deletions
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 |
