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;
const { data: creditUsages, error: creditUsageError } = await supabase_service try {
.from("credit_usage") const { data: creditUsages, error: creditUsageError } = await supabase_service
.select("credits_used") .rpc("get_credit_usage_2", {
.eq("subscription_id", subscription.id) sub_id: subscription.id,
.gte("created_at", subscription.current_period_start) start_time: subscription.current_period_start,
.lte("created_at", subscription.current_period_end); end_time: 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);
}
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);
} }
const totalCreditsUsed = creditUsages.reduce((acc, usage) => acc + usage.credits_used, 0);
// 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);