-
Notifications
You must be signed in to change notification settings - Fork 4
/
askQuestions.ts
118 lines (99 loc) · 3.33 KB
/
askQuestions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//actions/askQuestions.ts
"use server";
import { adminDb } from "@/firebaseAdmin";
// Define limits for users based on their plan type
const PRO_LIMIT = 500;
const FREE_LIMIT = 50;
// Function to handle storing questions and answers
export async function askQuestion({
userId,
question,
}: {
userId: string;
question: string;
}) {
const generatedContentRef = adminDb
.collection("users")
.doc(userId)
.collection("generatedContent");
// Fetch all previously asked questions by the user
const snapshot = await generatedContentRef.get();
const userMessages = snapshot.docs.map((doc) => doc.data());
// Check user limits based on their plan type
const userRef = await adminDb.collection("users").doc(userId).get();
const userData = userRef.data();
if (!userData) {
return {
success: false,
message: "User data not found. Please try again.",
};
}
const { hasActiveMembership, isEnterprise } = userData;
// Free plan limit check
if (!hasActiveMembership && userMessages.length >= FREE_LIMIT) {
return {
success: false,
message: `You'll need to upgrade to PRO or Enterprise to ask more than ${FREE_LIMIT} questions! 😢`,
};
}
// PRO plan limit check
if (hasActiveMembership && !isEnterprise && userMessages.length >= PRO_LIMIT) {
return {
success: false,
message: `You've reached the PRO limit of ${PRO_LIMIT} questions! 😢 Upgrade to Enterprise for unlimited access.`,
};
}
// No limit for Enterprise users
if (isEnterprise) {
// Enterprise users can proceed without any limit check
}
// Call the API to generate the response from Google Gemini
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt: question,
}),
});
const data = await response.json();
if (!response.ok || !data.generatedContent) {
return {
success: false,
message: "Error generating AI content.",
};
}
// Save the question and response to generatedContent
await generatedContentRef.add({
question,
response: data.generatedContent,
createdAt: new Date(),
});
return { success: true, message: data.generatedContent };
}
// Function to fetch previously generated content
export async function fetchGeneratedContent(userId: string) {
try {
const generatedContentRef = adminDb
.collection("users")
.doc(userId)
.collection("generatedContent");
const snapshot = await generatedContentRef.orderBy("createdAt", "desc").get();
if (snapshot.empty) {
console.log("No previously generated content found.");
return [];
}
// Ensure serializable data by mapping Firestore documents to plain JavaScript objects
const generatedContent = snapshot.docs.map((doc) => ({
id: doc.id, // Firestore document ID
question: doc.data().question || "", // The question asked
response: doc.data().response || "", // The AI-generated response
createdAt: doc.data().createdAt.toMillis(), // Convert Firestore Timestamp to milliseconds
}));
return generatedContent;
} catch (error) {
console.error("Error fetching previously generated content:", error);
throw new Error("Unable to fetch previously generated content.");
}
}