1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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>
)
}
|