From 2acf5f8966a40c1c9a97680c8dc263ee3f1ad3d1 Mon Sep 17 00:00:00 2001 From: dujinkim Date: Wed, 2 Jul 2025 00:45:49 +0000 Subject: (대표님/최겸) 20250702 변경사항 업데이트 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/b-rfq/service.ts | 6 + lib/b-rfq/summary-table/summary-rfq-columns.tsx | 4 +- lib/dashboard/dashboard-client.tsx | 115 +++ lib/dashboard/dashboard-overview-chart.tsx | 325 ++++++++ lib/dashboard/dashboard-stats-card.tsx | 88 ++ lib/dashboard/dashboard-summary-cards.tsx | 64 ++ lib/dashboard/partners-service.ts | 447 ++++++++++ lib/dashboard/service.ts | 454 ++++++++++ lib/qna/service.ts | 1006 +++++++++++++++++++++++ lib/qna/table/create-qna-dialog.tsx | 203 +++++ lib/qna/table/delete-qna-dialog.tsx | 250 ++++++ lib/qna/table/improved-comment-section.tsx | 319 +++++++ lib/qna/table/qna-detail.tsx | 455 ++++++++++ lib/qna/table/qna-export-actions.tsx | 261 ++++++ lib/qna/table/qna-table-columns.tsx | 325 ++++++++ lib/qna/table/qna-table-toolbar-actions.tsx | 176 ++++ lib/qna/table/qna-table.tsx | 236 ++++++ lib/qna/table/update-qna-sheet.tsx | 206 +++++ lib/qna/table/utils.tsx | 329 ++++++++ lib/qna/validation.ts | 374 +++++++++ lib/users/access-control/users-table.tsx | 2 +- 21 files changed, 5642 insertions(+), 3 deletions(-) create mode 100644 lib/dashboard/dashboard-client.tsx create mode 100644 lib/dashboard/dashboard-overview-chart.tsx create mode 100644 lib/dashboard/dashboard-stats-card.tsx create mode 100644 lib/dashboard/dashboard-summary-cards.tsx create mode 100644 lib/dashboard/partners-service.ts create mode 100644 lib/dashboard/service.ts create mode 100644 lib/qna/service.ts create mode 100644 lib/qna/table/create-qna-dialog.tsx create mode 100644 lib/qna/table/delete-qna-dialog.tsx create mode 100644 lib/qna/table/improved-comment-section.tsx create mode 100644 lib/qna/table/qna-detail.tsx create mode 100644 lib/qna/table/qna-export-actions.tsx create mode 100644 lib/qna/table/qna-table-columns.tsx create mode 100644 lib/qna/table/qna-table-toolbar-actions.tsx create mode 100644 lib/qna/table/qna-table.tsx create mode 100644 lib/qna/table/update-qna-sheet.tsx create mode 100644 lib/qna/table/utils.tsx create mode 100644 lib/qna/validation.ts (limited to 'lib') diff --git a/lib/b-rfq/service.ts b/lib/b-rfq/service.ts index 8aa79084..5a65872b 100644 --- a/lib/b-rfq/service.ts +++ b/lib/b-rfq/service.ts @@ -2528,6 +2528,11 @@ export async function requestRevision( ): Promise { try { // 입력값 검증 + + const session = await getServerSession(authOptions) + if (!session?.user?.id) { + throw new Error("인증이 필요합니다.") + } const validatedData = requestRevisionSchema.parse({ responseId, revisionReason, @@ -2567,6 +2572,7 @@ export async function requestRevision( revisionRequestComment: validatedData.revisionReason, // 새로운 필드에 저장 revisionRequestedAt: new Date(), // 수정 요청 시간 저장 updatedAt: new Date(), + updatedBy: Number(session.user.id), }) .where(eq(vendorAttachmentResponses.id, validatedData.responseId)) .returning(); diff --git a/lib/b-rfq/summary-table/summary-rfq-columns.tsx b/lib/b-rfq/summary-table/summary-rfq-columns.tsx index 40f143b2..af5c22b2 100644 --- a/lib/b-rfq/summary-table/summary-rfq-columns.tsx +++ b/lib/b-rfq/summary-table/summary-rfq-columns.tsx @@ -411,11 +411,11 @@ export function getRFQColumns({ setRowAction, router }: GetRFQColumnsProps): Col
초기: - {initial}개사 ({initialRate}%) + {initial}개사 ({Number(initialRate).toFixed(0)}%)
최종: - {final}개사 ({finalRate}%) + {final}개사 ({Number(finalRate).toFixed(0)}%)
); diff --git a/lib/dashboard/dashboard-client.tsx b/lib/dashboard/dashboard-client.tsx new file mode 100644 index 00000000..37dc1901 --- /dev/null +++ b/lib/dashboard/dashboard-client.tsx @@ -0,0 +1,115 @@ +"use client"; + +import { useState } from "react"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Button } from "@/components/ui/button"; +import { RefreshCw } from "lucide-react"; +import { DashboardStatsCard } from "./dashboard-stats-card"; +import { DashboardOverviewChart } from "./dashboard-overview-chart"; +import { DashboardSummaryCards } from "./dashboard-summary-cards"; +import { toast } from "sonner"; +import { DashboardData } from "./service"; + +interface DashboardClientProps { + initialData: DashboardData; + onRefresh: () => Promise; +} + +export function DashboardClient({ initialData, onRefresh }: DashboardClientProps) { + const [data, setData] = useState(initialData); + const [isRefreshing, setIsRefreshing] = useState(false); + + + const handleRefresh = async () => { + try { + setIsRefreshing(true); + const newData = await onRefresh(); + setData(newData); + toast.success("대시보드 데이터가 새로고침되었습니다."); + } catch (error) { + toast.error("데이터 새로고침에 실패했습니다."); + console.error("Dashboard refresh error:", error); + } finally { + setIsRefreshing(false); + } + }; + + const getDomainDisplayName = (domain: string) => { + const domainNames: Record = { + 'procurement': '구매 관리', + 'sales': '영업 관리', + "partners": 'Partners', + 'engineering': '엔지니어링' + }; + return domainNames[domain] || domain; + }; + + return ( +
+ {/* 헤더 */} +
+
+

+ {getDomainDisplayName(data.domain)} Dashboard +

+

+ {data.domain ==="partners"? "회사와 개인에게 할당된 일들을 보여줍니다.":"팀과 개인에게 할당된 일들을 보여줍니다."} +

+
+ +
+ + {/* 요약 카드 */} + + + {/* 차트 */} + + + {/* 탭 */} + + + {data.domain ==="partners"? "회사 업무 현황":"팀 업무 현황"} + 내 업무 현황 + + + +
+ {data.teamStats.map((stats) => ( + + ))} +
+
+ + +
+ {data.userStats.map((stats) => ( + + ))} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/lib/dashboard/dashboard-overview-chart.tsx b/lib/dashboard/dashboard-overview-chart.tsx new file mode 100644 index 00000000..ca5c0006 --- /dev/null +++ b/lib/dashboard/dashboard-overview-chart.tsx @@ -0,0 +1,325 @@ +"use client"; + +import { TrendingUp, BarChart3, PieChart } from "lucide-react"; +import { Bar, BarChart, CartesianGrid, XAxis, YAxis, Pie, PieChart as RechartsPieChart, Cell, ResponsiveContainer, LabelList } from "recharts"; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from "@/components/ui/card"; +import { + ChartConfig, + ChartContainer, + ChartTooltip, + ChartTooltipContent, +} from "@/components/ui/chart"; +import { DashboardStats } from "@/lib/dashboard/service"; + +interface DashboardOverviewChartProps { + data: DashboardStats[]; + title: string; + description?: string; +} + +// 차트 설정 +const chartConfig = { + pending: { + label: "대기", + color: "hsl(var(--chart-1))", // 회색 계열 + }, + inProgress: { + label: "진행중", + color: "hsl(var(--chart-2))", // 파란색 계열 + }, + completed: { + label: "완료", + color: "hsl(var(--chart-3))", // 초록색 계열 + }, +} satisfies ChartConfig; + +// 파이 차트용 색상 +const PIE_COLORS = { + pending: "#6b7280", + inProgress: "#3b82f6", + completed: "#10b981" +}; + +export function DashboardOverviewChart({ data, title, description }: DashboardOverviewChartProps) { + // 바 차트용 데이터 변환 + const barChartData = data.map(item => ({ + name: item.displayName.length > 10 ? + item.displayName.substring(0, 10) + "..." : + item.displayName, + fullName: item.displayName, + pending: item.pending, + inProgress: item.inProgress, + completed: item.completed, + total: item.total + })); + + // 파이 차트용 데이터 (전체 요약) + const totalPending = data.reduce((sum, item) => sum + item.pending, 0); + const totalInProgress = data.reduce((sum, item) => sum + item.inProgress, 0); + const totalCompleted = data.reduce((sum, item) => sum + item.completed, 0); + const totalTasks = totalPending + totalInProgress + totalCompleted; + + const pieChartData = [ + { name: "대기", value: totalPending, color: PIE_COLORS.pending }, + { name: "진행중", value: totalInProgress, color: PIE_COLORS.inProgress }, + { name: "완료", value: totalCompleted, color: PIE_COLORS.completed } + ].filter(item => item.value > 0); + + // 완료율 계산 + const completionRate = totalTasks > 0 ? Math.round((totalCompleted / totalTasks) * 100) : 0; + const isImproving = completionRate > 50; // 50% 이상이면 개선으로 간주 + + return ( +
+ {/* 바 차트 - 2/3 너비 */} + + + + + {title} - 업무별 현황 + + {description && {description}} + + + + + + + + { + const item = barChartData.find(d => d.name === label); + return item?.fullName || label; + }} + />} + /> + + + + value > 0 ? value : ''} + /> + + + + + +
+ {totalTasks > 0 && ( + <> + + 완료율 {completionRate}% - {isImproving ? '순조롭게 진행중' : '진행 필요'} + + )} +
+
+ 총 {totalTasks}건의 업무 현황 +
+
+
+ + {/* 파이 차트 - 1/3 너비 */} + + + + + 업무 분포 + + 상태별 비율 + + + + + [ + `${value}건 (${Math.round((Number(value) / totalTasks) * 100)}%)`, + name + ]} + />} + /> + + percent > 0.1 ? `${(percent * 100).toFixed(0)}%` : '' + } + outerRadius={70} // 작은 공간에 맞게 더 작게 조정 + fill="#8884d8" + dataKey="value" + > + {pieChartData.map((entry, index) => ( + + ))} + + + + + +
+
+
+ 대기 + {totalPending} +
+
+ 진행 + {totalInProgress} +
+
+ 완료 + {totalCompleted} +
+
+
+
+
+
+ ); +} + +// 더 컴팩트한 버전 (높이를 더 많이 줄이고 싶은 경우) +export function CompactDashboardChart({ data, title, description }: DashboardOverviewChartProps) { + const totalPending = data.reduce((sum, item) => sum + item.pending, 0); + const totalInProgress = data.reduce((sum, item) => sum + item.inProgress, 0); + const totalCompleted = data.reduce((sum, item) => sum + item.completed, 0); + const totalTasks = totalPending + totalInProgress + totalCompleted; + + const pieChartData = [ + { name: "대기", value: totalPending, color: PIE_COLORS.pending }, + { name: "진행중", value: totalInProgress, color: PIE_COLORS.inProgress }, + { name: "완료", value: totalCompleted, color: PIE_COLORS.completed } + ].filter(item => item.value > 0); + + const completionRate = totalTasks > 0 ? Math.round((totalCompleted / totalTasks) * 100) : 0; + + return ( +
+ {/* 요약 통계 */} + +
+

