|
| 1 | +import { type NextRequest, NextResponse } from 'next/server' |
| 2 | +import { z } from 'zod' |
| 3 | +import { |
| 4 | + authenticateCopilotRequestSessionOnly, |
| 5 | + createBadRequestResponse, |
| 6 | + createInternalServerErrorResponse, |
| 7 | + createRequestTracker, |
| 8 | + createUnauthorizedResponse, |
| 9 | +} from '@/lib/copilot/auth' |
| 10 | +import { createLogger } from '@/lib/logs/console/logger' |
| 11 | +import { db } from '@/db' |
| 12 | +import { copilotFeedback } from '@/db/schema' |
| 13 | + |
| 14 | +const logger = createLogger('CopilotFeedbackAPI') |
| 15 | + |
| 16 | +// Schema for feedback submission |
| 17 | +const FeedbackSchema = z.object({ |
| 18 | + chatId: z.string().uuid('Chat ID must be a valid UUID'), |
| 19 | + userQuery: z.string().min(1, 'User query is required'), |
| 20 | + agentResponse: z.string().min(1, 'Agent response is required'), |
| 21 | + isPositiveFeedback: z.boolean(), |
| 22 | + feedback: z.string().optional(), |
| 23 | + workflowYaml: z.string().optional(), // Optional workflow YAML when edit/build workflow tools were used |
| 24 | +}) |
| 25 | + |
| 26 | +/** |
| 27 | + * POST /api/copilot/feedback |
| 28 | + * Submit feedback for a copilot interaction |
| 29 | + */ |
| 30 | +export async function POST(req: NextRequest) { |
| 31 | + const tracker = createRequestTracker() |
| 32 | + |
| 33 | + try { |
| 34 | + // Authenticate user using the same pattern as other copilot routes |
| 35 | + const { userId: authenticatedUserId, isAuthenticated } = |
| 36 | + await authenticateCopilotRequestSessionOnly() |
| 37 | + |
| 38 | + if (!isAuthenticated || !authenticatedUserId) { |
| 39 | + return createUnauthorizedResponse() |
| 40 | + } |
| 41 | + |
| 42 | + const body = await req.json() |
| 43 | + const { chatId, userQuery, agentResponse, isPositiveFeedback, feedback, workflowYaml } = |
| 44 | + FeedbackSchema.parse(body) |
| 45 | + |
| 46 | + logger.info(`[${tracker.requestId}] Processing copilot feedback submission`, { |
| 47 | + userId: authenticatedUserId, |
| 48 | + chatId, |
| 49 | + isPositiveFeedback, |
| 50 | + userQueryLength: userQuery.length, |
| 51 | + agentResponseLength: agentResponse.length, |
| 52 | + hasFeedback: !!feedback, |
| 53 | + hasWorkflowYaml: !!workflowYaml, |
| 54 | + workflowYamlLength: workflowYaml?.length || 0, |
| 55 | + }) |
| 56 | + |
| 57 | + // Insert feedback into the database |
| 58 | + const [feedbackRecord] = await db |
| 59 | + .insert(copilotFeedback) |
| 60 | + .values({ |
| 61 | + userId: authenticatedUserId, |
| 62 | + chatId, |
| 63 | + userQuery, |
| 64 | + agentResponse, |
| 65 | + isPositive: isPositiveFeedback, |
| 66 | + feedback: feedback || null, |
| 67 | + workflowYaml: workflowYaml || null, |
| 68 | + }) |
| 69 | + .returning() |
| 70 | + |
| 71 | + logger.info(`[${tracker.requestId}] Successfully saved copilot feedback`, { |
| 72 | + feedbackId: feedbackRecord.feedbackId, |
| 73 | + userId: authenticatedUserId, |
| 74 | + isPositive: isPositiveFeedback, |
| 75 | + duration: tracker.getDuration(), |
| 76 | + }) |
| 77 | + |
| 78 | + return NextResponse.json({ |
| 79 | + success: true, |
| 80 | + feedbackId: feedbackRecord.feedbackId, |
| 81 | + message: 'Feedback submitted successfully', |
| 82 | + metadata: { |
| 83 | + requestId: tracker.requestId, |
| 84 | + duration: tracker.getDuration(), |
| 85 | + }, |
| 86 | + }) |
| 87 | + } catch (error) { |
| 88 | + const duration = tracker.getDuration() |
| 89 | + |
| 90 | + if (error instanceof z.ZodError) { |
| 91 | + logger.error(`[${tracker.requestId}] Validation error:`, { |
| 92 | + duration, |
| 93 | + errors: error.errors, |
| 94 | + }) |
| 95 | + return createBadRequestResponse( |
| 96 | + `Invalid request data: ${error.errors.map((e) => e.message).join(', ')}` |
| 97 | + ) |
| 98 | + } |
| 99 | + |
| 100 | + logger.error(`[${tracker.requestId}] Error submitting copilot feedback:`, { |
| 101 | + duration, |
| 102 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 103 | + stack: error instanceof Error ? error.stack : undefined, |
| 104 | + }) |
| 105 | + |
| 106 | + return createInternalServerErrorResponse('Failed to submit feedback') |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * GET /api/copilot/feedback |
| 112 | + * Get all feedback records (for analytics) |
| 113 | + */ |
| 114 | +export async function GET(req: NextRequest) { |
| 115 | + const tracker = createRequestTracker() |
| 116 | + |
| 117 | + try { |
| 118 | + // Authenticate user |
| 119 | + const { userId: authenticatedUserId, isAuthenticated } = |
| 120 | + await authenticateCopilotRequestSessionOnly() |
| 121 | + |
| 122 | + if (!isAuthenticated || !authenticatedUserId) { |
| 123 | + return createUnauthorizedResponse() |
| 124 | + } |
| 125 | + |
| 126 | + // Get all feedback records |
| 127 | + const feedbackRecords = await db |
| 128 | + .select({ |
| 129 | + feedbackId: copilotFeedback.feedbackId, |
| 130 | + userId: copilotFeedback.userId, |
| 131 | + chatId: copilotFeedback.chatId, |
| 132 | + userQuery: copilotFeedback.userQuery, |
| 133 | + agentResponse: copilotFeedback.agentResponse, |
| 134 | + isPositive: copilotFeedback.isPositive, |
| 135 | + feedback: copilotFeedback.feedback, |
| 136 | + workflowYaml: copilotFeedback.workflowYaml, |
| 137 | + createdAt: copilotFeedback.createdAt, |
| 138 | + }) |
| 139 | + .from(copilotFeedback) |
| 140 | + |
| 141 | + logger.info(`[${tracker.requestId}] Retrieved ${feedbackRecords.length} feedback records`) |
| 142 | + |
| 143 | + return NextResponse.json({ |
| 144 | + success: true, |
| 145 | + feedback: feedbackRecords, |
| 146 | + metadata: { |
| 147 | + requestId: tracker.requestId, |
| 148 | + duration: tracker.getDuration(), |
| 149 | + }, |
| 150 | + }) |
| 151 | + } catch (error) { |
| 152 | + logger.error(`[${tracker.requestId}] Error retrieving copilot feedback:`, error) |
| 153 | + return createInternalServerErrorResponse('Failed to retrieve feedback') |
| 154 | + } |
| 155 | +} |
0 commit comments