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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
|
"use client";
import * as React from "react";
import { Loader2, Send, X } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@/components/ui/drawer";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useMediaQuery } from "@/hooks/use-media-query";
import {
ApprovalLineSelector,
type ApprovalLineItem
} from "@/components/knox/approval/ApprovalLineSelector";
import {
getApprovalTemplateByName,
replaceTemplateVariables
} from "./template-utils";
/**
* 결재 미리보기 다이얼로그 Props
*/
export interface ApprovalPreviewDialogProps {
/** 다이얼로그 열림 상태 */
open: boolean;
/** 다이얼로그 열림 상태 변경 핸들러 */
onOpenChange: (open: boolean) => void;
/** 템플릿 이름 (DB에서 조회) */
templateName: string;
/** 템플릿 변수 ({{변수명}} 형태로 치환) */
variables: Record<string, string>;
/** 결재 제목 */
title: string;
/** 현재 사용자 정보 */
currentUser: {
id: number;
epId: string;
name?: string;
email?: string;
deptName?: string;
};
/** 초기 결재선 (선택사항) */
defaultApprovers?: string[];
/** 확인 버튼 클릭 시 콜백 */
onConfirm: (data: {
approvers: string[];
title: string;
}) => Promise<void>;
/** 제목 수정 가능 여부 (기본: true) */
allowTitleEdit?: boolean;
}
/**
* 결재 미리보기 다이얼로그 컴포넌트
*
* **주요 기능:**
* 1. 템플릿 실시간 미리보기 (변수 치환)
* 2. 결재선 선택 (ApprovalLineSelector 활용)
* 3. 제목/설명 수정
* 4. 반응형 UI (Desktop: Dialog, Mobile: Drawer)
*
* **사용 예시:**
* ```tsx
* <ApprovalPreviewDialog
* open={isOpen}
* onOpenChange={setIsOpen}
* templateName="벤더 가입 승인 요청"
* variables={{ "업체명": "ABC 협력업체" }}
* title="협력업체 가입 승인"
* currentUser={{ id: 1, epId: "EP001", name: "홍길동" }}
* onConfirm={async ({ approvers }) => {
* await submitApproval(approvers);
* }}
* />
* ```
*/
export function ApprovalPreviewDialog({
open,
onOpenChange,
templateName,
variables,
title: initialTitle,
currentUser,
defaultApprovers = [],
onConfirm,
allowTitleEdit = true,
}: ApprovalPreviewDialogProps) {
const isDesktop = useMediaQuery("(min-width: 768px)");
// 로딩 상태
const [isLoadingTemplate, setIsLoadingTemplate] = React.useState(false);
const [isSubmitting, setIsSubmitting] = React.useState(false);
// 폼 상태
const [title, setTitle] = React.useState(initialTitle);
const [approvalLines, setApprovalLines] = React.useState<ApprovalLineItem[]>([]);
const [previewHtml, setPreviewHtml] = React.useState<string>("");
// 템플릿 로딩 및 미리보기 생성
React.useEffect(() => {
if (!open) return;
async function loadTemplatePreview() {
try {
setIsLoadingTemplate(true);
// 1. 템플릿 조회
const template = await getApprovalTemplateByName(templateName);
if (!template) {
toast.error(`템플릿을 찾을 수 없습니다: ${templateName}`);
return;
}
// 2. 변수 치환
const renderedHtml = await replaceTemplateVariables(
template.content || "",
variables
);
setPreviewHtml(renderedHtml);
} catch (error) {
console.error("[ApprovalPreviewDialog] 템플릿 로딩 실패:", error);
toast.error("템플릿을 불러오는 중 오류가 발생했습니다.");
} finally {
setIsLoadingTemplate(false);
}
}
loadTemplatePreview();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, templateName]); // variables 제거 - 다이얼로그가 열릴 때만 로드
// 다이얼로그 상태 초기화/리셋
React.useEffect(() => {
if (!open) {
// 다이얼로그가 닫힐 때 상태 초기화
setTitle(initialTitle);
setApprovalLines([]);
setPreviewHtml("");
return;
}
// 다이얼로그가 열릴 때 초기화
setTitle(initialTitle);
// 상신자 추가
const submitter: ApprovalLineItem = {
id: `submitter-${currentUser.id}`,
epId: currentUser.epId,
userId: currentUser.id.toString(),
emailAddress: currentUser.email || "",
name: currentUser.name || "상신자",
deptName: currentUser.deptName,
role: "0", // 상신자
seq: "0",
opinion: "",
};
// 기본 결재자들 추가 (있는 경우)
const defaultLines: ApprovalLineItem[] = defaultApprovers.map((epId, index) => ({
id: `approver-${index}`,
epId: epId,
userId: "", // EP ID로만 식별
emailAddress: "",
name: `결재자 ${index + 1}`,
role: "1", // 결재
seq: (index + 1).toString(),
opinion: "",
}));
setApprovalLines([submitter, ...defaultLines]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]); // open 상태만 감지 - 다이얼로그 열림/닫힘 시에만 초기화
// 결재선 변경 핸들러
const handleApprovalLinesChange = (lines: ApprovalLineItem[]) => {
setApprovalLines(lines);
};
// 제출 핸들러
const handleSubmit = async () => {
try {
// 검증: 결재선 확인
const approvers = approvalLines
.filter((line) => line.role === "1" && line.seq !== "0")
.sort((a, b) => parseInt(a.seq) - parseInt(b.seq));
if (approvers.length === 0) {
toast.error("최소 1명의 결재자를 선택해주세요.");
return;
}
// 검증: 제목 확인
if (!title.trim()) {
toast.error("결재 제목을 입력해주세요.");
return;
}
setIsSubmitting(true);
// EP ID 목록 추출
const approverEpIds = approvers
.map((line) => line.epId)
.filter((epId): epId is string => !!epId);
// 상위 컴포넌트로 데이터 전달
await onConfirm({
approvers: approverEpIds,
title: title.trim(),
});
// 성공 시 다이얼로그 닫기
onOpenChange(false);
} catch (error) {
console.error("[ApprovalPreviewDialog] 제출 실패:", error);
// 에러는 상위 컴포넌트에서 처리 (toast 등)
} finally {
setIsSubmitting(false);
}
};
// 취소 핸들러
const handleCancel = () => {
onOpenChange(false);
};
// 폼 내용
const FormContent = () => (
<div className="space-y-6">
{/* 결재선 설정 */}
<div className="space-y-4">
<div className="space-y-2">
<Label>결재선</Label>
<p className="text-sm text-muted-foreground">
결재자를 검색하여 추가하고, 결재 순서를 설정하세요.
</p>
</div>
<ApprovalLineSelector
value={approvalLines}
onChange={handleApprovalLinesChange}
placeholder="결재자를 검색하세요..."
maxSelections={10}
domainFilter={{ type: "exclude", domains: ["partners"] }}
/>
</div>
{/* 제목 입력 */}
<div className="space-y-2">
<Label htmlFor="title">결재 제목</Label>
<Input
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="결재 제목을 입력하세요"
disabled={!allowTitleEdit || isSubmitting}
/>
</div>
{/* 템플릿 미리보기 */}
<div className="space-y-2">
<Label>문서 미리보기</Label>
<ScrollArea className="h-[400px] w-full rounded-md border bg-gray-50 p-4">
{isLoadingTemplate ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="size-6 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">
템플릿을 불러오는 중...
</span>
</div>
) : (
<div
className="prose prose-sm max-w-none"
dangerouslySetInnerHTML={{ __html: previewHtml }}
/>
)}
</ScrollArea>
</div>
</div>
);
// Desktop: Dialog
if (isDesktop) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl h-[90vh] flex flex-col p-0">
<DialogHeader className="px-6 pt-6 pb-4 border-b">
<DialogTitle>결재 문서 미리보기</DialogTitle>
<DialogDescription>
결재 문서를 확인하고 결재선을 설정한 후 상신하세요.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto px-6 py-4">
<FormContent />
</div>
<DialogFooter className="px-6 py-4 border-t gap-2 sm:space-x-0">
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
>
<X className="size-4 mr-2" />
취소
</Button>
<Button
onClick={handleSubmit}
disabled={isSubmitting || isLoadingTemplate}
>
{isSubmitting ? (
<>
<Loader2 className="size-4 mr-2 animate-spin" />
상신 중...
</>
) : (
<>
<Send className="size-4 mr-2" />
결재 상신
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// Mobile: Drawer
return (
<Drawer open={open} onOpenChange={onOpenChange}>
<DrawerContent className="h-[90vh] flex flex-col">
<DrawerHeader className="border-b">
<DrawerTitle>결재 문서 미리보기</DrawerTitle>
<DrawerDescription>
결재 문서를 확인하고 결재선을 설정한 후 상신하세요.
</DrawerDescription>
</DrawerHeader>
<div className="flex-1 overflow-y-auto px-4 py-4">
<FormContent />
</div>
<DrawerFooter className="border-t gap-2">
<Button
variant="outline"
onClick={handleCancel}
disabled={isSubmitting}
>
<X className="size-4 mr-2" />
취소
</Button>
<Button
onClick={handleSubmit}
disabled={isSubmitting || isLoadingTemplate}
>
{isSubmitting ? (
<>
<Loader2 className="size-4 mr-2 animate-spin" />
상신 중...
</>
) : (
<>
<Send className="size-4 mr-2" />
결재 상신
</>
)}
</Button>
</DrawerFooter>
</DrawerContent>
</Drawer>
);
}
|