fix: Dynamic credit initialization from subscription plan
- Removed hardcoded 100 credits from lazy initialization - Now looks up user's subscription plan and uses monthly_credits - Set total_purchased to 0 (previously incorrectly set to 100) - Fallback to 10 credits if no plan found (starter default)
This commit is contained in:
@@ -53,14 +53,30 @@ export async function getUserCredits(userId: string): Promise<UserCredits | null
|
|||||||
.single();
|
.single();
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
// If user doesn't have credits yet, create entry with default values
|
// If user doesn't have credits yet, create entry based on their subscription plan
|
||||||
if (error.code === 'PGRST116') {
|
if (error.code === 'PGRST116') {
|
||||||
|
// Get user's subscription plan credits
|
||||||
|
const { data: subscription } = await supabase
|
||||||
|
.from('user_subscriptions')
|
||||||
|
.select(`
|
||||||
|
subscription_plans (
|
||||||
|
monthly_credits
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
.eq('user_id', userId)
|
||||||
|
.single();
|
||||||
|
|
||||||
|
// Extract monthly_credits from plan (default to 10 for starter)
|
||||||
|
const planData = subscription?.subscription_plans;
|
||||||
|
const plan = Array.isArray(planData) ? planData[0] : planData;
|
||||||
|
const startingCredits = plan?.monthly_credits ?? 10;
|
||||||
|
|
||||||
const { data: newCredits, error: insertError } = await supabase
|
const { data: newCredits, error: insertError } = await supabase
|
||||||
.from('user_credits')
|
.from('user_credits')
|
||||||
.insert({
|
.insert({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
balance: 100, // Starting credits
|
balance: startingCredits,
|
||||||
total_purchased: 100,
|
total_purchased: 0,
|
||||||
total_used: 0
|
total_used: 0
|
||||||
})
|
})
|
||||||
.select()
|
.select()
|
||||||
@@ -71,6 +87,7 @@ export async function getUserCredits(userId: string): Promise<UserCredits | null
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(`[Credits] Created credits for user with ${startingCredits} balance from plan`);
|
||||||
return newCredits;
|
return newCredits;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user