From fefca6304eefea94f41057f9f934b0e19ceb54bb Mon Sep 17 00:00:00 2001 From: 0-Zz-ang Date: Fri, 22 Aug 2025 13:47:37 +0900 Subject: (박서영)Compliance 설문/응답 리스트 생성 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../evcp/(evcp)/compliance/[templateId]/page.tsx | 66 ++ .../[templateId]/responses/[responseId]/page.tsx | 62 ++ .../compliance/[templateId]/responses/page.tsx | 119 +++ app/[lng]/evcp/(evcp)/compliance/page.tsx | 68 ++ app/api/compliance/files/download/route.ts | 90 +++ config/complianceColumnsConfig.ts | 69 ++ db/schema/index.ts | 5 +- lib/compliance/compliance-response-detail.tsx | 400 +++++++++ lib/compliance/compliance-template-detail.tsx | 83 ++ .../compliance-question-create-dialog.tsx | 562 +++++++++++++ .../compliance-question-delete-dialog.tsx | 107 +++ .../questions/compliance-question-edit-sheet.tsx | 572 +++++++++++++ .../compliance-questions-draggable-list.tsx | 157 ++++ .../responses/compliance-response-stats.tsx | 97 +++ .../responses/compliance-responses-columns.tsx | 189 +++++ .../responses/compliance-responses-list.tsx | 141 ++++ .../responses/compliance-responses-page-client.tsx | 62 ++ .../responses/compliance-responses-table.tsx | 141 ++++ .../responses/compliance-responses-toolbar.tsx | 69 ++ lib/compliance/services.ts | 899 +++++++++++++++++++++ .../table/compliance-survey-templates-columns.tsx | 176 ++++ .../table/compliance-survey-templates-table.tsx | 156 ++++ .../table/compliance-survey-templates-toolbar.tsx | 48 ++ .../table/compliance-template-create-dialog.tsx | 191 +++++ .../table/compliance-template-edit-sheet.tsx | 182 +++++ .../table/delete-compliance-templates-dialog.tsx | 209 +++++ 26 files changed, 4919 insertions(+), 1 deletion(-) create mode 100644 app/[lng]/evcp/(evcp)/compliance/[templateId]/page.tsx create mode 100644 app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/[responseId]/page.tsx create mode 100644 app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/page.tsx create mode 100644 app/[lng]/evcp/(evcp)/compliance/page.tsx create mode 100644 app/api/compliance/files/download/route.ts create mode 100644 config/complianceColumnsConfig.ts create mode 100644 lib/compliance/compliance-response-detail.tsx create mode 100644 lib/compliance/compliance-template-detail.tsx create mode 100644 lib/compliance/questions/compliance-question-create-dialog.tsx create mode 100644 lib/compliance/questions/compliance-question-delete-dialog.tsx create mode 100644 lib/compliance/questions/compliance-question-edit-sheet.tsx create mode 100644 lib/compliance/questions/compliance-questions-draggable-list.tsx create mode 100644 lib/compliance/responses/compliance-response-stats.tsx create mode 100644 lib/compliance/responses/compliance-responses-columns.tsx create mode 100644 lib/compliance/responses/compliance-responses-list.tsx create mode 100644 lib/compliance/responses/compliance-responses-page-client.tsx create mode 100644 lib/compliance/responses/compliance-responses-table.tsx create mode 100644 lib/compliance/responses/compliance-responses-toolbar.tsx create mode 100644 lib/compliance/services.ts create mode 100644 lib/compliance/table/compliance-survey-templates-columns.tsx create mode 100644 lib/compliance/table/compliance-survey-templates-table.tsx create mode 100644 lib/compliance/table/compliance-survey-templates-toolbar.tsx create mode 100644 lib/compliance/table/compliance-template-create-dialog.tsx create mode 100644 lib/compliance/table/compliance-template-edit-sheet.tsx create mode 100644 lib/compliance/table/delete-compliance-templates-dialog.tsx diff --git a/app/[lng]/evcp/(evcp)/compliance/[templateId]/page.tsx b/app/[lng]/evcp/(evcp)/compliance/[templateId]/page.tsx new file mode 100644 index 00000000..5dd74305 --- /dev/null +++ b/app/[lng]/evcp/(evcp)/compliance/[templateId]/page.tsx @@ -0,0 +1,66 @@ +import * as React from "react" +import { notFound } from "next/navigation" +import { Shell } from "@/components/shell" +import { InformationButton } from "@/components/information/information-button" +import { ComplianceTemplateDetail } from "@/lib/compliance/compliance-template-detail" +import { ComplianceResponseStats } from "@/lib/compliance/responses/compliance-response-stats" +import { + getComplianceSurveyTemplate, + getComplianceQuestions, + getComplianceResponses, + getComplianceResponseStats +} from "@/lib/compliance/services" + +interface TemplateDetailPageProps { + params: { + lng: string; + templateId: string; + }; +} + +export default async function TemplateDetailPage({ params }: TemplateDetailPageProps) { + const resolvedParams = await params; + const { templateId } = resolvedParams; + + const templateIdAsNumber = Number(templateId); + + // 서버에서 데이터 미리 가져오기 + const [template, questions, responses, stats] = await Promise.all([ + getComplianceSurveyTemplate(templateIdAsNumber), + getComplianceQuestions(templateIdAsNumber), + getComplianceResponses(templateIdAsNumber), + getComplianceResponseStats(templateIdAsNumber) + ]); + + if (!template) { + notFound(); + } + + return ( + +
+
+
+
+

+ 템플릿 상세 +

+ +
+

+ 설문조사 템플릿의 질문들과 옵션을 확인할 수 있습니다. +

+
+
+
+ + +
+ ) +} diff --git a/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/[responseId]/page.tsx b/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/[responseId]/page.tsx new file mode 100644 index 00000000..73d9bbac --- /dev/null +++ b/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/[responseId]/page.tsx @@ -0,0 +1,62 @@ +import * as React from "react" +import { Shell } from "@/components/shell" +import { InformationButton } from "@/components/information/information-button" +import { ComplianceResponseDetail } from "@/lib/compliance/compliance-response-detail" +import { + getComplianceResponse, + getComplianceResponseAnswers, + getComplianceResponseFiles, + getComplianceSurveyTemplate, + getComplianceQuestions +} from "@/lib/compliance/services" + +interface ResponseDetailPageProps { + params: { + lng: string; + templateId: string; + responseId: string; + }; +} + +export default async function ResponseDetailPage({ params }: ResponseDetailPageProps) { + const resolvedParams = await params; + const { templateId, responseId } = resolvedParams; + + const templateIdAsNumber = Number(templateId); + const responseIdAsNumber = Number(responseId); + + // 서버에서 데이터 미리 가져오기 + const promises = Promise.all([ + getComplianceResponse(responseIdAsNumber), + getComplianceResponseAnswers(responseIdAsNumber), + getComplianceResponseFiles(responseIdAsNumber), + getComplianceSurveyTemplate(templateIdAsNumber), + getComplianceQuestions(templateIdAsNumber) + ]); + + return ( + +
+
+
+
+

+ 설문조사 응답 상세 +

+ +
+

+ 설문조사 응답의 모든 답변과 첨부파일을 확인할 수 있습니다. +

+
+
+
+ + +
+ ) +} diff --git a/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/page.tsx b/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/page.tsx new file mode 100644 index 00000000..80e15768 --- /dev/null +++ b/app/[lng]/evcp/(evcp)/compliance/[templateId]/responses/page.tsx @@ -0,0 +1,119 @@ +import { Suspense } from "react"; +import { notFound } from "next/navigation"; +import { type SearchParams } from "@/types/table"; +import { getComplianceSurveyTemplate, getComplianceResponsesWithPagination, getComplianceResponseStats } from "@/lib/compliance/services"; +import { ComplianceResponsesPageClient } from "@/lib/compliance/responses/compliance-responses-page-client"; +import { Shell } from "@/components/shell"; +import { Skeleton } from "@/components/ui/skeleton"; +import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton"; +import { InformationButton } from "@/components/information/information-button"; + +interface ComplianceResponsesPageProps { + params: Promise<{ + templateId: string; + }>; + searchParams: Promise; +} + +export default async function ComplianceResponsesPage({ params, searchParams }: ComplianceResponsesPageProps) { + const resolvedParams = await params; + const resolvedSearchParams = await searchParams; + const templateId = parseInt(resolvedParams.templateId); + + if (isNaN(templateId)) { + notFound(); + } + + // pageSize 기반으로 모드 자동 결정 (items 페이지와 동일한 로직) + const search = { page: 1, perPage: 10, ...resolvedSearchParams }; + const isInfiniteMode = search.perPage >= 1_000_000; + + // 페이지네이션 모드일 때만 서버에서 데이터 가져오기 + // 무한 스크롤 모드에서는 클라이언트에서 SWR로 데이터 로드 + const promises = isInfiniteMode + ? undefined + : Promise.all([ + getComplianceSurveyTemplate(templateId), + getComplianceResponsesWithPagination(templateId), + getComplianceResponseStats(templateId), + ]); + + if (!promises) { + // 무한 스크롤 모드 + return ( + +
+
+
+
+

