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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
|
"use client";
import * as React from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
Sheet,
SheetContent,
SheetDescription,
SheetFooter,
SheetHeader,
SheetTitle,
SheetTrigger,
} from "@/components/ui/sheet";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Edit, Plus, Trash2 } from "lucide-react";
import {
updateComplianceQuestion,
getComplianceQuestionOptions,
createComplianceQuestionOption,
deleteComplianceQuestionOption,
getSelectableParentQuestions,
} from "@/lib/compliance/services";
import { QUESTION_TYPES } from "@/db/schema/compliance";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { complianceQuestions } from "@/db/schema/compliance";
const questionSchema = z.object({
questionNumber: z.string().min(1, "질문 번호를 입력하세요"),
questionText: z.string().min(1, "질문 내용을 입력하세요"),
questionType: z.string().min(1, "질문 유형을 선택하세요"),
isRequired: z.boolean(),
hasDetailText: z.boolean(),
hasFileUpload: z.boolean(),
isConditional: z.boolean(),
parentQuestionId: z.number().optional(),
conditionalValue: z.string().optional(),
});
type QuestionFormData = z.infer<typeof questionSchema>;
interface ComplianceQuestionEditDialogProps {
question: typeof complianceQuestions.$inferSelect;
onSuccess?: () => void;
}
export function ComplianceQuestionEditSheet({
question,
onSuccess
}: ComplianceQuestionEditDialogProps) {
const [open, setOpen] = React.useState(false);
const [isLoading, setIsLoading] = React.useState(false);
const router = useRouter();
const [options, setOptions] = React.useState<Array<{ id: number; optionValue: string; optionText: string; allowsOtherInput: boolean; displayOrder: number }>>([]);
const [newOptionValue, setNewOptionValue] = React.useState("");
const [newOptionText, setNewOptionText] = React.useState("");
const [newOptionOther, setNewOptionOther] = React.useState(false);
const [parentOptions, setParentOptions] = React.useState<Array<{ id: number; optionValue: string; optionText: string }>>([]);
const [selectableParents, setSelectableParents] = React.useState<Array<{ id: number; questionNumber: string; questionText: string; questionType: string }>>([]);
const [parentQuestionId, setParentQuestionId] = React.useState<number | null>(question.parentQuestionId || null);
const [showOptionForm, setShowOptionForm] = React.useState(false);
const [showOptionsDeleteDialog, setShowOptionsDeleteDialog] = React.useState(false);
const [pendingQuestionTypeChange, setPendingQuestionTypeChange] = React.useState<string | null>(null);
const form = useForm<QuestionFormData>({
resolver: zodResolver(questionSchema),
defaultValues: {
questionNumber: question.questionNumber,
questionText: question.questionText,
questionType: question.questionType,
isRequired: question.isRequired,
hasDetailText: question.hasDetailText,
hasFileUpload: question.hasFileUpload,
isConditional: !!question.parentQuestionId,
parentQuestionId: question.parentQuestionId || undefined,
conditionalValue: question.conditionalValue || "",
},
});
const isSelectionType = React.useMemo(() => {
return [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((form.getValues("questionType") || "").toUpperCase() as any);
}, [form]);
const loadOptions = React.useCallback(async () => {
if (!isSelectionType) return;
try {
const data = await getComplianceQuestionOptions(question.id);
setOptions(data);
} catch (e) {
console.error("loadOptions error", e);
}
}, [isSelectionType, question.id]);
React.useEffect(() => {
if (open) {
loadOptions();
}
}, [open, loadOptions]);
// 선택 가능한 부모 질문들 로드 (조건부 질문용)
React.useEffect(() => {
const loadSelectableParents = async () => {
if (!open) return;
try {
// 현재 질문과 같은 템플릿의 선택형 질문들만 가져오기
const data = await getSelectableParentQuestions(question.templateId, question.id);
setSelectableParents(data);
} catch (e) {
console.error("loadSelectableParents error", e);
setSelectableParents([]);
}
};
loadSelectableParents();
}, [open, question.templateId, question.id]);
// 부모 질문의 옵션 로드 (조건부 질문용)
React.useEffect(() => {
const loadParentOptions = async () => {
if (!open) return;
if (!parentQuestionId) {
setParentOptions([]);
return;
}
try {
const data = await getComplianceQuestionOptions(parentQuestionId);
setParentOptions(data.map((o: any) => ({ id: o.id, optionValue: o.optionValue, optionText: o.optionText })));
} catch (e) {
console.error("loadParentOptions error", e);
setParentOptions([]);
}
};
loadParentOptions();
}, [open, parentQuestionId]);
const onSubmit = async (data: QuestionFormData) => {
try {
setIsLoading(true);
// 디버깅을 위한 로그
console.log("Edit form data:", data);
console.log("Current isConditional:", data.isConditional);
console.log("Current parentQuestionId:", parentQuestionId);
console.log("Current conditionalValue:", data.conditionalValue);
// 조건부 질문 관련 데이터 처리
const updateData = {
...data,
parentQuestionId: data.isConditional ? parentQuestionId : null,
conditionalValue: data.isConditional ? data.conditionalValue : undefined,
};
// isConditional과 parentQuestionId는 제거 (스키마에 없음)
delete (updateData as any).isConditional;
console.log("Final updateData:", updateData);
await updateComplianceQuestion(question.id, updateData);
toast.success("질문이 성공적으로 수정되었습니다.");
setOpen(false);
// 페이지 새로고침
router.refresh();
if (onSuccess) {
onSuccess();
}
} catch (error) {
console.error("Error updating question:", error);
// 중복 질문번호 오류 처리
if (error instanceof Error && error.message === "DUPLICATE_QUESTION_NUMBER") {
form.setError("questionNumber", {
type: "manual",
message: "이미 사용 중인 질문번호입니다."
});
toast.error("이미 사용 중인 질문번호입니다.");
} else {
toast.error("질문 수정 중 오류가 발생했습니다.");
}
} finally {
setIsLoading(false);
}
};
return (
<Sheet open={open} onOpenChange={setOpen}>
<SheetTrigger asChild>
<Button variant="ghost" size="sm">
<Edit className="h-4 w-4" />
</Button>
</SheetTrigger>
<SheetContent className="sm:max-w-[500px] overflow-y-auto">
<SheetHeader>
<SheetTitle>질문 수정</SheetTitle>
<SheetDescription>
질문 내용을 수정합니다.
</SheetDescription>
</SheetHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="questionNumber"
render={({ field }) => (
<FormItem>
<FormLabel>질문 번호</FormLabel>
<FormControl>
<Input placeholder="Q1" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{/* 필수 질문과 조건부 질문 체크박스 */}
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="isRequired"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel>필수 질문</FormLabel>
<FormDescription>
응답자가 반드시 답변해야 하는 질문
</FormDescription>
</div>
</FormItem>
)}
/>
<FormField
control={form.control}
name="isConditional"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel>조건부 질문</FormLabel>
<FormDescription>
특정 조건에 따라 표시되는 질문
</FormDescription>
</div>
</FormItem>
)}
/>
</div>
<FormField
control={form.control}
name="questionText"
render={({ field }) => (
<FormItem>
<FormLabel>질문 내용</FormLabel>
<FormControl>
<Textarea
placeholder="질문 내용을 입력하세요"
className="min-h-[100px]"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="questionType"
render={({ field }) => (
<FormItem>
<FormLabel>질문 유형</FormLabel>
<Select
onValueChange={(newValue) => {
const currentType = field.value;
const isCurrentSelectionType = [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((currentType || "").toUpperCase() as any);
const isNewSelectionType = [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes(newValue.toUpperCase() as any);
// 선택형에서 비선택형으로 변경하고 기존 옵션이 있는 경우
if (isCurrentSelectionType && !isNewSelectionType && options.length > 0) {
setPendingQuestionTypeChange(newValue);
setShowOptionsDeleteDialog(true);
} else {
field.onChange(newValue);
}
}}
defaultValue={(field.value || "").toUpperCase()}
>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="질문 유형을 선택하세요" />
</SelectTrigger>
</FormControl>
<SelectContent>
{Object.entries(QUESTION_TYPES).map(([key, value]) => (
<SelectItem key={key} value={value}>
{value}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
{isSelectionType && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="text-sm font-medium">옵션 관리</div>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => {
setNewOptionValue("");
setNewOptionText("");
setNewOptionOther(false);
// 옵션 추가 모드 활성화
setShowOptionForm(true);
}}
>
<Plus className="h-4 w-4 mr-1" />
옵션 추가
</Button>
</div>
{/* 옵션 추가 폼 */}
{showOptionForm && (
<div className="space-y-3 p-3 border rounded-lg bg-muted/50">
<div className="grid grid-cols-2 gap-3">
<div>
<Input
value={newOptionValue}
onChange={(e) => setNewOptionValue(e.target.value)}
placeholder="option_value (예: YES)"
/>
</div>
<div>
<Input
value={newOptionText}
onChange={(e) => setNewOptionText(e.target.value)}
placeholder="option_text (표시 라벨)"
/>
</div>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Checkbox
checked={newOptionOther}
onCheckedChange={(v) => setNewOptionOther(Boolean(v))}
/>
<span className="text-sm text-muted-foreground">기타 허용</span>
</div>
<div className="flex gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={async () => {
if (!newOptionValue || !newOptionText) {
toast.error("option_value와 option_text를 입력하세요.");
return;
}
try {
await createComplianceQuestionOption({
questionId: question.id,
optionValue: newOptionValue.toUpperCase(),
optionText: newOptionText,
allowsOtherInput: newOptionOther,
displayOrder: (options?.length || 0) + 1,
});
setNewOptionValue("");
setNewOptionText("");
setNewOptionOther(false);
setShowOptionForm(false);
await loadOptions();
toast.success("옵션이 추가되었습니다.");
} catch (e) {
console.error(e);
toast.error("옵션 추가 중 오류가 발생했습니다.");
}
}}
>
등록
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setShowOptionForm(false);
setNewOptionValue("");
setNewOptionText("");
setNewOptionOther(false);
}}
>
취소
</Button>
</div>
</div>
</div>
)}
<div className="space-y-2">
{options.length === 0 ? (
<div className="text-xs text-muted-foreground">등록된 옵션이 없습니다.</div>
) : (
options.map((opt) => (
<div key={opt.id} className="flex items-center gap-3 rounded border p-2">
<div className="text-xs text-muted-foreground w-10">#{opt.displayOrder}</div>
<div className="text-sm font-mono">{opt.optionValue}</div>
<div className="text-sm flex-1">{opt.optionText}</div>
{opt.allowsOtherInput && <Badge variant="secondary">기타 허용</Badge>}
<Button
type="button"
variant="ghost"
size="icon"
onClick={async () => {
try {
await deleteComplianceQuestionOption(opt.id);
await loadOptions();
toast.success("옵션이 삭제되었습니다.");
} catch (e) {
console.error(e);
toast.error("옵션 삭제 중 오류가 발생했습니다.");
}
}}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))
)}
</div>
</div>
)}
{/* 조건부 질문일 때만 부모 질문과 조건값 표시 */}
{form.watch("isConditional") && (
<div className="space-y-2">
{/* 조건 질문 선택 */}
<div>
<FormLabel>조건 질문</FormLabel>
<Select onValueChange={(v) => setParentQuestionId(Number(v))} value={String(parentQuestionId || "")}>
<SelectTrigger>
<SelectValue placeholder="조건 기준 질문을 선택하세요">
{parentQuestionId ? (
<div className="truncate max-w-[300px] text-left">
{selectableParents.find(p => p.id === parentQuestionId)?.questionText}
</div>
) : null}
</SelectValue>
</SelectTrigger>
<SelectContent>
{selectableParents.map((p) => (
<SelectItem key={p.id} value={String(p.id)}>
{p.questionText}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* 조건값 선택 */}
<FormField
control={form.control}
name="conditionalValue"
render={({ field }) => (
<FormItem className="space-y-1">
<FormLabel>조건값</FormLabel>
{parentOptions.length > 0 ? (
<>
<Select onValueChange={field.onChange} defaultValue={(field.value || "").toString()}>
<SelectTrigger>
<SelectValue placeholder="조건값을 선택하세요" />
</SelectTrigger>
<SelectContent>
{parentOptions.map((opt) => (
<SelectItem key={opt.id} value={opt.optionValue}>
{opt.optionValue}
</SelectItem>
))}
</SelectContent>
</Select>
</>
) : (
<>
<FormControl>
<Input placeholder="먼저 부모 질문을 선택하세요" disabled />
</FormControl>
<FormDescription>조건 질문을 선택하세요.</FormDescription>
</>
)}
<FormMessage />
</FormItem>
)}
/>
</div>
)}
<SheetFooter>
<Button
type="button"
variant="outline"
onClick={() => setOpen(false)}
disabled={isLoading}
>
취소
</Button>
<Button type="submit" disabled={isLoading}>
{isLoading ? "수정 중..." : "질문 수정"}
</Button>
</SheetFooter>
</form>
</Form>
</SheetContent>
{/* 옵션 삭제 확인 다이얼로그 */}
<Dialog open={showOptionsDeleteDialog} onOpenChange={setShowOptionsDeleteDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>옵션 삭제 확인</DialogTitle>
<DialogDescription>
질문 유형을 변경하면 기존 옵션들이 모두 삭제됩니다. 계속하시겠습니까?
</DialogDescription>
</DialogHeader>
<div className="py-4">
<div className="bg-muted p-4 rounded-lg">
<h4 className="font-medium mb-2">삭제될 옵션들:</h4>
{options.map((option, index) => (
<div key={option.id} className="text-sm text-muted-foreground mb-1">
<strong>옵션 {index + 1}:</strong> {option.optionValue} - {option.optionText}
</div>
))}
</div>
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => {
setShowOptionsDeleteDialog(false);
setPendingQuestionTypeChange(null);
}}
>
취소
</Button>
<Button
type="button"
variant="destructive"
onClick={async () => {
try {
// 옵션들을 삭제
for (const option of options) {
await deleteComplianceQuestionOption(option.id);
}
setOptions([]);
// 질문 유형 변경
if (pendingQuestionTypeChange) {
form.setValue("questionType", pendingQuestionTypeChange);
}
toast.success("옵션이 삭제되고 질문 유형이 변경되었습니다.");
setShowOptionsDeleteDialog(false);
setPendingQuestionTypeChange(null);
} catch (error) {
console.error("Error deleting options:", error);
toast.error("옵션 삭제 중 오류가 발생했습니다.");
}
}}
>
옵션 삭제 및 유형 변경
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Sheet>
);
}
|