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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
|
'use client'
import { useState } 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 { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { toast } from 'sonner';
import { Loader2, Plus, Trash2, FileText, AlertCircle } from 'lucide-react';
// API 함수 및 타입
import { submitApproval, submitSecurityApproval, createSubmitApprovalRequest, createApprovalLine } from '@/lib/knox-api/approval/approval';
import type { ApprovalLine, SubmitApprovalRequest } from '@/lib/knox-api/approval/approval';
// Mock 데이터
import { mockApprovalAPI, createMockApprovalLine, getRoleText } from './mocks/approval-mock';
const formSchema = z.object({
subject: z.string().min(1, '제목은 필수입니다'),
contents: z.string().min(1, '내용은 필수입니다'),
contentsType: z.enum(['TEXT', 'HTML', 'MIME']),
docSecuType: z.enum(['PERSONAL', 'CONFIDENTIAL', 'CONFIDENTIAL_STRICT']),
urgYn: z.boolean(),
importantYn: z.boolean(),
notifyOption: z.enum(['0', '1', '2', '3']),
docMngSaveCode: z.enum(['0', '1']),
sbmLang: z.enum(['ko', 'ja', 'zh', 'en']),
timeZone: z.string().default('GMT+9'),
aplns: z.array(z.object({
userId: z.string().min(1, '사용자 ID는 필수입니다'),
emailAddress: z.string().email('유효한 이메일 주소를 입력해주세요').optional(),
role: z.enum(['0', '1', '2', '3', '4', '7', '9']),
seq: z.string(),
opinion: z.string().optional()
})).min(1, '최소 1개의 결재 경로가 필요합니다'),
// 첨부파일 (선택)
attachments: z.any().optional()
});
type FormData = z.infer<typeof formSchema>;
interface ApprovalSubmitProps {
useFakeData?: boolean;
systemId?: string;
onSubmitSuccess?: (apInfId: string) => void;
}
export default function ApprovalSubmit({
useFakeData = false,
systemId = 'EVCP_SYSTEM',
onSubmitSuccess
}: ApprovalSubmitProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [submitResult, setSubmitResult] = useState<{ apInfId: string } | null>(null);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: {
subject: '',
contents: '',
contentsType: 'TEXT',
docSecuType: 'PERSONAL',
urgYn: false,
importantYn: false,
notifyOption: '0',
docMngSaveCode: '0',
sbmLang: 'ko',
timeZone: 'GMT+9',
aplns: [
{
userId: '',
emailAddress: '',
role: '0',
seq: '1',
opinion: ''
}
],
attachments: undefined
}
});
const aplns = form.watch('aplns');
const addApprovalLine = () => {
const newSeq = (aplns.length + 1).toString();
form.setValue('aplns', [...aplns, {
userId: '',
emailAddress: '',
role: '1',
seq: newSeq,
opinion: ''
}]);
};
const removeApprovalLine = (index: number) => {
if (aplns.length > 1) {
const newAplns = aplns.filter((_, i) => i !== index);
// 순서 재정렬
const reorderedAplns = newAplns.map((apln, i) => ({
...apln,
seq: (i + 1).toString()
}));
form.setValue('aplns', reorderedAplns);
}
};
const onSubmit = async (data: FormData) => {
setIsSubmitting(true);
setSubmitResult(null);
try {
// 결재 경로 생성
const approvalLines: ApprovalLine[] = await Promise.all(
data.aplns.map(async (apln) => {
if (useFakeData) {
return createMockApprovalLine({
userId: apln.userId,
emailAddress: apln.emailAddress,
role: apln.role,
seq: apln.seq,
opinion: apln.opinion
});
} else {
return createApprovalLine(
{ userId: apln.userId, emailAddress: apln.emailAddress },
apln.role,
apln.seq,
{ opinion: apln.opinion }
);
}
})
);
// 상신 요청 생성
const attachmentsArray = data.attachments ? Array.from(data.attachments as FileList) : undefined;
const submitRequest: SubmitApprovalRequest = useFakeData
? {
...data,
urgYn: data.urgYn ? 'Y' : 'N',
importantYn: data.importantYn ? 'Y' : 'N',
sbmDt: new Date().toISOString().replace(/-|:|T/g, '').slice(0, 14),
apInfId: 'test-ap-inf-id-' + Date.now(),
aplns: approvalLines,
attachments: attachmentsArray
}
: await createSubmitApprovalRequest(
data.contents,
data.subject,
approvalLines,
{
contentsType: data.contentsType,
docSecuType: data.docSecuType,
urgYn: data.urgYn ? 'Y' : 'N',
importantYn: data.importantYn ? 'Y' : 'N',
notifyOption: data.notifyOption,
docMngSaveCode: data.docMngSaveCode,
sbmLang: data.sbmLang,
timeZone: data.timeZone,
attachments: attachmentsArray
}
);
// API 호출 (보안 등급에 따라 분기)
const isSecure = data.docSecuType === 'CONFIDENTIAL' || data.docSecuType === 'CONFIDENTIAL_STRICT';
const response = useFakeData
? await mockApprovalAPI.submitApproval(submitRequest)
: isSecure
? await submitSecurityApproval(submitRequest, systemId)
: await submitApproval(submitRequest, systemId);
if (response.result === 'SUCCESS') {
setSubmitResult({ apInfId: response.data.apInfId });
toast.success('결재가 성공적으로 상신되었습니다.');
onSubmitSuccess?.(response.data.apInfId);
form.reset();
} else {
toast.error('결재 상신에 실패했습니다.');
}
} catch (error) {
console.error('결재 상신 오류:', error);
toast.error('결재 상신 중 오류가 발생했습니다.');
} finally {
setIsSubmitting(false);
}
};
return (
<Card className="w-full max-w-4xl">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="w-5 h-5" />
결재 상신
</CardTitle>
<CardDescription>
새로운 결재를 상신합니다. {useFakeData && '(테스트 모드)'}
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{submitResult && (
<div className="p-4 bg-green-50 border border-green-200 rounded-lg">
<div className="flex items-center gap-2 text-green-700">
<AlertCircle className="w-4 h-4" />
<span className="font-medium">상신 완료</span>
</div>
<p className="text-sm text-green-600 mt-1">
결재 ID: {submitResult.apInfId}
</p>
</div>
)}
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
{/* 기본 정보 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold">기본 정보</h3>
<FormField
control={form.control}
name="subject"
render={({ field }) => (
<FormItem>
<FormLabel>제목 *</FormLabel>
<FormControl>
<Input placeholder="결재 제목을 입력하세요" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contents"
render={({ field }) => (
<FormItem>
<FormLabel>내용 *</FormLabel>
<FormControl>
<Textarea
placeholder="결재 내용을 입력하세요"
rows={8}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="contentsType"
render={({ field }) => (
<FormItem>
<FormLabel>내용 형식</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="내용 형식 선택" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="TEXT">TEXT</SelectItem>
<SelectItem value="HTML">HTML</SelectItem>
<SelectItem value="MIME">MIME</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="docSecuType"
render={({ field }) => (
<FormItem>
<FormLabel>보안 등급</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="보안 등급 선택" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="PERSONAL">개인</SelectItem>
<SelectItem value="CONFIDENTIAL">기밀</SelectItem>
<SelectItem value="CONFIDENTIAL_STRICT">극기밀</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="urgYn"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>긴급 여부</FormLabel>
<FormDescription>긴급 결재로 처리</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="importantYn"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-3">
<div className="space-y-0.5">
<FormLabel>중요 여부</FormLabel>
<FormDescription>중요 결재로 분류</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
</div>
{/* 첨부 파일 */}
<FormField
control={form.control}
name="attachments"
render={({ field }) => (
<FormItem>
<FormLabel>첨부 파일</FormLabel>
<FormControl>
<Input
type="file"
multiple
onChange={(e) => field.onChange(e.target.files)}
/>
</FormControl>
<FormDescription>필요 시 파일을 선택하세요. (다중 선택 가능)</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<Separator />
{/* 결재 경로 */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">결재 경로</h3>
<Button
type="button"
variant="outline"
size="sm"
onClick={addApprovalLine}
>
<Plus className="w-4 h-4 mr-2" />
결재자 추가
</Button>
</div>
<div className="space-y-3">
{aplns.map((apln, index) => (
<div key={index} className="flex items-center gap-3 p-3 border rounded-lg">
<Badge variant="outline">{index + 1}</Badge>
<div className="flex-1 grid grid-cols-4 gap-3">
<FormField
control={form.control}
name={`aplns.${index}.userId`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input placeholder="사용자 ID" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`aplns.${index}.emailAddress`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input placeholder="이메일 (선택)" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`aplns.${index}.role`}
render={({ field }) => (
<FormItem>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="0">기안</SelectItem>
<SelectItem value="1">결재</SelectItem>
<SelectItem value="2">합의</SelectItem>
<SelectItem value="3">후결</SelectItem>
<SelectItem value="4">병렬합의</SelectItem>
<SelectItem value="7">병렬결재</SelectItem>
<SelectItem value="9">통보</SelectItem>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name={`aplns.${index}.opinion`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input placeholder="의견 (선택)" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex items-center gap-2">
<Badge variant="secondary">
{getRoleText(apln.role)}
</Badge>
{aplns.length > 1 && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => removeApprovalLine(index)}
>
<Trash2 className="w-4 h-4" />
</Button>
)}
</div>
</div>
))}
</div>
</div>
<Separator />
{/* 제출 버튼 */}
<div className="flex justify-end space-x-3">
<Button
type="button"
variant="outline"
onClick={() => form.reset()}
disabled={isSubmitting}
>
초기화
</Button>
<Button type="submit" disabled={isSubmitting}>
{isSubmitting ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
상신 중...
</>
) : (
'결재 상신'
)}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
);
}
|