+ 응답 현황 +

+ +
+

+ 준법 설문조사 응답 현황을 확인할 수 있습니다. +

+
+
+
+ + 응답 목록을 불러오는 중...}> + + +
+ ); + } + + const [template, responses, stats] = await promises; + + if (!template) { + notFound(); + } + + return ( + +
+
+
+
+

+ 응답 현황 +

+ +
+

+ 템플릿: {template.name} - 준법 설문조사 응답 현황을 확인할 수 있습니다. +

+
+
+
+ + }> + {/* 추가 기능들 */} + + + + } + > + + +
+ ); +} diff --git a/app/[lng]/evcp/(evcp)/compliance/page.tsx b/app/[lng]/evcp/(evcp)/compliance/page.tsx new file mode 100644 index 00000000..3b97ce99 --- /dev/null +++ b/app/[lng]/evcp/(evcp)/compliance/page.tsx @@ -0,0 +1,68 @@ +import * as React from "react" +import { type SearchParams } from "@/types/table" + +import { Skeleton } from "@/components/ui/skeleton" +import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton" +import { Shell } from "@/components/shell" +import { getComplianceSurveyTemplatesWithPagination } from "@/lib/compliance/services" +import { ComplianceSurveyTemplatesTable } from "@/lib/compliance/table/compliance-survey-templates-table" +import { InformationButton } from "@/components/information/information-button" + +interface IndexPageProps { + searchParams: Promise +} + +export default async function IndexPage(props: IndexPageProps) { + const searchParams = await props.searchParams + + // pageSize 기반으로 모드 자동 결정 (items 페이지와 동일한 로직) + const search = { page: 1, perPage: 10, ...searchParams } + const isInfiniteMode = search.perPage >= 1_000_000 + + // 페이지네이션 모드일 때만 서버에서 데이터 가져오기 + // 무한 스크롤 모드에서는 클라이언트에서 SWR로 데이터 로드 + const promises = isInfiniteMode + ? undefined + : Promise.all([ + getComplianceSurveyTemplatesWithPagination(), + ]) + + return ( + +
+
+
+
+

