diff options
| author | 0-Zz-ang <s1998319@gmail.com> | 2025-08-22 13:47:37 +0900 |
|---|---|---|
| committer | 0-Zz-ang <s1998319@gmail.com> | 2025-08-22 13:47:37 +0900 |
| commit | fefca6304eefea94f41057f9f934b0e19ceb54bb (patch) | |
| tree | f4914faa83e242a68d27feac58ebf0c527302cd2 /lib/compliance/questions | |
| parent | dbdae213e39b82ff8ee565df0774bd2f72f06140 (diff) | |
(박서영)Compliance 설문/응답 리스트 생성
Diffstat (limited to 'lib/compliance/questions')
4 files changed, 1398 insertions, 0 deletions
diff --git a/lib/compliance/questions/compliance-question-create-dialog.tsx b/lib/compliance/questions/compliance-question-create-dialog.tsx new file mode 100644 index 00000000..c0e050ab --- /dev/null +++ b/lib/compliance/questions/compliance-question-create-dialog.tsx @@ -0,0 +1,562 @@ +"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 { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +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 { Checkbox } from "@/components/ui/checkbox"; +import { Badge } from "@/components/ui/badge"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Plus, Trash2 } from "lucide-react"; +import { createComplianceQuestion, createComplianceQuestionOption, getComplianceQuestionsCount, getComplianceQuestions, getComplianceQuestionOptions } from "@/lib/compliance/services"; +import { QUESTION_TYPES } from "@/db/schema/compliance"; +import { toast } from "sonner"; +import { useRouter } from "next/navigation"; + +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(), + conditionalValue: z.string().optional(), +}); + +type QuestionFormData = z.infer<typeof questionSchema>; + +interface ComplianceQuestionCreateDialogProps { + templateId: number; + onSuccess?: () => void; +} + +export function ComplianceQuestionCreateDialog({ + templateId, + onSuccess +}: ComplianceQuestionCreateDialogProps) { + const [open, setOpen] = React.useState(false); + const [isLoading, setIsLoading] = React.useState(false); + const router = useRouter(); + + const form = useForm<QuestionFormData>({ + resolver: zodResolver(questionSchema), + defaultValues: { + questionNumber: "", + questionText: "", + questionType: "", + isRequired: false, + hasDetailText: false, + hasFileUpload: false, + conditionalValue: "", + }, + }); + + // 부모 질문 및 옵션 상태 + const [parentQuestionId, setParentQuestionId] = React.useState<number | "">(""); + const [selectableParents, setSelectableParents] = React.useState<Array<{ id: number; questionNumber: string; questionText: string; questionType: string }>>([]); + const [parentOptions, setParentOptions] = React.useState<Array<{ id: number; optionValue: string; optionText: string }>>([]); + + // 옵션 관리 상태 + const [options, setOptions] = React.useState<Array<{ 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 [showOptionForm, setShowOptionForm] = React.useState(false); + + // 선택형 질문인지 확인 + const isSelectionType = React.useMemo(() => { + const questionType = form.watch("questionType"); + return [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((questionType || "").toUpperCase() as any); + }, [form.watch("questionType")]); + + // 시트/다이얼로그 열릴 때 부모 후보 로드 (같은 템플릿 내 선택형 질문만) + React.useEffect(() => { + if (!open) return; + (async () => { + try { + const qs = await getComplianceQuestions(templateId); + const filtered = (qs || []).filter((q: any) => [QUESTION_TYPES.RADIO, QUESTION_TYPES.CHECKBOX, QUESTION_TYPES.DROPDOWN].includes((q.questionType || "").toUpperCase())); + setSelectableParents(filtered); + } catch (e) { + console.error("load selectable parents error", e); + } + })(); + }, [open, templateId]); + + // 부모 선택 시 옵션 로드 + React.useEffect(() => { + if (!open) return; + (async () => { + if (!parentQuestionId) { setParentOptions([]); return; } + try { + const opts = await getComplianceQuestionOptions(Number(parentQuestionId)); + setParentOptions(opts.map((o: any) => ({ id: o.id, optionValue: o.optionValue, optionText: o.optionText }))); + } catch (e) { + console.error("load parent options error", e); + setParentOptions([]); + } + })(); + }, [open, parentQuestionId]); + + const onSubmit = async (data: QuestionFormData) => { + try { + setIsLoading(true); + + // 새로운 질문의 displayOrder는 기존 질문 개수 + 1 + const currentQuestionsCount = await getComplianceQuestionsCount(templateId); + + const newQuestion = await createComplianceQuestion({ + templateId, + ...data, + parentQuestionId: data.isConditional && parentQuestionId ? Number(parentQuestionId) : null, + displayOrder: currentQuestionsCount + 1, + }); + + // 선택형 질문이고 옵션이 있다면 옵션들도 생성 + if (isSelectionType && options.length > 0 && newQuestion) { + try { + // 옵션들을 순차적으로 생성 + for (let i = 0; i < options.length; i++) { + const option = options[i]; + await createComplianceQuestionOption({ + questionId: newQuestion.id, + optionValue: option.optionValue, + optionText: option.optionText, + allowsOtherInput: option.allowsOtherInput, + displayOrder: i + 1, + }); + } + } catch (optionError) { + console.error("Error creating options:", optionError); + toast.error("질문은 생성되었지만 옵션 생성 중 오류가 발생했습니다."); + } + } + + toast.success("질문이 성공적으로 추가되었습니다."); + setOpen(false); + form.reset(); + setOptions([]); + setShowOptionForm(false); + + // 페이지 새로고침 + router.refresh(); + + if (onSuccess) { + onSuccess(); + } + } catch (error) { + console.error("Error creating 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 ( + <Dialog open={open} onOpenChange={setOpen}> + <DialogTrigger asChild> + <Button variant="outline" size="sm"> + <Plus className="mr-2 h-4 w-4" /> + 질문 추가 + </Button> + </DialogTrigger> + <DialogContent className="sm:max-w-[600px]"> + <DialogHeader> + <DialogTitle>새 질문 추가</DialogTitle> + <DialogDescription> + 템플릿에 새로운 질문을 추가합니다. + </DialogDescription> + </DialogHeader> + + <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> + )} + /> + + <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={field.onChange} defaultValue={field.value}> + <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={() => { + if (!newOptionValue || !newOptionText) { + toast.error("option_value와 option_text를 입력하세요."); + return; + } + const newOption = { + optionValue: newOptionValue.toUpperCase(), + optionText: newOptionText, + allowsOtherInput: newOptionOther, + displayOrder: options.length + 1, + }; + setOptions([...options, newOption]); + setNewOptionValue(""); + setNewOptionText(""); + setNewOptionOther(false); + setShowOptionForm(false); + toast.success("옵션이 추가되었습니다."); + }} + > + 등록 + </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, index) => ( + <div key={index} 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={() => { + const newOptions = options.filter((_, i) => i !== index); + setOptions(newOptions); + toast.success("옵션이 제거되었습니다."); + }} + > + <Trash2 className="h-4 w-4" /> + </Button> + </div> + )) + )} + </div> + </div> + )} + + {/* 조건부 질문 체크박스 */} + + + <div className="grid grid-cols-3 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="hasDetailText" + 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="hasFileUpload" + 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="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> + )} + /> + + {/* 조건부 질문일 때만 부모 질문과 조건값 표시 */} + {form.watch("isConditional") && ( + <div className="space-y-2"> + {/* 조건 질문 선택 */} + <div> + <FormLabel>조건 질문</FormLabel> + <Select onValueChange={(v) => setParentQuestionId(v as any)} value={(parentQuestionId as any) || ""}> + <SelectTrigger> + <SelectValue placeholder="조건 기준 질문을 선택하세요"> + {parentQuestionId ? ( + <div className="truncate max-w-[300px] text-left"> + {selectableParents.find(p => String(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> + )} + + {/* 기존 조건값 입력 필드는 부모/조건값 섹션으로 대체됨 */} + + <DialogFooter> + <Button + type="button" + variant="outline" + onClick={() => setOpen(false)} + disabled={isLoading} + > + 취소 + </Button> + <Button type="submit" disabled={isLoading}> + {isLoading ? "추가 중..." : "질문 추가"} + </Button> + </DialogFooter> + </form> + </Form> + </DialogContent> + </Dialog> + ); +} diff --git a/lib/compliance/questions/compliance-question-delete-dialog.tsx b/lib/compliance/questions/compliance-question-delete-dialog.tsx new file mode 100644 index 00000000..997721db --- /dev/null +++ b/lib/compliance/questions/compliance-question-delete-dialog.tsx @@ -0,0 +1,107 @@ +"use client"; + +import * as React from "react"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +import { Trash2 } from "lucide-react"; +import { deleteComplianceQuestion } from "@/lib/compliance/services"; +import { toast } from "sonner"; +import { useRouter } from "next/navigation"; +import { complianceQuestions } from "@/db/schema/compliance"; + +interface ComplianceQuestionDeleteDialogProps { + question: typeof complianceQuestions.$inferSelect; + onSuccess?: () => void; +} + +export function ComplianceQuestionDeleteDialog({ + question, + onSuccess +}: ComplianceQuestionDeleteDialogProps) { + const [open, setOpen] = React.useState(false); + const [isLoading, setIsLoading] = React.useState(false); + const router = useRouter(); + + const handleDelete = async () => { + try { + setIsLoading(true); + + await deleteComplianceQuestion(question.id); + + toast.success("질문이 성공적으로 삭제되었습니다."); + setOpen(false); + + // 페이지 새로고침 + router.refresh(); + + if (onSuccess) { + onSuccess(); + } + } catch (error) { + console.error("Error deleting question:", error); + toast.error("질문 삭제 중 오류가 발생했습니다."); + } finally { + setIsLoading(false); + } + }; + + return ( + <Dialog open={open} onOpenChange={setOpen}> + <DialogTrigger asChild> + <Button variant="ghost" size="sm"> + <Trash2 className="h-4 w-4" /> + </Button> + </DialogTrigger> + <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> + <p className="text-sm text-muted-foreground"> + <strong>질문 번호:</strong> {question.questionNumber} + </p> + <p className="text-sm text-muted-foreground"> + <strong>질문 내용:</strong> {question.questionText} + </p> + <p className="text-sm text-muted-foreground"> + <strong>질문 유형:</strong> {question.questionType} + </p> + </div> + </div> + + <DialogFooter> + <Button + type="button" + variant="outline" + onClick={() => setOpen(false)} + disabled={isLoading} + > + 취소 + </Button> + <Button + type="button" + variant="destructive" + onClick={handleDelete} + disabled={isLoading} + > + {isLoading ? "삭제 중..." : "질문 삭제"} + </Button> + </DialogFooter> + </DialogContent> + </Dialog> + ); +} diff --git a/lib/compliance/questions/compliance-question-edit-sheet.tsx b/lib/compliance/questions/compliance-question-edit-sheet.tsx new file mode 100644 index 00000000..064cafc1 --- /dev/null +++ b/lib/compliance/questions/compliance-question-edit-sheet.tsx @@ -0,0 +1,572 @@ +"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 { + 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 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); + + // 조건부 질문 관련 데이터 처리 + const updateData = { + ...data, + parentQuestionId: data.isConditional ? parentQuestionId : null, + conditionalValue: data.isConditional ? data.conditionalValue : undefined, + }; + + // isConditional과 parentQuestionId는 제거 (스키마에 없음) + delete (updateData as any).isConditional; + + 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> + )} + /> + + <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={field.onChange} 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> + )} + + <div className="grid grid-cols-3 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="hasDetailText" + 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="hasFileUpload" + 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="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> + )} + /> + + {/* 조건부 질문일 때만 부모 질문과 조건값 표시 */} + {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> + </Sheet> + ); +} diff --git a/lib/compliance/questions/compliance-questions-draggable-list.tsx b/lib/compliance/questions/compliance-questions-draggable-list.tsx new file mode 100644 index 00000000..6a226b54 --- /dev/null +++ b/lib/compliance/questions/compliance-questions-draggable-list.tsx @@ -0,0 +1,157 @@ +"use client"; + +import * as React from "react"; +import { Badge } from "@/components/ui/badge"; +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion"; +import { Sortable, SortableDragHandle, SortableItem } from "@/components/ui/sortable"; +import { GripVertical } from "lucide-react"; +import { complianceQuestions } from "@/db/schema/compliance"; +import { ComplianceQuestionEditSheet } from "./compliance-question-edit-sheet"; +import { ComplianceQuestionDeleteDialog } from "./compliance-question-delete-dialog"; +import { updateComplianceQuestion } from "@/lib/compliance/services"; +import { toast } from "sonner"; +import { useRouter } from "next/navigation"; + +interface SortableQuestionItemProps { + question: typeof complianceQuestions.$inferSelect; + onSuccess?: () => void; +} + +function SortableQuestionItem({ question, onSuccess }: SortableQuestionItemProps) { + return ( + <SortableItem value={question.id} className="mb-1"> + <AccordionItem value={`question-${question.id}`}> + <AccordionTrigger className="text-left py-1.5"> + <div className="flex items-center gap-2 w-full"> + <SortableDragHandle + variant="ghost" + size="sm" + className="p-0.5 h-auto hover:bg-muted/50 rounded" + > + <GripVertical className="h-3 w-3 text-muted-foreground" /> + </SortableDragHandle> + <Badge variant="outline">{question.questionNumber}</Badge> + <span className="font-medium flex-1 leading-tight">{question.questionText}</span> + <div className="flex items-center gap-2"> + <ComplianceQuestionEditSheet question={question} onSuccess={onSuccess} /> + <ComplianceQuestionDeleteDialog question={question} onSuccess={onSuccess} /> + </div> + </div> + </AccordionTrigger> + <AccordionContent> + <div className="space-y-4 pt-2 pl-8"> + <div className="grid grid-cols-2 gap-4 text-sm"> + <div> + <span className="font-medium">질문 타입:</span> + <Badge variant="secondary" className="ml-2">{question.questionType}</Badge> + </div> + <div> + <span className="font-medium">필수 여부:</span> + <Badge variant="secondary" className="ml-2"> + {question.isRequired ? '필수' : '선택'} + </Badge> + </div> + <div> + <span className="font-medium">상세 설명:</span> + <Badge variant="secondary" className="ml-2"> + {question.hasDetailText ? '필요' : '불필요'} + </Badge> + </div> + <div> + <span className="font-medium">파일 업로드:</span> + <Badge variant="secondary" className="ml-2"> + {question.hasFileUpload ? '필요' : '불필요'} + </Badge> + </div> + </div> + {question.conditionalValue && ( + <div className="text-sm text-muted-foreground"> + <span className="font-medium">조건:</span> {question.conditionalValue} + </div> + )} + </div> + </AccordionContent> + </AccordionItem> + </SortableItem> + ); +} + +interface ComplianceQuestionsDraggableListProps { + questions: typeof complianceQuestions.$inferSelect[]; + onSuccess?: () => void; +} + +export function ComplianceQuestionsDraggableList({ + questions, + onSuccess +}: ComplianceQuestionsDraggableListProps) { + const [items, setItems] = React.useState(questions); + const router = useRouter(); + + React.useEffect(() => { + setItems(questions); + }, [questions]); + + const handleValueChange = async (newItems: typeof complianceQuestions.$inferSelect[]) => { + setItems(newItems); + + // 새로운 순서로 displayOrder 업데이트 + const updatedItems = newItems.map((item, index) => ({ + ...item, + displayOrder: index + 1, + })); + + // 서버에 순서 업데이트 + await updateDisplayOrders(updatedItems); + }; + + const updateDisplayOrders = async (updatedItems: typeof complianceQuestions.$inferSelect[]) => { + try { + // 각 질문의 displayOrder를 순차적으로 업데이트 + await Promise.all( + updatedItems.map((item, index) => + updateComplianceQuestion(item.id, { + displayOrder: index + 1, + }) + ) + ); + + toast.success("질문 순서가 업데이트되었습니다."); + router.refresh(); + + if (onSuccess) { + onSuccess(); + } + } catch (error) { + console.error("Error updating question order:", error); + toast.error("질문 순서 업데이트 중 오류가 발생했습니다."); + } + }; + + if (items.length === 0) { + return ( + <div className="text-center py-8 text-muted-foreground"> + 아직 질문이 없습니다. 질문을 추가해보세요. + </div> + ); + } + + return ( + <Sortable value={items} onValueChange={handleValueChange}> + <Accordion type="single" collapsible className="w-full"> + {items.map((question) => ( + <SortableQuestionItem + key={question.id} + question={question} + onSuccess={onSuccess} + /> + ))} + </Accordion> + </Sortable> + ); +} |
