|
| 1 | +'use server'; |
| 2 | + |
| 3 | +import { authActionClient } from '@/actions/safe-action'; |
| 4 | +import { answerQuestion } from '@/trigger/tasks/vendors/answer-question'; |
| 5 | +import { revalidatePath } from 'next/cache'; |
| 6 | +import { headers } from 'next/headers'; |
| 7 | +import { z } from 'zod'; |
| 8 | + |
| 9 | +const inputSchema = z.object({ |
| 10 | + question: z.string(), |
| 11 | + questionIndex: z.number(), |
| 12 | + totalQuestions: z.number(), |
| 13 | +}); |
| 14 | + |
| 15 | +export const answerSingleQuestionAction = authActionClient |
| 16 | + .inputSchema(inputSchema) |
| 17 | + .metadata({ |
| 18 | + name: 'answer-single-question', |
| 19 | + track: { |
| 20 | + event: 'answer-single-question', |
| 21 | + channel: 'server', |
| 22 | + }, |
| 23 | + }) |
| 24 | + .action(async ({ parsedInput, ctx }) => { |
| 25 | + const { question, questionIndex, totalQuestions } = parsedInput; |
| 26 | + const { session } = ctx; |
| 27 | + |
| 28 | + if (!session?.activeOrganizationId) { |
| 29 | + throw new Error('No active organization'); |
| 30 | + } |
| 31 | + |
| 32 | + const organizationId = session.activeOrganizationId; |
| 33 | + |
| 34 | + try { |
| 35 | + // Call answerQuestion function directly |
| 36 | + const result = await answerQuestion( |
| 37 | + { |
| 38 | + question, |
| 39 | + organizationId, |
| 40 | + questionIndex, |
| 41 | + totalQuestions, |
| 42 | + }, |
| 43 | + { |
| 44 | + useMetadata: false, |
| 45 | + }, |
| 46 | + ); |
| 47 | + |
| 48 | + // Revalidate the page to show updated answer |
| 49 | + const headersList = await headers(); |
| 50 | + let path = headersList.get('x-pathname') || headersList.get('referer') || ''; |
| 51 | + path = path.replace(/\/[a-z]{2}\//, '/'); |
| 52 | + revalidatePath(path); |
| 53 | + |
| 54 | + return { |
| 55 | + success: result.success, |
| 56 | + data: { |
| 57 | + questionIndex: result.questionIndex, |
| 58 | + question: result.question, |
| 59 | + answer: result.answer, |
| 60 | + sources: result.sources, |
| 61 | + error: result.error, |
| 62 | + }, |
| 63 | + }; |
| 64 | + } catch (error) { |
| 65 | + return { |
| 66 | + success: false, |
| 67 | + error: error instanceof Error ? error.message : 'Failed to answer question', |
| 68 | + }; |
| 69 | + } |
| 70 | + }); |
0 commit comments