+ 준법 설문조사 관리 +

+ +
+

+ 준법 설문조사 템플릿을 관리하고 응답 현황을 확인할 수 있습니다. +

+
+
+ +
+ + }> + {/* DateRangePicker 등 추가 컴포넌트 */} + + + + } + > + + +
+ ) +} diff --git a/app/api/compliance/files/download/route.ts b/app/api/compliance/files/download/route.ts new file mode 100644 index 00000000..7bcb59cd --- /dev/null +++ b/app/api/compliance/files/download/route.ts @@ -0,0 +1,90 @@ +import { NextRequest, NextResponse } from "next/server"; +import { getServerSession } from "next-auth"; +import { authOptions } from "@/lib/auth"; +import db from "@/db/db"; +import { complianceResponseFiles } from "@/db/schema/compliance"; +import { eq } from "drizzle-orm"; +import fs from "fs/promises"; +import path from "path"; + +// MIME 타입 매핑 (기존 API와 동일) +const getMimeType = (filePath: string): string => { + const ext = path.extname(filePath).toLowerCase(); + const mimeTypes: Record = { + '.pdf': 'application/pdf', + '.doc': 'application/msword', + '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + '.xls': 'application/vnd.ms-excel', + '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.png': 'image/png', + '.gif': 'image/gif', + '.txt': 'text/plain', + '.zip': 'application/zip', + }; + + return mimeTypes[ext] || 'application/octet-stream'; +}; + +export async function GET(request: NextRequest) { + try { + // 인증 확인 + const session = await getServerSession(authOptions); + if (!session?.user) { + return NextResponse.json({ error: "인증이 필요합니다." }, { status: 401 }); + } + + // 쿼리 파라미터에서 fileId 추출 + const { searchParams } = new URL(request.url); + const fileId = searchParams.get("fileId"); + + if (!fileId) { + return NextResponse.json({ error: "파일 ID가 필요합니다." }, { status: 400 }); + } + + // 파일 정보 조회 + const [file] = await db + .select() + .from(complianceResponseFiles) + .where(eq(complianceResponseFiles.id, parseInt(fileId))); + + if (!file) { + return NextResponse.json({ error: "파일을 찾을 수 없습니다." }, { status: 404 }); + } + + // 파일 경로 구성 (public 폴더 기준) + const filePath = path.join(process.cwd(), "public", file.filePath); + + // 파일 존재 확인 + try { + await fs.access(filePath); + } catch { + return NextResponse.json({ error: "파일이 서버에 존재하지 않습니다." }, { status: 404 }); + } + + // 파일 읽기 + const fileBuffer = await fs.readFile(filePath); + + // 파일 타입 결정 + const mimeType = file.mimeType || getMimeType(file.filePath); + + // 응답 헤더 설정 + const headers = new Headers(); + headers.set("Content-Type", mimeType); + headers.set("Content-Disposition", `attachment; filename="${encodeURIComponent(file.fileName)}"`); + headers.set("Content-Length", file.fileSize?.toString() || fileBuffer.length.toString()); + + return new NextResponse(fileBuffer, { + status: 200, + headers, + }); + + } catch (error) { + console.error("파일 다운로드 오류:", error); + return NextResponse.json( + { error: "파일 다운로드 중 오류가 발생했습니다." }, + { status: 500 } + ); + } +} diff --git a/config/complianceColumnsConfig.ts b/config/complianceColumnsConfig.ts new file mode 100644 index 00000000..52085757 --- /dev/null +++ b/config/complianceColumnsConfig.ts @@ -0,0 +1,69 @@ +import { ComplianceSurveyTemplate } from "@/db/schema/compliance" + +export interface ComplianceColumnConfig { + id: keyof ComplianceSurveyTemplate + label: string + group?: string + excelHeader?: string + type?: string + sortable?: boolean + filterable?: boolean + width?: number +} + +export const complianceColumnsConfig: ComplianceColumnConfig[] = [ + { + id: "name", + label: "템플릿명", + excelHeader: "템플릿명", + type: "text", + sortable: true, + filterable: true, + width: 200, + }, + { + id: "description", + label: "설명", + excelHeader: "설명", + type: "text", + sortable: true, + filterable: true, + width: 300, + }, + { + id: "version", + label: "버전", + excelHeader: "버전", + type: "text", + sortable: true, + filterable: true, + width: 100, + }, + { + id: "isActive", + label: "상태", + excelHeader: "상태", + type: "boolean", + sortable: true, + filterable: true, + width: 100, + }, + { + id: "createdAt", + label: "생성일", + excelHeader: "생성일", + type: "date", + sortable: true, + filterable: true, + width: 120, + }, + { + id: "updatedAt", + label: "수정일", + excelHeader: "수정일", + type: "date", + sortable: true, + filterable: true, + width: 120, + }, +] diff --git a/db/schema/index.ts b/db/schema/index.ts index 7637d247..b800d615 100644 --- a/db/schema/index.ts +++ b/db/schema/index.ts @@ -60,4 +60,7 @@ export * from './knox/titles'; // 직급 export * from './knox/approvals'; // Knox 결재 - eVCP 에서 상신한 결재를 저장 // === Risks 스키마 === -export * from './risks/risks'; \ No newline at end of file +export * from './risks/risks'; + +// === Compliance 스키마 === +export * from './compliance'; \ No newline at end of file diff --git a/lib/compliance/compliance-response-detail.tsx b/lib/compliance/compliance-response-detail.tsx new file mode 100644 index 00000000..af12469c --- /dev/null +++ b/lib/compliance/compliance-response-detail.tsx @@ -0,0 +1,400 @@ +"use client" + +import * as React from "react" +import { format } from "date-fns" +import { ko } from "date-fns/locale" + +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" +import { Badge } from "@/components/ui/badge" +import { Separator } from "@/components/ui/separator" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow +} from "@/components/ui/table" +import { + Accordion, + AccordionContent, + AccordionItem, + AccordionTrigger, +} from "@/components/ui/accordion" +import { + FileText, + Users, + CheckCircle, + Clock, + AlertCircle, + Download, + File +} from "lucide-react" + +import { + getComplianceResponse, + getComplianceResponseAnswers, + getComplianceResponseFilesByResponseId, + getComplianceSurveyTemplate, + getComplianceQuestions, + getComplianceQuestionOptions +} from "./services" + +interface ComplianceResponseDetailProps { + templateId: number + responseId: number +} + +export function ComplianceResponseDetail({ templateId, responseId }: ComplianceResponseDetailProps) { + const [response, setResponse] = React.useState(null) + const [answers, setAnswers] = React.useState([]) + const [files, setFiles] = React.useState([]) + const [template, setTemplate] = React.useState(null) + const [questions, setQuestions] = React.useState([]) + const [loading, setLoading] = React.useState(true) + + React.useEffect(() => { + const fetchResponseData = async () => { + try { + const [responseData, answersData, filesData, templateData, questionsData] = await Promise.all([ + getComplianceResponse(responseId), + getComplianceResponseAnswers(responseId), + getComplianceResponseFilesByResponseId(responseId), + getComplianceSurveyTemplate(templateId), + getComplianceQuestions(templateId) + ]) + + setResponse(responseData) + setAnswers(answersData) + setFiles(filesData) + setTemplate(templateData) + setQuestions(questionsData) + } catch (error) { + console.error("Error fetching response data:", error) + } finally { + setLoading(false) + } + } + + fetchResponseData() + }, [templateId, responseId]) + + const getStatusIcon = (status: string) => { + switch (status) { + case 'COMPLETED': + return + case 'IN_PROGRESS': + return + case 'REVIEWED': + return + default: + return + } + } + + const getStatusText = (status: string) => { + switch (status) { + case 'COMPLETED': + return '완료' + case 'IN_PROGRESS': + return '진행중' + case 'REVIEWED': + return '검토완료' + default: + return '알 수 없음' + } + } + + const getQuestionText = (questionId: number) => { + const question = questions.find(q => q.id === questionId) + return question ? question.questionText : '질문을 찾을 수 없습니다' + } + + const getQuestionNumber = (questionId: number) => { + const question = questions.find(q => q.id === questionId) + return question ? question.questionNumber : '-' + } + + const getQuestionType = (questionId: number) => { + const question = questions.find(q => q.id === questionId) + return question ? question.questionType : '-' + } + + // 파일 다운로드 핸들러 + const handleFileDownload = async (file: any) => { + try { + // 파일 다운로드 API 호출 + const response = await fetch(`/api/compliance/files/download?fileId=${file.id}`); + + if (!response.ok) { + throw new Error('파일 다운로드에 실패했습니다'); + } + + // Blob으로 파일 데이터 받기 + const blob = await response.blob(); + + // 임시 URL 생성하여 다운로드 + const url = window.URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = file.fileName; + document.body.appendChild(link); + link.click(); + + // 정리 + document.body.removeChild(link); + window.URL.revokeObjectURL(url); + + console.log("✅ 파일 다운로드 성공:", file.fileName); + } catch (error) { + console.error("❌ 파일 다운로드 실패:", error); + alert(`파일 다운로드에 실패했습니다: ${error instanceof Error ? error.message : '알 수 없는 오류'}`); + } + } + + if (loading) { + return ( +
+
+
+
+ ) + } + + if (!response) { + return ( +
+ 응답을 찾을 수 없습니다. +
+ ) + } + + return ( +
+ {/* 응답 정보 */} + + + + + 설문조사 응답 정보 + + + +
+
+ +

{template?.name || '-'}

+
+
+ +

+ {response.vendorName ? ( + {response.vendorName} + ) : ( + 기본계약 ID: {response.basicContractId} + )} +

+ {response.vendorCode && ( +

Vendor Code: {response.vendorCode}

+ )} +
+
+ +
+ {getStatusIcon(response.status)} + + {getStatusText(response.status)} + +
+
+
+ +

+ {response.completedAt ? + format(new Date(response.completedAt), 'yyyy-MM-dd HH:mm', { locale: ko }) : + '-' + } +

+
+
+ +

+ {response.createdAt ? + format(new Date(response.createdAt), 'yyyy-MM-dd HH:mm', { locale: ko }) : + '-' + } +

+
+
+ +

+ {response.updatedAt ? + format(new Date(response.updatedAt), 'yyyy-MM-dd HH:mm', { locale: ko }) : + '-' + } +

+
+
+
+
+ + {/* 답변 목록 */} + + + + + 답변 목록 ({answers.length}개) + + + + {answers.length === 0 ? ( +
+ 아직 답변이 없습니다. +
+ ) : ( + + {answers.map((answer, index) => ( + + +
+ + {getQuestionNumber(answer.questionId)} + + + {getQuestionText(answer.questionId)} + + + {getQuestionType(answer.questionId)} + +
+
+ +
+ {/* 답변 값 */} + {answer.answerValue && ( +
+ +

{answer.answerValue}

+
+ )} + + {/* 상세 설명 */} + {answer.detailText && ( +
+ +

{answer.detailText}

+
+ )} + + {/* 기타 텍스트 */} + {answer.otherText && ( +
+ +

{answer.otherText}

+
+ )} + + {/* 퍼센트 값 */} + {answer.percentageValue && ( +
+ +

{answer.percentageValue}%

+
+ )} + + {/* 첨부파일 */} +
+ +
+ {files.filter(file => file.answerId === answer.id).length > 0 ? ( +
+ {files + .filter(file => file.answerId === answer.id) + .map((file) => ( +
+
+ + {file.fileName} + + ({file.fileSize ? `${(file.fileSize / 1024).toFixed(1)} KB` : '크기 정보 없음'}) + +
+ +
+ ))} +
+ ) : ( +

첨부된 파일이 없습니다

+ )} +
+
+ + {/* 답변 생성일 */} +
+ 답변일: {answer.createdAt ? + format(new Date(answer.createdAt), 'yyyy-MM-dd HH:mm', { locale: ko }) : + '-' + } +
+
+
+
+ ))} +
+ )} +
+
+ + {/* 검토 정보 */} + {response.reviewedBy && ( + + + + + 검토 정보 + + + +
+
+ +

+ {response.reviewerName ? ( + {response.reviewerName} + ) : ( + 사용자 ID: {response.reviewedBy} + )} +

+ {response.reviewerEmail && ( +

{response.reviewerEmail}

+ )} +
+
+ +

+ {response.reviewedAt ? + format(new Date(response.reviewedAt), 'yyyy-MM-dd HH:mm', { locale: ko }) : + '-' + } +

+
+
+ {response.reviewNotes && ( +
+ +

{response.reviewNotes}

+
+ )} +
+
+ )} +
+ ) +} diff --git a/lib/compliance/compliance-template-detail.tsx b/lib/compliance/compliance-template-detail.tsx new file mode 100644 index 00000000..f4531697 --- /dev/null +++ b/lib/compliance/compliance-template-detail.tsx @@ -0,0 +1,83 @@ +"use client" + +import * as React from "react" +import { useRouter } from "next/navigation" + +import { Button } from "@/components/ui/button" +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" +import { FileText, Users } from "lucide-react" + +import { ComplianceResponseStats } from "@/lib/compliance/responses/compliance-response-stats" +import { ComplianceQuestionCreateDialog } from "@/lib/compliance/questions/compliance-question-create-dialog" +import { ComplianceQuestionsDraggableList } from "@/lib/compliance/questions/compliance-questions-draggable-list" + +interface ComplianceTemplateDetailProps { + templateId: number + template: Awaited> + questions: Awaited> + responses: Awaited> + stats: Awaited> +} + +export function ComplianceTemplateDetail({ templateId, template, questions, responses, stats }: ComplianceTemplateDetailProps) { + const router = useRouter() + + + + if (!template) { + return ( +
+ 템플릿을 찾을 수 없습니다. +
+ ) + } + + return ( +
+ {/* 응답 현황 링크 */} + + + + + 응답 현황 ({responses.length}개) + + + +
+ {/* 통계 카드들 */} + + +
+

+ 이 템플릿에 대한 응답들을 확인하려면 응답 현황 페이지로 이동하세요. +

+ +
+
+
+
+ + {/* 질문 목록 */} + + +
+ + + 설문 질문 목록 ({questions.length}개) + + +
+
+ + + +
+
+ ) +} 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; + +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({ + resolver: zodResolver(questionSchema), + defaultValues: { + questionNumber: "", + questionText: "", + questionType: "", + isRequired: false, + hasDetailText: false, + hasFileUpload: false, + conditionalValue: "", + }, + }); + + // 부모 질문 및 옵션 상태 + const [parentQuestionId, setParentQuestionId] = React.useState(""); + const [selectableParents, setSelectableParents] = React.useState>([]); + const [parentOptions, setParentOptions] = React.useState>([]); + + // 옵션 관리 상태 + const [options, setOptions] = React.useState>([]); + 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 ( + + + + + + + 새 질문 추가 + + 템플릿에 새로운 질문을 추가합니다. + + + +
+ + ( + + 질문 번호 + + + + + + )} + /> + + ( + + 질문 내용 + +