add client self-service ai activity plans on goals screen
This commit is contained in:
1 parent
0825bb3d65
commit
a65b3cac08
5 files changed
+426
-2
No files matched your search
@@ -0,0 +1,190 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { buildAIContext } from "@/lib/ai/ai-context";
|
||||
import { buildEnhancedPrompt, buildBasicPrompt } from "@/lib/ai/prompt-builder";
|
||||
import log from "@/lib/logger";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
import { getUserMembershipContext } from "@/lib/membership/access";
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
const { userId } = await auth();
|
||||
if (!userId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(userId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
if (currentUser.role !== "client") {
|
||||
return NextResponse.json(
|
||||
{ error: "Only clients can self-generate AI plans" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const { membershipType, features } = await getUserMembershipContext(userId);
|
||||
|
||||
if (membershipType === "basic") {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"AI plan generation is available on Premium and VIP memberships",
|
||||
membershipType,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
if (features.recommendationsPerMonth > 0) {
|
||||
const currentMonth = new Date();
|
||||
const monthStart = new Date(
|
||||
currentMonth.getFullYear(),
|
||||
currentMonth.getMonth(),
|
||||
1,
|
||||
);
|
||||
const monthEnd = new Date(
|
||||
currentMonth.getFullYear(),
|
||||
currentMonth.getMonth() + 1,
|
||||
1,
|
||||
);
|
||||
|
||||
const existingRecommendations =
|
||||
await db.getRecommendationsByUserId(userId);
|
||||
const recommendationsThisMonth = existingRecommendations.filter(
|
||||
(recommendation) =>
|
||||
recommendation.generatedAt >= monthStart &&
|
||||
recommendation.generatedAt < monthEnd,
|
||||
).length;
|
||||
|
||||
if (recommendationsThisMonth >= features.recommendationsPerMonth) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: `Your ${membershipType} plan includes ${features.recommendationsPerMonth} AI recommendation(s) per month`,
|
||||
membershipType,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const profile = await db.getFitnessProfileByUserId(userId);
|
||||
if (!profile) {
|
||||
return NextResponse.json(
|
||||
{ error: "Complete your fitness profile before generating a plan" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
let prompt: string;
|
||||
try {
|
||||
const context = await buildAIContext(userId);
|
||||
prompt = buildEnhancedPrompt(context);
|
||||
} catch (error) {
|
||||
log.warn("Failed to build AI context for self-generate", {
|
||||
userId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
prompt = buildBasicPrompt(profile);
|
||||
}
|
||||
|
||||
const openaiApiKey = process.env.OPENAI_API_KEY;
|
||||
if (!openaiApiKey) {
|
||||
return NextResponse.json(
|
||||
{ error: "AI provider unavailable. Try again later." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const openaiResponse = await fetch(
|
||||
"https://api.openai.com/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${openaiApiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "gpt-4o-mini",
|
||||
messages: [
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
'You are a professional fitness trainer and nutritionist. Always respond with valid JSON only, no markdown or code blocks. The response must have this exact structure: {"recommendationText": "string", "activityPlan": "string", "dietPlan": "string"}',
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: prompt,
|
||||
},
|
||||
],
|
||||
temperature: 0.7,
|
||||
max_tokens: 1500,
|
||||
response_format: { type: "json_object" },
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!openaiResponse.ok) {
|
||||
const errorText = await openaiResponse.text();
|
||||
log.error("OpenAI self-generate request failed", new Error(errorText), {
|
||||
userId,
|
||||
status: openaiResponse.status,
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to generate AI plan" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
const openaiData = await openaiResponse.json();
|
||||
|
||||
let parsedResponse: {
|
||||
recommendationText?: string;
|
||||
activityPlan?: string;
|
||||
dietPlan?: string;
|
||||
};
|
||||
|
||||
try {
|
||||
parsedResponse = JSON.parse(openaiData.choices[0].message.content);
|
||||
} catch (e) {
|
||||
log.error("Failed to parse self-generate OpenAI response", e, {
|
||||
userId,
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid response from AI provider" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
|
||||
const recommendation = await db.createRecommendation({
|
||||
id: crypto.randomUUID(),
|
||||
userId,
|
||||
fitnessProfileId: profile.id,
|
||||
recommendationText: parsedResponse.recommendationText || "",
|
||||
activityPlan: parsedResponse.activityPlan || "",
|
||||
dietPlan: parsedResponse.dietPlan || "",
|
||||
status: "approved",
|
||||
generatedAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: recommendation,
|
||||
meta: {
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
log.error("Failed to self-generate recommendation", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user