완료율

+
{completionRate}%
+

총 {totalTasks}건

+
+ 50 ? 'text-green-600' : 'text-orange-600'}`} /> +
+ + {/* 컴팩트 파이 차트 */} + + + {title} + + +
+ {/* 작은 파이 차트 */} +
+ + + [`${value}건`, name]} + />} + /> + + {pieChartData.map((entry, index) => ( + + ))} + + + +
+ + {/* 통계 목록 */} +
+
+
+ 대기: {totalPending}건 +
+
+
+ 진행중: {totalInProgress}건 +
+
+
+ 완료: {totalCompleted}건 +
+
+
+
+
+
+ ); +} + diff --git a/lib/dashboard/dashboard-stats-card.tsx b/lib/dashboard/dashboard-stats-card.tsx new file mode 100644 index 00000000..4485e8e0 --- /dev/null +++ b/lib/dashboard/dashboard-stats-card.tsx @@ -0,0 +1,88 @@ +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Progress } from "@/components/ui/progress"; +import { DashboardStats, UserDashboardStats } from "./service"; + +interface DashboardStatsCardProps { + stats: DashboardStats | UserDashboardStats; + showUserStats?: boolean; +} + +export function DashboardStatsCard({ stats, showUserStats = false }: DashboardStatsCardProps) { + const userStats = showUserStats ? stats as UserDashboardStats : null; + + const completionRate = stats.total > 0 ? Math.round((stats.completed / stats.total) * 100) : 0; + const myCompletionRate = userStats && userStats.myTotal > 0 + ? Math.round((userStats.myCompleted / userStats.myTotal) * 100) + : 0; + + return ( + + + {stats.displayName} + + + {/* 팀 전체 통계 */} +
+
+ 팀 전체 + {stats.total}건 +
+ +
+ + 대기 {stats.pending} + + + 진행 {stats.inProgress} + + + 완료 {stats.completed} + +
+ +
+
+ 완료율 + {completionRate}% +
+ +
+
+ + {/* 개인 통계 */} + {showUserStats && userStats && ( + <> +
+
+
+ 내 업무 + {userStats.myTotal}건 +
+ +
+ + 대기 {userStats.myPending} + + + 진행 {userStats.myInProgress} + + + 완료 {userStats.myCompleted} + +
+ +
+
+ 완료율 + {myCompletionRate}% +
+ +
+
+ + )} +
+
+ ); +} \ No newline at end of file diff --git a/lib/dashboard/dashboard-summary-cards.tsx b/lib/dashboard/dashboard-summary-cards.tsx new file mode 100644 index 00000000..9d1d9ef2 --- /dev/null +++ b/lib/dashboard/dashboard-summary-cards.tsx @@ -0,0 +1,64 @@ +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { CheckCircle, Clock, PlayCircle, Users } from "lucide-react"; +import { DashboardData } from "./service"; + +interface DashboardSummaryCardsProps { + summary: DashboardData['summary']; +} + +export function DashboardSummaryCards({ summary }: DashboardSummaryCardsProps) { + const cards = [ + { + title: "전체 업무", + value: summary.totalTasks, + icon: Users, + description: `내 업무 ${summary.myTasks}건`, + color: "text-blue-600" + }, + { + title: "대기중", + value: summary.teamPending, + icon: Clock, + description: `내 대기 ${summary.myPending}건`, + color: "text-gray-600" + }, + { + title: "진행중", + value: summary.teamInProgress, + icon: PlayCircle, + description: `내 진행 ${summary.myInProgress}건`, + color: "text-blue-600" + }, + { + title: "완료", + value: summary.teamCompleted, + icon: CheckCircle, + description: `내 완료 ${summary.myCompleted}건`, + color: "text-green-600" + } + ]; + + return ( +
+ {cards.map((card, index) => { + const Icon = card.icon; + return ( + + + + {card.title} + + + + +
{card.value}
+

+ {card.description} +

+
+
+ ); + })} +
+ ); +} \ No newline at end of file diff --git a/lib/dashboard/partners-service.ts b/lib/dashboard/partners-service.ts new file mode 100644 index 00000000..327a16a9 --- /dev/null +++ b/lib/dashboard/partners-service.ts @@ -0,0 +1,447 @@ +"use server"; + +import db from "@/db/db"; +import { sql } from "drizzle-orm"; +import { getServerSession } from "next-auth/next"; +import { authOptions } from "@/app/api/auth/[...nextauth]/route"; +import { getPartnerTablesByDomain } from "@/config/partners-dashboard-table"; +import { TableConfig } from "@/types/dashboard"; + +export interface PartnersDashboardStats { + tableName: string; + displayName: string; + total: number; + pending: number; + inProgress: number; + completed: number; +} + +export interface PartnersUserDashboardStats extends PartnersDashboardStats { + myTotal: number; + myPending: number; + myInProgress: number; + myCompleted: number; +} + +export interface PartnersDashboardData { + domain: string; + companyId: string; + teamStats: PartnersDashboardStats[]; + userStats: PartnersUserDashboardStats[]; + summary: { + totalTasks: number; + myTasks: number; + teamPending: number; + teamInProgress: number; + teamCompleted: number; + myPending: number; + myInProgress: number; + myCompleted: number; + }; +} + +// Partners 팀 대시보드 데이터 조회 (회사 필터링 포함) +export async function getPartnersTeamDashboardData(domain: string): Promise { + try { + const session = await getServerSession(authOptions); + if (!session?.user?.companyId) { + throw new Error("회사 정보가 없습니다."); + } + + const companyId = session.user.companyId; + const tables = getPartnerTablesByDomain(domain); + + if (tables.length === 0) { + console.warn(`파트너 도메인 '${domain}'에 대한 테이블이 없습니다.`); + return []; + } + + console.log(`👥 회사 ID: ${companyId}로 파트너 데이터 조회`); + + // 병렬 처리로 성능 향상 + const results = await Promise.allSettled( + tables.map(tableConfig => getPartnersTableStats(tableConfig, companyId)) + ); + + // 성공한 결과만 반환 + const successfulResults: PartnersDashboardStats[] = []; + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + successfulResults.push(result.value); + } else { + console.error(`파트너 테이블 ${tables[index].tableName} 통계 조회 실패:`, result.reason); + } + }); + + console.log('📊 파트너 팀 대시보드 결과:', successfulResults); + return successfulResults; + } catch (error) { + console.error("파트너 팀 대시보드 데이터 조회 실패:", error); + throw new Error("파트너 팀 대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// Partners 사용자 대시보드 데이터 조회 +export async function getPartnersUserDashboardData(domain: string): Promise { + try { + const session = await getServerSession(authOptions); + if (!session?.user?.id || !session?.user?.companyId) { + throw new Error("사용자 또는 회사 정보가 없습니다."); + } + + const userId = session.user.id; + const companyId = session.user.companyId; + const tables = getPartnerTablesByDomain(domain); + + if (tables.length === 0) { + console.warn(`파트너 도메인 '${domain}'에 대한 테이블이 없습니다.`); + return []; + } + + console.log(`👤 사용자 ID: ${userId}, 회사 ID: ${companyId}`); + + // 병렬 처리로 성능 향상 + const results = await Promise.allSettled( + tables.map(async (tableConfig) => { + const [teamStats, userStats] = await Promise.all([ + getPartnersTableStats(tableConfig, companyId), + getPartnersUserTableStats(tableConfig, companyId, userId) + ]); + + return { + ...teamStats, + myTotal: userStats.total, + myPending: userStats.pending, + myInProgress: userStats.inProgress, + myCompleted: userStats.completed + } as PartnersUserDashboardStats; + }) + ); + + // 성공한 결과만 반환 + const successfulResults: PartnersUserDashboardStats[] = []; + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + successfulResults.push(result.value); + } else { + console.error(`파트너 테이블 ${tables[index].tableName} 사용자 통계 조회 실패:`, result.reason); + } + }); + + return successfulResults; + } catch (error) { + console.error("파트너 사용자 대시보드 데이터 조회 실패:", error); + throw new Error("파트너 사용자 대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// Partners 전체 대시보드 데이터 조회 +export async function getPartnersDashboardData(domain: string): Promise { + try { + const session = await getServerSession(authOptions); + if (!session?.user?.id || !session?.user?.companyId) { + throw new Error("사용자 또는 회사 정보가 없습니다."); + } + + const [teamStats, userStats] = await Promise.all([ + getPartnersTeamDashboardData(domain), + getPartnersUserDashboardData(domain) + ]); + + // 요약 통계 계산 + const summary = { + totalTasks: teamStats.reduce((sum, stat) => sum + stat.total, 0), + myTasks: userStats.reduce((sum, stat) => sum + stat.myTotal, 0), + teamPending: teamStats.reduce((sum, stat) => sum + stat.pending, 0), + teamInProgress: teamStats.reduce((sum, stat) => sum + stat.inProgress, 0), + teamCompleted: teamStats.reduce((sum, stat) => sum + stat.completed, 0), + myPending: userStats.reduce((sum, stat) => sum + stat.myPending, 0), + myInProgress: userStats.reduce((sum, stat) => sum + stat.myInProgress, 0), + myCompleted: userStats.reduce((sum, stat) => sum + stat.myCompleted, 0) + }; + + return { + domain, + companyId: session.user.companyId, + teamStats, + userStats, + summary + }; + } catch (error) { + console.error("파트너 대시보드 데이터 조회 실패:", error); + throw new Error("파트너 대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// Partners 테이블별 전체 통계 조회 (회사 필터링 포함) +async function getPartnersTableStats(config: TableConfig, companyId: string): Promise { + try { + console.log(`\n🔍 파트너 테이블 ${config.tableName} 통계 조회 (회사: ${companyId})`); + + // 1단계: 회사별 총 개수 확인 + const totalQuery = ` + SELECT COUNT(*)::INTEGER as total + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' + `; + console.log("Total SQL:", totalQuery); + + const totalResult = await db.execute(sql.raw(totalQuery)); + console.log("Total 결과:", totalResult.rows[0]); + + // 2단계: 회사별 상태값 분포 확인 + const statusQuery = ` + SELECT "${config.statusField}" as status, COUNT(*) as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IS NOT NULL + GROUP BY "${config.statusField}" + ORDER BY count DESC + `; + console.log("Status SQL:", statusQuery); + + const statusResult = await db.execute(sql.raw(statusQuery)); + console.log("Status 결과:", statusResult.rows); + + // 3단계: 상태별 개수 조회 + const pendingValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'pending') + .map(([original]) => original); + + const inProgressValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'in_progress') + .map(([original]) => original); + + const completedValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'completed') + .map(([original]) => original); + + console.log("파트너 상태 매핑:"); + console.log("- pending:", pendingValues); + console.log("- inProgress:", inProgressValues); + console.log("- completed:", completedValues); + + let pendingCount = 0; + let inProgressCount = 0; + let completedCount = 0; + + // Pending 개수 (회사 필터 포함) + if (pendingValues.length > 0) { + const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const pendingQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${pendingValuesList}) + `; + + const pendingResult = await db.execute(sql.raw(pendingQuery)); + pendingCount = parseInt(pendingResult.rows[0]?.count || '0'); + console.log("Pending 개수:", pendingCount); + } + + // In Progress 개수 (회사 필터 포함) + if (inProgressValues.length > 0) { + const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const inProgressQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${inProgressValuesList}) + `; + + const inProgressResult = await db.execute(sql.raw(inProgressQuery)); + inProgressCount = parseInt(inProgressResult.rows[0]?.count || '0'); + console.log("InProgress 개수:", inProgressCount); + } + + // Completed 개수 (회사 필터 포함) + if (completedValues.length > 0) { + const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const completedQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND "${config.statusField}" IN (${completedValuesList}) + `; + + const completedResult = await db.execute(sql.raw(completedQuery)); + completedCount = parseInt(completedResult.rows[0]?.count || '0'); + console.log("Completed 개수:", completedCount); + } + + const stats = { + tableName: config.tableName, + displayName: config.displayName, + total: parseInt(totalResult.rows[0]?.total || '0'), + pending: pendingCount, + inProgress: inProgressCount, + completed: completedCount + }; + + console.log(`✅ 파트너 ${config.tableName} 최종 통계:`, stats); + return stats; + } catch (error) { + console.error(`❌ 파트너 테이블 ${config.tableName} 통계 조회 중 오류:`, error); + return createEmptyPartnersStats(config); + } +} + +// Partners 사용자별 테이블 통계 조회 (회사 + 사용자 필터링) +async function getPartnersUserTableStats(config: TableConfig, companyId: string, userId: string): Promise { + try { + // 사용자 필드가 없는 경우 빈 통계 반환 + if (!hasUserFields(config)) { + console.log(`⚠️ 파트너 테이블 ${config.tableName}에 사용자 필드가 없습니다.`); + return createEmptyPartnersStats(config); + } + + console.log(`\n👤 파트너 사용자 ${userId}의 ${config.tableName} 통계 조회 (회사: ${companyId})`); + + // 사용자 조건 생성 (회사 필터 포함) + const userConditions = []; + if (config.userFields.creator) { + userConditions.push(`"${config.userFields.creator}" = '${userId}'`); + } + if (config.userFields.updater) { + userConditions.push(`"${config.userFields.updater}" = '${userId}'`); + } + if (config.userFields.assignee) { + userConditions.push(`"${config.userFields.assignee}" = '${userId}'`); + } + + if (userConditions.length === 0) { + return createEmptyPartnersStats(config); + } + + const userConditionStr = userConditions.join(' OR '); + + // 1. 사용자 + 회사 총 개수 + const userTotalQuery = ` + SELECT COUNT(*)::INTEGER as total + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) + `; + console.log("User Total SQL:", userTotalQuery); + + const userTotalResult = await db.execute(sql.raw(userTotalQuery)); + console.log("User Total 결과:", userTotalResult.rows[0]); + + // 2. 사용자 + 회사 상태별 개수 + const pendingValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'pending') + .map(([original]) => original); + + const inProgressValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'in_progress') + .map(([original]) => original); + + const completedValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'completed') + .map(([original]) => original); + + let userPendingCount = 0; + let userInProgressCount = 0; + let userCompletedCount = 0; + + // User + Company Pending 개수 + if (pendingValues.length > 0) { + const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userPendingQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${pendingValuesList}) + `; + + const userPendingResult = await db.execute(sql.raw(userPendingQuery)); + userPendingCount = parseInt(userPendingResult.rows[0]?.count || '0'); + console.log("User Pending 개수:", userPendingCount); + } + + // User + Company In Progress 개수 + if (inProgressValues.length > 0) { + const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userInProgressQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${inProgressValuesList}) + `; + + const userInProgressResult = await db.execute(sql.raw(userInProgressQuery)); + userInProgressCount = parseInt(userInProgressResult.rows[0]?.count || '0'); + console.log("User InProgress 개수:", userInProgressCount); + } + + // User + Company Completed 개수 + if (completedValues.length > 0) { + const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userCompletedQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "vendor_id" = '${companyId}' AND (${userConditionStr}) AND "${config.statusField}" IN (${completedValuesList}) + `; + + const userCompletedResult = await db.execute(sql.raw(userCompletedQuery)); + userCompletedCount = parseInt(userCompletedResult.rows[0]?.count || '0'); + console.log("User Completed 개수:", userCompletedCount); + } + + const stats = { + tableName: config.tableName, + displayName: config.displayName, + total: parseInt(userTotalResult.rows[0]?.total || '0'), + pending: userPendingCount, + inProgress: userInProgressCount, + completed: userCompletedCount + }; + + console.log(`✅ 파트너 사용자 ${config.tableName} 최종 통계:`, stats); + return stats; + } catch (error) { + console.error(`❌ 파트너 테이블 ${config.tableName} 사용자 통계 조회 중 오류:`, error); + return createEmptyPartnersStats(config); + } +} + +// 유틸리티 함수들 +function createEmptyPartnersStats(config: TableConfig): PartnersDashboardStats { + return { + tableName: config.tableName, + displayName: config.displayName, + total: 0, + pending: 0, + inProgress: 0, + completed: 0 + }; +} + +function hasUserFields(config: TableConfig): boolean { + return !!(config.userFields.creator || config.userFields.updater || config.userFields.assignee); +} + +// 디버깅 함수: Partners 전용 +export async function simplePartnersTest(tableName: string, statusField: string, companyId: string) { + try { + console.log(`\n🧪 파트너 ${tableName} 간단한 테스트 (회사: ${companyId}):`); + + // 1. 회사별 총 개수 + const totalQuery = `SELECT COUNT(*) as total FROM "${tableName}" WHERE "vendor_id" = '${companyId}'`; + const totalResult = await db.execute(sql.raw(totalQuery)); + console.log("회사별 총 개수:", totalResult.rows[0]); + + // 2. 회사별 상태 분포 + const statusQuery = ` + SELECT "${statusField}" as status, COUNT(*) as count + FROM "${tableName}" + WHERE "vendor_id" = '${companyId}' + GROUP BY "${statusField}" + ORDER BY count DESC + `; + const statusResult = await db.execute(sql.raw(statusQuery)); + console.log("회사별 상태 분포:", statusResult.rows); + + return { + total: totalResult.rows[0], + statusDistribution: statusResult.rows + }; + } catch (error) { + console.error("파트너 간단한 테스트 실패:", error); + return null; + } +} \ No newline at end of file diff --git a/lib/dashboard/service.ts b/lib/dashboard/service.ts new file mode 100644 index 00000000..16b05d45 --- /dev/null +++ b/lib/dashboard/service.ts @@ -0,0 +1,454 @@ +"use server"; + +import db from "@/db/db"; +import { sql, eq, or, and, count, sum, inArray } from "drizzle-orm"; +import { getServerSession } from "next-auth/next"; +import { authOptions } from "@/app/api/auth/[...nextauth]/route"; +import { getTablesByDomain } from "@/config/dashboard-table"; +import { TableConfig } from "@/types/dashboard"; + +export interface DashboardStats { + tableName: string; + displayName: string; + total: number; + pending: number; + inProgress: number; + completed: number; +} + +export interface UserDashboardStats extends DashboardStats { + myTotal: number; + myPending: number; + myInProgress: number; + myCompleted: number; +} + +export interface DashboardData { + domain: string; + teamStats: DashboardStats[]; + userStats: UserDashboardStats[]; + summary: { + totalTasks: number; + myTasks: number; + teamPending: number; + teamInProgress: number; + teamCompleted: number; + myPending: number; + myInProgress: number; + myCompleted: number; + }; +} + +// 팀 대시보드 데이터 조회 +export async function getTeamDashboardData(domain: string): Promise { + try { + const tables = getTablesByDomain(domain); + + if (tables.length === 0) { + console.warn(`도메인 '${domain}'에 대한 테이블이 없습니다.`); + return []; + } + + // 병렬 처리로 성능 향상 + const results = await Promise.allSettled( + tables.map(tableConfig => getTableStats(tableConfig)) + ); + + // 성공한 결과만 반환, 실패한 것들은 로그 출력 + const successfulResults: DashboardStats[] = []; + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + successfulResults.push(result.value); + } else { + console.error(`테이블 ${tables[index].tableName} 통계 조회 실패:`, result.reason); + } + }); + + console.log('📊 팀 대시보드 결과:', successfulResults); + + return successfulResults; + } catch (error) { + console.error("팀 대시보드 데이터 조회 실패:", error); + throw new Error("팀 대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// 사용자 대시보드 데이터 조회 +export async function getUserDashboardData(domain: string): Promise { + try { + // 현재 사용자 정보 가져오기 + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + throw new Error("인증되지 않은 사용자입니다."); + } + + const userId = session.user.id; + const tables = getTablesByDomain(domain); + + if (tables.length === 0) { + console.warn(`도메인 '${domain}'에 대한 테이블이 없습니다.`); + return []; + } + + console.log(`👤 사용자 ID: ${userId}`); + + // 병렬 처리로 성능 향상 + const results = await Promise.allSettled( + tables.map(async (tableConfig) => { + const [teamStats, userStats] = await Promise.all([ + getTableStats(tableConfig), + getUserTableStats(tableConfig, userId) + ]); + + return { + ...teamStats, + myTotal: userStats.total, + myPending: userStats.pending, + myInProgress: userStats.inProgress, + myCompleted: userStats.completed + } as UserDashboardStats; + }) + ); + + // 성공한 결과만 반환 + const successfulResults: UserDashboardStats[] = []; + results.forEach((result, index) => { + if (result.status === 'fulfilled') { + successfulResults.push(result.value); + } else { + console.error(`테이블 ${tables[index].tableName} 사용자 통계 조회 실패:`, result.reason); + } + }); + + return successfulResults; + } catch (error) { + console.error("사용자 대시보드 데이터 조회 실패:", error); + throw new Error("사용자 대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// 전체 대시보드 데이터 조회 (팀 + 개인) +export async function getDashboardData(domain: string): Promise { + try { + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + throw new Error("인증되지 않은 사용자입니다."); + } + + // 병렬 처리로 성능 향상 + const [teamStats, userStats] = await Promise.all([ + getTeamDashboardData(domain), + getUserDashboardData(domain) + ]); + + // 요약 통계 계산 + const summary = { + totalTasks: teamStats.reduce((sum, stat) => sum + stat.total, 0), + myTasks: userStats.reduce((sum, stat) => sum + stat.myTotal, 0), + teamPending: teamStats.reduce((sum, stat) => sum + stat.pending, 0), + teamInProgress: teamStats.reduce((sum, stat) => sum + stat.inProgress, 0), + teamCompleted: teamStats.reduce((sum, stat) => sum + stat.completed, 0), + myPending: userStats.reduce((sum, stat) => sum + stat.myPending, 0), + myInProgress: userStats.reduce((sum, stat) => sum + stat.myInProgress, 0), + myCompleted: userStats.reduce((sum, stat) => sum + stat.myCompleted, 0) + }; + + return { + domain, + teamStats, + userStats, + summary + }; + } catch (error) { + console.error("대시보드 데이터 조회 실패:", error); + throw new Error("대시보드 데이터를 불러오는데 실패했습니다."); + } +} + +// 테이블별 전체 통계 조회 (완전히 수정된 버전) +async function getTableStats(config: TableConfig): Promise { + try { + console.log(`\n🔍 테이블 ${config.tableName} 통계 조회 시작`); + + // 1단계: 기본 총 개수 확인 + console.log("1단계: 총 개수 조회"); + const totalQuery = `SELECT COUNT(*)::INTEGER as total FROM "${config.tableName}"`; + console.log("Total SQL:", totalQuery); + + const totalResult = await db.execute(sql.raw(totalQuery)); + console.log("Total 결과:", totalResult.rows[0]); + + // 2단계: 실제 상태값 확인 + console.log("2단계: 상태값 분포 확인"); + const statusQuery = ` + SELECT "${config.statusField}" as status, COUNT(*) as count + FROM "${config.tableName}" + WHERE "${config.statusField}" IS NOT NULL + GROUP BY "${config.statusField}" + ORDER BY count DESC + `; + console.log("Status SQL:", statusQuery); + + const statusResult = await db.execute(sql.raw(statusQuery)); + console.log("Status 결과:", statusResult.rows); + + // 3단계: 상태별 개수 조회 (개별 쿼리) + console.log("3단계: 상태별 개수 조회"); + + const pendingValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'pending') + .map(([original]) => original); + + const inProgressValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'in_progress') + .map(([original]) => original); + + const completedValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'completed') + .map(([original]) => original); + + console.log("매핑된 상태값:"); + console.log("- pending:", pendingValues); + console.log("- inProgress:", inProgressValues); + console.log("- completed:", completedValues); + + // 개별 쿼리로 정확한 개수 조회 + let pendingCount = 0; + let inProgressCount = 0; + let completedCount = 0; + + // Pending 개수 + if (pendingValues.length > 0) { + const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const pendingQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "${config.statusField}" IN (${pendingValuesList}) + `; + console.log("Pending SQL:", pendingQuery); + + const pendingResult = await db.execute(sql.raw(pendingQuery)); + pendingCount = parseInt(pendingResult.rows[0]?.count || '0'); + console.log("Pending 개수:", pendingCount); + } + + // In Progress 개수 + if (inProgressValues.length > 0) { + const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const inProgressQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "${config.statusField}" IN (${inProgressValuesList}) + `; + console.log("InProgress SQL:", inProgressQuery); + + const inProgressResult = await db.execute(sql.raw(inProgressQuery)); + inProgressCount = parseInt(inProgressResult.rows[0]?.count || '0'); + console.log("InProgress 개수:", inProgressCount); + } + + // Completed 개수 + if (completedValues.length > 0) { + const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const completedQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE "${config.statusField}" IN (${completedValuesList}) + `; + console.log("Completed SQL:", completedQuery); + + const completedResult = await db.execute(sql.raw(completedQuery)); + completedCount = parseInt(completedResult.rows[0]?.count || '0'); + console.log("Completed 개수:", completedCount); + } + + const stats = { + tableName: config.tableName, + displayName: config.displayName, + total: parseInt(totalResult.rows[0]?.total || '0'), + pending: pendingCount, + inProgress: inProgressCount, + completed: completedCount + }; + + console.log(`✅ ${config.tableName} 최종 통계:`, stats); + return stats; + } catch (error) { + console.error(`❌ 테이블 ${config.tableName} 통계 조회 중 오류:`, error); + // 에러 발생 시 빈 통계 반환 + return createEmptyStats(config); + } +} + +// 사용자별 테이블 통계 조회 (수정된 버전) +async function getUserTableStats(config: TableConfig, userId: string): Promise { + try { + // 사용자 필드가 없는 경우 빈 통계 반환 + if (!hasUserFields(config)) { + console.log(`⚠️ 테이블 ${config.tableName}에 사용자 필드가 없습니다.`); + return createEmptyStats(config); + } + + console.log(`\n👤 사용자 ${userId}의 ${config.tableName} 통계 조회`); + + // 사용자 조건 생성 + const userConditions = []; + if (config.userFields.creator) { + userConditions.push(`"${config.userFields.creator}" = '${userId}'`); + } + if (config.userFields.updater) { + userConditions.push(`"${config.userFields.updater}" = '${userId}'`); + } + if (config.userFields.assignee) { + userConditions.push(`"${config.userFields.assignee}" = '${userId}'`); + } + + if (userConditions.length === 0) { + return createEmptyStats(config); + } + + const userConditionStr = userConditions.join(' OR '); + + // 1. 사용자 총 개수 + const userTotalQuery = ` + SELECT COUNT(*)::INTEGER as total + FROM "${config.tableName}" + WHERE ${userConditionStr} + `; + console.log("User Total SQL:", userTotalQuery); + + const userTotalResult = await db.execute(sql.raw(userTotalQuery)); + console.log("User Total 결과:", userTotalResult.rows[0]); + + // 2. 사용자 상태별 개수 + const pendingValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'pending') + .map(([original]) => original); + + const inProgressValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'in_progress') + .map(([original]) => original); + + const completedValues = Object.entries(config.statusMapping) + .filter(([_, mapped]) => mapped === 'completed') + .map(([original]) => original); + + let userPendingCount = 0; + let userInProgressCount = 0; + let userCompletedCount = 0; + + // User Pending 개수 + if (pendingValues.length > 0) { + const pendingValuesList = pendingValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userPendingQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE (${userConditionStr}) AND "${config.statusField}" IN (${pendingValuesList}) + `; + + const userPendingResult = await db.execute(sql.raw(userPendingQuery)); + userPendingCount = parseInt(userPendingResult.rows[0]?.count || '0'); + console.log("User Pending 개수:", userPendingCount); + } + + // User In Progress 개수 + if (inProgressValues.length > 0) { + const inProgressValuesList = inProgressValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userInProgressQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE (${userConditionStr}) AND "${config.statusField}" IN (${inProgressValuesList}) + `; + + const userInProgressResult = await db.execute(sql.raw(userInProgressQuery)); + userInProgressCount = parseInt(userInProgressResult.rows[0]?.count || '0'); + console.log("User InProgress 개수:", userInProgressCount); + } + + // User Completed 개수 + if (completedValues.length > 0) { + const completedValuesList = completedValues.map(v => `'${v.replace(/'/g, "''")}'`).join(','); + const userCompletedQuery = ` + SELECT COUNT(*)::INTEGER as count + FROM "${config.tableName}" + WHERE (${userConditionStr}) AND "${config.statusField}" IN (${completedValuesList}) + `; + + const userCompletedResult = await db.execute(sql.raw(userCompletedQuery)); + userCompletedCount = parseInt(userCompletedResult.rows[0]?.count || '0'); + console.log("User Completed 개수:", userCompletedCount); + } + + const stats = { + tableName: config.tableName, + displayName: config.displayName, + total: parseInt(userTotalResult.rows[0]?.total || '0'), + pending: userPendingCount, + inProgress: userInProgressCount, + completed: userCompletedCount + }; + + console.log(`✅ 사용자 ${config.tableName} 최종 통계:`, stats); + return stats; + } catch (error) { + console.error(`❌ 테이블 ${config.tableName} 사용자 통계 조회 중 오류:`, error); + return createEmptyStats(config); + } +} + +// 유틸리티 함수들 +function createEmptyStats(config: TableConfig): DashboardStats { + return { + tableName: config.tableName, + displayName: config.displayName, + total: 0, + pending: 0, + inProgress: 0, + completed: 0 + }; +} + +function hasUserFields(config: TableConfig): boolean { + return !!(config.userFields.creator || config.userFields.updater || config.userFields.assignee); +} + +// 디버깅 함수: 단순한 테스트 +export async function simpleTest(tableName: string, statusField: string) { + try { + console.log(`\n🧪 ${tableName} 간단한 테스트:`); + + // 1. 총 개수 + const totalQuery = `SELECT COUNT(*) as total FROM "${tableName}"`; + const totalResult = await db.execute(sql.raw(totalQuery)); + console.log("총 개수:", totalResult.rows[0]); + + // 2. 상태 분포 + const statusQuery = ` + SELECT "${statusField}" as status, COUNT(*) as count + FROM "${tableName}" + GROUP BY "${statusField}" + ORDER BY count DESC + `; + const statusResult = await db.execute(sql.raw(statusQuery)); + console.log("상태 분포:", statusResult.rows); + + // 3. 특정 상태 테스트 + const draftQuery = `SELECT COUNT(*) as count FROM "${tableName}" WHERE "${statusField}" = 'DRAFT'`; + const draftResult = await db.execute(sql.raw(draftQuery)); + console.log("DRAFT 개수:", draftResult.rows[0]); + + const docConfirmedQuery = `SELECT COUNT(*) as count FROM "${tableName}" WHERE "${statusField}" = 'Doc. Confirmed'`; + const docConfirmedResult = await db.execute(sql.raw(docConfirmedQuery)); + console.log("Doc. Confirmed 개수:", docConfirmedResult.rows[0]); + + return { + total: totalResult.rows[0], + statusDistribution: statusResult.rows, + draft: draftResult.rows[0], + docConfirmed: docConfirmedResult.rows[0] + }; + } catch (error) { + console.error("간단한 테스트 실패:", error); + return null; + } +} \ No newline at end of file diff --git a/lib/qna/service.ts b/lib/qna/service.ts new file mode 100644 index 00000000..d9c877c6 --- /dev/null +++ b/lib/qna/service.ts @@ -0,0 +1,1006 @@ +"use server"; + +import { revalidateTag, unstable_noStore } from "next/cache"; +import { getServerSession } from "next-auth/next"; +import { authOptions } from "@/app/api/auth/[...nextauth]/route"; +import db from "@/db/db"; +import { qna, qnaAnswer, qnaComments } from "@/db/schema/qna"; +import { qnaView, qnaAnswerView, qnaCommentView } from "@/db/schema"; +import { + eq, + desc, + asc, + and, + or, + ilike, + inArray, + gte, + lte, + isNull, + isNotNull, + count, + sql +} from "drizzle-orm"; +import { unstable_cache } from "@/lib/unstable-cache"; +import { filterColumns } from "@/lib/filter-columns"; +import type { + GetQnaSchema, + CreateQnaSchema, + UpdateQnaSchema, + CreateAnswerSchema, + UpdateAnswerSchema, + CreateCommentSchema, + UpdateCommentSchema, +} from "./validation"; + +/* ================================================================ + Helper Functions +================================================================ */ + +/** + * 인증된 사용자 정보 가져오기 + */ +async function getAuthenticatedUser() { + const session = await getServerSession(authOptions); + if (!session?.user?.id) { + throw new Error("인증이 필요합니다."); + } + return parseInt(session.user.id); +} + +/** + * 현재 사용자 ID 가져오기 (비로그인 허용) + */ +async function getCurrentUserId() { + try { + const session = await getServerSession(authOptions); + return session?.user?.id ? parseInt(session.user.id) : null; + } catch { + return null; + } +} + +/* ================================================================ + Repository Functions (트랜잭션 지원) +================================================================ */ + +/** + * Q&A 목록 조회 Repository + */ +async function selectQnaList( + tx: any, + options: { + where?: any; + orderBy?: any[]; + offset: number; + limit: number; + } +) { + const { where, orderBy = [desc(qnaView.createdAt)], offset, limit } = options; + + return await tx + .select() + .from(qnaView) + .where(where) + .orderBy(...orderBy) + .offset(offset) + .limit(limit); +} + +/** + * Q&A 총 개수 조회 Repository + */ +async function countQnaList(tx: any, where?: any) { + const [result] = await tx + .select({ count: count() }) + .from(qnaView) + .where(where); + return result.count; +} + +/** + * Q&A 상세 조회 Repository + */ +async function selectQnaDetail(tx: any, id: number) { + const [question] = await tx + .select() + .from(qnaView) + .where(eq(qnaView.id, id)); + + return question || null; +} + +/** + * 답변 목록 조회 Repository + */ +async function selectAnswersByQnaId(tx: any, qnaId: number) { + return await tx + .select() + .from(qnaAnswerView) + .where(eq(qnaAnswerView.qnaId, qnaId)) + .orderBy(desc(qnaAnswerView.createdAt)); +} + +/** + * 댓글 목록 조회 Repository (계층형) + */ +async function selectCommentsByAnswerId(tx: any, answerId: number) { + return await tx + .select() + .from(qnaCommentView) + .where(eq(qnaCommentView.answerId, answerId)) + .orderBy(asc(qnaCommentView.createdAt)); // 댓글은 오래된 순으로 +} + +/** + * 내가 답변한 질문 ID 목록 조회 + */ +async function getMyAnsweredQnaIds(tx: any, userId: number, qnaIds: number[]) { + if (qnaIds.length === 0) return []; + + const results = await tx + .select({ qnaId: qnaAnswer.qnaId }) + .from(qnaAnswer) + .where( + and( + eq(qnaAnswer.author, userId), + inArray(qnaAnswer.qnaId, qnaIds), + eq(qnaAnswer.isDeleted, false) + ) + ); + + return results.map(r => r.qnaId); +} + +/* ================================================================ + 1) Q&A 목록 조회 (고급 필터링/정렬 지원) +================================================================ */ + +export async function getQnaList(input: GetQnaSchema) { + return unstable_cache( + async () => { + try { + const offset = (input.page - 1) * input.perPage; + const advancedTable = input.flags.includes("advancedTable") || true; + + // 현재 사용자 ID (내 답변 여부 확인용) + const currentUserId = await getCurrentUserId(); + + // 고급 필터링 WHERE 절 구성 + const advancedWhere = advancedTable + ? filterColumns({ + table: qnaView, + filters: input.filters, + joinOperator: input.joinOperator, + }) + : undefined; + + // 전역 검색 WHERE 절 + let globalWhere; + if (input.search) { + const searchPattern = `%${input.search}%`; + globalWhere = or( + ilike(qnaView.title, searchPattern), + ilike(qnaView.content, searchPattern), + ilike(qnaView.authorName, searchPattern), + ilike(qnaView.companyName, searchPattern) + ); + } + + // Q&A 특화 필터링 + const qnaSpecificWhere = and( + // 도메인 필터 + input.authorDomain.length > 0 + ? inArray(qnaView.authorDomain, input.authorDomain) + : undefined, + + // 벤더 타입 필터 + input.vendorType.length > 0 + ? inArray(qnaView.vendorType, input.vendorType) + : undefined, + + // 답변 유무 필터 (뷰에서 이미 계산된 값 사용) + input.hasAnswers === "answered" + ? eq(qnaView.hasAnswers, true) + : input.hasAnswers === "unanswered" + ? eq(qnaView.hasAnswers, false) + : undefined, + + // 내 질문만 보기 + input.myQuestions === "true" && currentUserId + ? eq(qnaView.author, currentUserId) + : undefined, + + // 날짜 범위 필터 + ); + + // 최종 WHERE 절 결합 + const finalWhere = and( + advancedWhere, + globalWhere, + qnaSpecificWhere + ); + + // 정렬 설정 + const orderBy = input.sort.length > 0 + ? input.sort.map((item) => + item.desc + ? desc(qnaView[item.id as keyof typeof qnaView]) + : asc(qnaView[item.id as keyof typeof qnaView]) + ) + : [desc(qnaView.lastActivityAt), desc(qnaView.createdAt)]; // 최근 활동순으로 기본 정렬 + + // 트랜잭션 내에서 데이터 조회 + const { data, total } = await db.transaction(async (tx) => { + const data = await selectQnaList(tx, { + where: finalWhere, + orderBy, + offset, + limit: input.perPage, + }); + + const total = await countQnaList(tx, finalWhere); + + // 내가 답변한 질문들 표시 (로그인한 경우만) + let dataWithMyAnswers = data; + if (currentUserId && data.length > 0) { + const qnaIds = data.map(q => q.id); + const myAnsweredIds = await getMyAnsweredQnaIds(tx, currentUserId, qnaIds); + + dataWithMyAnswers = data.map(q => ({ + ...q, + hasMyAnswer: myAnsweredIds.includes(q.id), + isMyQuestion: currentUserId === q.author, + })); + } else { + dataWithMyAnswers = data.map(q => ({ + ...q, + hasMyAnswer: false, + isMyQuestion: false, + })); + } + + return { data: dataWithMyAnswers, total }; + }); + + const pageCount = Math.ceil(total / input.perPage); + + return { + data, + pageCount, + total, + // 메타 정보 추가 + meta: { + currentPage: input.page, + perPage: input.perPage, + hasNextPage: input.page < pageCount, + hasPrevPage: input.page > 1, + } + }; + } catch (err) { + console.error("Q&A 목록 조회 실패:", err); + return { + data: [], + pageCount: 0, + total: 0, + meta: { + currentPage: 1, + perPage: input.perPage, + hasNextPage: false, + hasPrevPage: false, + } + }; + } + }, + [JSON.stringify(input)], // 캐싱 키 + { + revalidate: 1800, // 30분 캐싱 + tags: ["qna", "qna-list"], + } + )(); +} + +/* ================================================================ + 2) Q&A 상세 조회 +================================================================ */ + +export async function getQnaById(id: number) { + return unstable_cache( + async () => { + try { + const currentUserId = await getCurrentUserId(); + + return await db.transaction(async (tx) => { + // 질문 정보 조회 (뷰 사용으로 단순화) + const question = await selectQnaDetail(tx, id); + if (!question) return null; + + // 답변 목록 조회 (뷰 사용으로 단순화) + const answers = await selectAnswersByQnaId(tx, id); + + // 각 답변의 댓글들 조회 및 계층 구조 생성 + const answersWithComments = await Promise.all( + answers.map(async (answer) => { + const comments = await selectCommentsByAnswerId(tx, answer.id); + + // 댓글 계층 구조 생성 (뷰에서 이미 계층 정보 제공) + const commentMap = new Map(); + const rootComments: any[] = []; + + // 먼저 모든 댓글을 Map에 저장 + comments.forEach(comment => { + commentMap.set(comment.id, { + ...comment, + children: [], + isMyComment: currentUserId === comment.author, + }); + }); + + // 계층 구조 생성 + comments.forEach(comment => { + const commentWithChildren = commentMap.get(comment.id); + if (comment.parentCommentId) { + const parent = commentMap.get(comment.parentCommentId); + if (parent) { + parent.children.push(commentWithChildren); + } + } else { + rootComments.push(commentWithChildren); + } + }); + + return { + ...answer, + comments: rootComments, + isMyAnswer: currentUserId === answer.author, + }; + }) + ); + + return { + ...question, + answers: answersWithComments, + isMyQuestion: currentUserId === question.author, + // 뷰에서 이미 계산된 통계 정보 활용 + totalInteractions: question.totalAnswers + question.totalComments, + }; + }); + } catch (err) { + console.error("Q&A 상세 조회 실패:", err); + return null; + } + }, + [`qna-detail-${id}`], + { + revalidate: 1800, // 30분 캐싱 + tags: ["qna", `qna-${id}`], + } + )(); +} + +/* ================================================================ + 3) Q&A 생성/수정/삭제 (CRUD 액션들) +================================================================ */ + +/** + * 새로운 Q&A 질문 생성 + */ +export async function createQna(input: CreateQnaSchema) { + try { + const userId = await getAuthenticatedUser(); + + const [newQna] = await db.insert(qna).values({ + title: input.title, + content: input.content, + category: input.category, + author: userId, + }).returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + + return { + success: true, + data: newQna, + message: "질문이 성공적으로 등록되었습니다." + }; + } catch (err) { + console.error("질문 생성 실패:", err); + return { + success: false, + error: err instanceof Error ? err.message : "질문 등록에 실패했습니다.", + data: null + }; + } +} + +/** + * Q&A 질문 수정 + */ +export async function updateQna(id: number, input: UpdateQnaSchema) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 + const [existing] = await db + .select({ + author: qna.author, + title: qna.title + }) + .from(qna) + .where(eq(qna.id, id)); + + if (!existing) { + return { success: false, error: "질문을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "수정 권한이 없습니다." }; + } + + const [updated] = await db + .update(qna) + .set({ + ...input, + updatedAt: new Date() + }) + .where(eq(qna.id, id)) + .returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${id}`); + + return { + success: true, + data: updated, + message: "질문이 성공적으로 수정되었습니다." + }; + } catch (err) { + console.error("질문 수정 실패:", err); + return { + success: false, + error: err instanceof Error ? err.message : "질문 수정에 실패했습니다." + }; + } +} + +/** + * Q&A 질문 삭제 (소프트 삭제) + */ +export async function deleteQna(id: number) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 + const [existing] = await db + .select({ + author: qna.author, + title: qna.title + }) + .from(qna) + .where(eq(qna.id, id)); + + if (!existing) { + return { success: false, error: "질문을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "삭제 권한이 없습니다." }; + } + + await db + .update(qna) + .set({ + isDeleted: true, + deletedAt: new Date() + }) + .where(eq(qna.id, id)); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${id}`); + + return { + success: true, + message: "질문이 성공적으로 삭제되었습니다." + }; + } catch (err) { + console.error("질문 삭제 실패:", err); + return { + success: false, + error: err instanceof Error ? err.message : "질문 삭제에 실패했습니다." + }; + } +} + +/* ================================================================ + 4) 답변 관련 CRUD 액션들 +================================================================ */ + +/** + * 답변 생성 + */ +export async function createAnswer(input: CreateAnswerSchema) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 질문 존재 여부 확인 + const [questionExists] = await db + .select({ id: qna.id }) + .from(qna) + .where(and( + eq(qna.id, input.qnaId), + eq(qna.isDeleted, false) + )); + + if (!questionExists) { + return { success: false, error: "존재하지 않는 질문입니다." }; + } + + const [newAnswer] = await db.insert(qnaAnswer).values({ + qnaId: input.qnaId, + content: input.content, + author: userId, + }).returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${input.qnaId}`); + + return { + success: true, + data: newAnswer, + message: "답변이 성공적으로 등록되었습니다." + }; + } catch (error) { + console.error("답변 생성 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "답변 등록에 실패했습니다." + }; + } +} + +/** + * 답변 수정 + */ +export async function updateAnswer(id: number, input: UpdateAnswerSchema) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 + const [existing] = await db + .select({ + author: qnaAnswer.author, + qnaId: qnaAnswer.qnaId + }) + .from(qnaAnswer) + .where(eq(qnaAnswer.id, id)); + + if (!existing) { + return { success: false, error: "답변을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "수정 권한이 없습니다." }; + } + + const [updated] = await db + .update(qnaAnswer) + .set({ + content: input.content, + updatedAt: new Date() + }) + .where(eq(qnaAnswer.id, id)) + .returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${existing.qnaId}`); + + return { + success: true, + data: updated, + message: "답변이 성공적으로 수정되었습니다." + }; + } catch (err) { + console.error("답변 수정 실패:", err); + return { + success: false, + error: err instanceof Error ? err.message : "답변 수정에 실패했습니다." + }; + } +} + +/** + * 답변 삭제 + */ +export async function deleteAnswer(id: number) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 + const [existing] = await db + .select({ + author: qnaAnswer.author, + qnaId: qnaAnswer.qnaId + }) + .from(qnaAnswer) + .where(eq(qnaAnswer.id, id)); + + if (!existing) { + return { success: false, error: "답변을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "삭제 권한이 없습니다." }; + } + + // 하드 삭제 (답변은 CASCADE로 댓글도 함께 삭제) + await db.delete(qnaAnswer).where(eq(qnaAnswer.id, id)); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${existing.qnaId}`); + + return { + success: true, + message: "답변이 성공적으로 삭제되었습니다." + }; + } catch (err) { + console.error("답변 삭제 실패:", err); + return { + success: false, + error: err instanceof Error ? err.message : "답변 삭제에 실패했습니다." + }; + } +} + +/* ================================================================ + 5) 댓글 관련 CRUD 액션들 +================================================================ */ + +/** + * 댓글 생성 + */ +export async function createComment(input: CreateCommentSchema) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 답변 존재 여부 확인 + const [answerExists] = await db + .select({ + id: qnaAnswer.id, + qnaId: qnaAnswer.qnaId + }) + .from(qnaAnswer) + .where(and( + eq(qnaAnswer.id, input.answerId), + eq(qnaAnswer.isDeleted, false) + )); + + if (!answerExists) { + return { success: false, error: "존재하지 않는 답변입니다." }; + } + + // 부모 댓글 존재 여부 확인 (대댓글인 경우) + if (input.parentCommentId) { + const [parentExists] = await db + .select({ id: qnaComments.id }) + .from(qnaComments) + .where(and( + eq(qnaComments.id, input.parentCommentId), + eq(qnaComments.answerId, input.answerId), + eq(qnaComments.isDeleted, false) + )); + + if (!parentExists) { + return { success: false, error: "존재하지 않는 부모 댓글입니다." }; + } + } + + const [newComment] = await db.insert(qnaComments).values({ + ...input, + author: userId, + }).returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${answerExists.qnaId}`); + + return { + success: true, + data: newComment, + message: "댓글이 성공적으로 등록되었습니다." + }; + } catch (error) { + console.error("댓글 작성 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "댓글 등록에 실패했습니다." + }; + } +} + +/** + * 댓글 수정 + */ +export async function updateComment(id: number, input: UpdateCommentSchema) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 및 질문 ID 가져오기 + const [existing] = await db + .select({ + author: qnaComments.author, + answerId: qnaComments.answerId, + qnaId: qnaAnswer.qnaId + }) + .from(qnaComments) + .leftJoin(qnaAnswer, eq(qnaComments.answerId, qnaAnswer.id)) + .where(eq(qnaComments.id, id)); + + if (!existing) { + return { success: false, error: "댓글을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "수정 권한이 없습니다." }; + } + + const [updated] = await db + .update(qnaComments) + .set({ + content: input.content, + updatedAt: new Date() + }) + .where(eq(qnaComments.id, id)) + .returning(); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${existing.qnaId}`); + + return { + success: true, + data: updated, + message: "댓글이 성공적으로 수정되었습니다." + }; + } catch (error) { + console.error("댓글 수정 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "댓글 수정에 실패했습니다." + }; + } +} + +/** + * 댓글 삭제 + */ +export async function deleteComment(id: number) { + unstable_noStore(); + try { + const userId = await getAuthenticatedUser(); + + // 권한 확인 및 질문 ID 가져오기 + const [existing] = await db + .select({ + author: qnaComments.author, + answerId: qnaComments.answerId, + qnaId: qnaAnswer.qnaId + }) + .from(qnaComments) + .leftJoin(qnaAnswer, eq(qnaComments.answerId, qnaAnswer.id)) + .where(eq(qnaComments.id, id)); + + if (!existing) { + return { success: false, error: "댓글을 찾을 수 없습니다." }; + } + + if (existing.author !== userId) { + return { success: false, error: "삭제 권한이 없습니다." }; + } + + // 하드 삭제 (대댓글도 CASCADE로 함께 삭제) + await db.delete(qnaComments).where(eq(qnaComments.id, id)); + + revalidateTag("qna"); + revalidateTag("qna-list"); + revalidateTag(`qna-${existing.qnaId}`); + + return { + success: true, + message: "댓글이 성공적으로 삭제되었습니다." + }; + } catch (error) { + console.error("댓글 삭제 실패:", error); + return { + success: false, + error: error instanceof Error ? error.message : "댓글 삭제에 실패했습니다." + }; + } +} + +/* ================================================================ + 6) 답변별 댓글 목록 조회 +================================================================ */ + +export async function getCommentsByAnswerId(answerId: number) { + return unstable_cache( + async () => { + try { + const currentUserId = await getCurrentUserId(); + + return await db.transaction(async (tx) => { + const comments = await selectCommentsByAnswerId(tx, answerId); + + // 댓글 계층 구조 생성 + const commentMap = new Map(); + const rootComments: any[] = []; + + // 모든 댓글을 Map에 저장 + comments.forEach(comment => { + commentMap.set(comment.id, { + ...comment, + children: [], + isMyComment: currentUserId === comment.author, + }); + }); + + // 계층 구조 생성 + comments.forEach(comment => { + const commentWithChildren = commentMap.get(comment.id); + if (comment.parentCommentId) { + const parent = commentMap.get(comment.parentCommentId); + if (parent) { + parent.children.push(commentWithChildren); + } + } else { + rootComments.push(commentWithChildren); + } + }); + + return rootComments; + }); + } catch (error) { + console.error("댓글 조회 실패:", error); + return []; + } + }, + [`comments-${answerId}`], + { + revalidate: 1800, // 30분 캐싱 + tags: ["qna", `comments-${answerId}`], + } + )(); +} + +/* ================================================================ + 7) 통계 및 메타 정보 조회 +================================================================ */ + +/** + * Q&A 대시보드 통계 조회 + */ +export async function getQnaStats() { + return unstable_cache( + async () => { + try { + // 뷰를 사용하여 간단하게 통계 조회 + const [stats] = await db + .select({ + totalQuestions: count(), + answeredQuestions: sql`COUNT(CASE WHEN ${qnaView.hasAnswers} = true THEN 1 END)`, + unansweredQuestions: sql`COUNT(CASE WHEN ${qnaView.hasAnswers} = false THEN 1 END)`, + popularQuestions: sql`COUNT(CASE WHEN ${qnaView.isPopular} = true THEN 1 END)`, + totalAnswers: sql`SUM(${qnaView.totalAnswers})`, + totalComments: sql`SUM(${qnaView.totalComments})`, + }) + .from(qnaView); + + // 최근 활동 통계 + const [recentStats] = await db + .select({ + questionsThisWeek: sql`COUNT(CASE WHEN ${qnaView.createdAt} >= NOW() - INTERVAL '7 days' THEN 1 END)`, + questionsThisMonth: sql`COUNT(CASE WHEN ${qnaView.createdAt} >= NOW() - INTERVAL '30 days' THEN 1 END)`, + activeQuestionsThisWeek: sql`COUNT(CASE WHEN ${qnaView.lastActivityAt} >= NOW() - INTERVAL '7 days' THEN 1 END)`, + }) + .from(qnaView); + + return { + ...stats, + ...recentStats, + // 추가 계산 통계 + answerRate: stats.totalQuestions > 0 + ? Math.round((stats.answeredQuestions / stats.totalQuestions) * 100) + : 0, + avgAnswersPerQuestion: stats.totalQuestions > 0 + ? Math.round((stats.totalAnswers || 0) / stats.totalQuestions * 100) / 100 + : 0, + }; + } catch (err) { + console.error("Q&A 통계 조회 실패:", err); + return { + totalQuestions: 0, + answeredQuestions: 0, + unansweredQuestions: 0, + popularQuestions: 0, + totalAnswers: 0, + totalComments: 0, + questionsThisWeek: 0, + questionsThisMonth: 0, + activeQuestionsThisWeek: 0, + answerRate: 0, + avgAnswersPerQuestion: 0, + }; + } + }, + ["qna-stats"], + { + revalidate: 3600, // 1시간 캐싱 + tags: ["qna", "qna-stats"], + } + )(); +} + +/** + * 사용자별 Q&A 활동 통계 + */ +export async function getMyQnaActivity() { + try { + const userId = await getAuthenticatedUser(); + + return unstable_cache( + async () => { + const [myStats] = await db + .select({ + myQuestions: count(), + myAnsweredQuestions: sql`COUNT(CASE WHEN ${qnaView.hasAnswers} = true THEN 1 END)`, + }) + .from(qnaView) + .where(eq(qnaView.author, userId)); + + const [myAnswers] = await db + .select({ + totalAnswers: count(), + }) + .from(qnaAnswerView) + .where(eq(qnaAnswerView.author, userId)); + + const [myComments] = await db + .select({ + totalComments: count(), + }) + .from(qnaCommentView) + .where(eq(qnaCommentView.author, userId)); + + return { + ...myStats, + ...myAnswers, + ...myComments, + }; + }, + [`my-qna-activity-${userId}`], + { + revalidate: 1800, // 30분 캐싱 + tags: ["qna", `user-activity-${userId}`], + } + )(); + } catch (err) { + return { + myQuestions: 0, + myAnsweredQuestions: 0, + totalAnswers: 0, + totalComments: 0, + }; + } +} \ No newline at end of file diff --git a/lib/qna/table/create-qna-dialog.tsx b/lib/qna/table/create-qna-dialog.tsx new file mode 100644 index 00000000..d5af932b --- /dev/null +++ b/lib/qna/table/create-qna-dialog.tsx @@ -0,0 +1,203 @@ +"use client" + +import * as React from "react" +import { zodResolver } from "@hookform/resolvers/zod" +import { useForm } from "react-hook-form" +import { toast } from "sonner" + +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form" +import { Input } from "@/components/ui/input" +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select" + +import { createQnaSchema, type CreateQnaSchema } from "@/lib/qna/validation" +import { createQna } from "../service" +import { QNA_CATEGORY_LABELS } from "@/db/schema" +import TiptapEditor from "@/components/qna/tiptap-editor" + +interface CreateQnaDialogProps { + open: boolean + onOpenChange: (open: boolean) => void +} + +export function CreateQnaDialog({ open, onOpenChange }: CreateQnaDialogProps) { + const [isCreatePending, startCreateTransition] = React.useTransition() + + const form = useForm({ + resolver: zodResolver(createQnaSchema), + defaultValues: { + title: "", + content: "", + category: undefined, + }, + }) + + function onSubmit(input: CreateQnaSchema) { + startCreateTransition(async () => { + try { + const result = await createQna(input) + + if (result.success) { + toast.success(result.message || "질문이 성공적으로 등록되었습니다.") + form.reset() + onOpenChange(false) + } else { + toast.error(result.error || "질문 등록에 실패했습니다.") + } + } catch (error) { + toast.error("예기치 못한 오류가 발생했습니다.") + console.error("질문 생성 오류:", error) + } + }) + } + + // 다이얼로그가 닫힐 때 폼 리셋 + React.useEffect(() => { + if (!open) { + form.reset() + } + }, [open, form]) + + + console.log(form.getValues(),"생성") + + return ( + + + + 새 질문 작성 + + 질문의 제목과 내용을 입력해주세요. 다른 사용자들이 이해하기 쉽도록 구체적으로 작성해주세요. + + + + {/* 폼 영역: flex-1으로 남은 공간 모두 사용 */} +
+
+ + {/* 카테고리와 제목은 스크롤 없이 고정 */} +
+ {/* 카테고리 선택 */} + ( + + 카테고리 * + + + + )} + /> + + {/* 제목 입력 */} + ( + + 제목 * + + + + + + )} + /> +
+ + {/* 내용 입력 영역: 고정 높이로 스크롤 생성 */} + ( + + 내용 * + + {/* 고정 높이 400px로 설정하여 스크롤 보장 */} +
+ +
+
+ +
+ • 문제 상황을 구체적으로 설명해주세요
+ • 이미지 복사&붙여넣기, 드래그&드롭 지원
+ • 예상하는 결과와 실제 결과를 명시해주세요 +
+
+ )} + /> + + +
+ + + + + +
+
+ ) +} \ No newline at end of file diff --git a/lib/qna/table/delete-qna-dialog.tsx b/lib/qna/table/delete-qna-dialog.tsx new file mode 100644 index 00000000..55dcd366 --- /dev/null +++ b/lib/qna/table/delete-qna-dialog.tsx @@ -0,0 +1,250 @@ +"use client" + +import * as React from "react" +import { toast } from "sonner" +import { Trash2 } from "lucide-react" + +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog" +import { + Drawer, + DrawerContent, + DrawerDescription, + DrawerFooter, + DrawerHeader, + DrawerTitle, + DrawerTrigger, +} from "@/components/ui/drawer" +import { Badge } from "@/components/ui/badge" +import { ScrollArea } from "@/components/ui/scroll-area" + +import { QnaViewSelect } from "@/db/schema" +import { useMediaQuery } from "@/hooks/use-media-query" +import { deleteQna } from "../service" + +interface DeleteQnaDialogProps { + open: boolean + onOpenChange: (open: boolean) => void + qnas: QnaViewSelect[] + showTrigger?: boolean + onSuccess?: () => void +} + +export function DeleteQnaDialog({ + open, + onOpenChange, + qnas, + showTrigger = true, + onSuccess +}: DeleteQnaDialogProps) { + const [isDeletePending, startDeleteTransition] = React.useTransition() + const isDesktop = useMediaQuery("(min-width: 640px)") + + const qnaCount = qnas.length + const isMultiple = qnaCount > 1 + + async function handleDelete() { + startDeleteTransition(async () => { + try { + const promises = qnas.map(qna => deleteQna(qna.id)) + const results = await Promise.all(promises) + + const successCount = results.filter(result => result.success).length + const failCount = results.length - successCount + + if (successCount > 0) { + toast.success( + isMultiple + ? `${successCount}개의 질문이 삭제되었습니다.` + : "질문이 삭제되었습니다." + ) + onSuccess?.() + } + + if (failCount > 0) { + toast.error( + isMultiple + ? `${failCount}개의 질문 삭제에 실패했습니다.` + : "질문 삭제에 실패했습니다." + ) + } + + if (successCount > 0) { + onOpenChange(false) + } + } catch (error) { + toast.error("삭제 중 오류가 발생했습니다.") + console.error("질문 삭제 오류:", error) + } + }) + } + + const title = isMultiple ? `${qnaCount}개 질문 삭제` : "질문 삭제" + const description = isMultiple + ? "선택한 질문들을 정말로 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다." + : "이 질문을 정말로 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다." + + if (isDesktop) { + return ( + + {showTrigger && ( + + + + )} + + + {title} + {description} + + + {/* 삭제할 질문 목록 */} +
+
삭제 대상:
+ +
+ {qnas.map((qna, index) => ( +
+
+ {index + 1}. +
+
+
+ {qna.title} +
+
+ {qna.authorName} + + {qna.companyName || "미지정"} + + 답변 {qna.totalAnswers}개 +
+
+ {qna.hasAnswers && ( + + 답변있음 + + )} + {qna.isPopular && ( + + 인기질문 + + )} +
+
+
+ ))} +
+
+
+ + {/* 경고 메시지 */} +
+
+ 주의: 질문을 삭제하면 해당 질문의 모든 답변과 댓글도 함께 삭제됩니다. +
+
+ + + + + +
+
+ ) + } + + return ( + + {showTrigger && ( + + + + )} + + + {title} + {description} + + +
+ {/* 삭제할 질문 목록 */} +
+
삭제 대상:
+
+ {qnas.map((qna, index) => ( +
+
+ {index + 1}. +
+
+
+ {qna.title} +
+
+ {qna.authorName} • 답변 {qna.totalAnswers}개 +
+
+
+ ))} +
+
+ + {/* 경고 메시지 */} +
+
+ 주의: 삭제된 질문과 관련 데이터는 복구할 수 없습니다. +
+
+
+ + + + + +
+
+ ) +} \ No newline at end of file diff --git a/lib/qna/table/improved-comment-section.tsx b/lib/qna/table/improved-comment-section.tsx new file mode 100644 index 00000000..ce32b706 --- /dev/null +++ b/lib/qna/table/improved-comment-section.tsx @@ -0,0 +1,319 @@ +import * as React from "react"; +import { useSession } from "next-auth/react"; +import { Button } from "@/components/ui/button"; +import { Textarea } from "@/components/ui/textarea"; +import { Badge } from "@/components/ui/badge"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { format } from "date-fns"; +import { Comment } from "@/lib/qna/types"; +import { + MessageCircle, + Trash2, + Edit, + Check, + X, + User, + Plus +} from "lucide-react"; + +interface ImprovedCommentSectionProps { + answerId: string | number; + comments: Comment[]; + onAddComment: (content: string) => Promise; + onDeleteComment: (commentId: string | number) => Promise; + onUpdateComment?: (commentId: string | number, content: string) => Promise; +} + +export function ImprovedCommentSection({ + answerId, + comments, + onAddComment, + onDeleteComment, + onUpdateComment +}: ImprovedCommentSectionProps) { + const { data: session } = useSession(); + + // 상태 관리 + const [content, setContent] = React.useState(""); + const [isSubmitting, setIsSubmitting] = React.useState(false); + const [editingId, setEditingId] = React.useState(null); + const [editContent, setEditContent] = React.useState(""); + const [showCommentForm, setShowCommentForm] = React.useState(false); + + // 댓글 작성 + const handleSubmit = async () => { + if (!content.trim() || !session?.user) return; + + setIsSubmitting(true); + try { + await onAddComment(content); + setContent(""); + setShowCommentForm(false); + } catch (error) { + console.error("댓글 작성 실패:", error); + } finally { + setIsSubmitting(false); + } + }; + + // 댓글 수정 시작 + const handleEditStart = (comment: Comment) => { + setEditingId(comment.id); + setEditContent(comment.content); + }; + + // 댓글 수정 취소 + const handleEditCancel = () => { + setEditingId(null); + setEditContent(""); + }; + + // 댓글 수정 저장 + const handleEditSave = async (commentId: string | number) => { + if (!editContent.trim() || !onUpdateComment) return; + + try { + await onUpdateComment(commentId, editContent); + setEditingId(null); + setEditContent(""); + } catch (error) { + console.error("댓글 수정 실패:", error); + } + }; + + return ( +
+ {/* 헤더 */} +
+
+ + + 댓글 + + {comments.length > 0 && ( + + {comments.length} + + )} +
+ + {session?.user && !showCommentForm && ( + + )} +
+ + {/* 댓글 목록 */} + {comments.length > 0 && ( +
+ {comments.map((comment) => ( +
+
+ {/* 아바타 */} + + + + + + + + {/* 댓글 내용 */} +
+
+ {/* 작성자 정보 */} +
+ + {comment.authorName || comment.author} + + + {format(new Date(comment.createdAt), "MM월 dd일 HH:mm")} + +
+ + {/* 댓글 텍스트 */} + {editingId === comment.id ? ( +
+