0

Update credit_billing.ts

This commit is contained in:
Nicolas 2024-05-09 15:29:58 -07:00
parent 832a4f53e0
commit fce17e6beb

View File

@ -212,20 +212,26 @@ export async function supaCheckTeamCredits(team_id: string, credits: number) {
return { success: true, message: "Sufficient credits available" }; return { success: true, message: "Sufficient credits available" };
} }
// Calculate the total credits used by the team within the current billing period let totalCreditsUsed = 0;
try {
const { data: creditUsages, error: creditUsageError } = await supabase_service const { data: creditUsages, error: creditUsageError } = await supabase_service
.from("credit_usage") .rpc("get_credit_usage_2", {
.select("credits_used") sub_id: subscription.id,
.eq("subscription_id", subscription.id) start_time: subscription.current_period_start,
.gte("created_at", subscription.current_period_start) end_time: subscription.current_period_end
.lte("created_at", subscription.current_period_end); });
if (creditUsageError) { if (creditUsageError) {
throw new Error(`Failed to retrieve credit usage for subscription_id: ${subscription.id}`); console.error("Error calculating credit usage:", creditUsageError);
} }
const totalCreditsUsed = creditUsages.reduce((acc, usage) => acc + usage.credits_used, 0); if (creditUsages && creditUsages.length > 0) {
totalCreditsUsed = creditUsages[0].total_credits_used;
console.log("Total Credits Used:", totalCreditsUsed);
}
} catch (error) {
console.error("Error calculating credit usage:", error);
}
// Adjust total credits used by subtracting coupon value // Adjust total credits used by subtracting coupon value
const adjustedCreditsUsed = Math.max(0, totalCreditsUsed - couponCredits); const adjustedCreditsUsed = Math.max(0, totalCreditsUsed - couponCredits);