| 20 | * This ensures users can use their plan's included amount plus any prepaid credits. |
| 21 | */ |
| 22 | export async function setUsageLimitForCredits( |
| 23 | entityType: 'user' | 'organization', |
| 24 | entityId: string, |
| 25 | plan: string, |
| 26 | seats: number | null, |
| 27 | creditBalance: number |
| 28 | ): Promise<void> { |
| 29 | try { |
| 30 | const { basePrice } = getPlanPricing(plan) |
| 31 | |
| 32 | const seatCount = seats || 1 |
| 33 | const planBase = |
| 34 | entityType === 'organization' ? Number(basePrice) * seatCount : Number(basePrice) |
| 35 | const creditBalanceNum = Number(creditBalance) |
| 36 | const newLimit = planBase + creditBalanceNum |
| 37 | |
| 38 | if (entityType === 'organization') { |
| 39 | const orgRows = await db |
| 40 | .select({ orgUsageLimit: organization.orgUsageLimit }) |
| 41 | .from(organization) |
| 42 | .where(eq(organization.id, entityId)) |
| 43 | .limit(1) |
| 44 | |
| 45 | const currentLimit = orgRows.length > 0 ? toNumber(toDecimal(orgRows[0].orgUsageLimit)) : 0 |
| 46 | |
| 47 | if (newLimit > currentLimit) { |
| 48 | await db |
| 49 | .update(organization) |
| 50 | .set({ orgUsageLimit: newLimit.toString() }) |
| 51 | .where(eq(organization.id, entityId)) |
| 52 | |
| 53 | logger.info('Set org usage limit to planBase + credits', { |
| 54 | organizationId: entityId, |
| 55 | plan, |
| 56 | seats, |
| 57 | planBase, |
| 58 | creditBalance, |
| 59 | previousLimit: currentLimit, |
| 60 | newLimit, |
| 61 | }) |
| 62 | } |
| 63 | } else { |
| 64 | const userStatsRows = await db |
| 65 | .select({ currentUsageLimit: userStats.currentUsageLimit }) |
| 66 | .from(userStats) |
| 67 | .where(eq(userStats.userId, entityId)) |
| 68 | .limit(1) |
| 69 | |
| 70 | const currentLimit = |
| 71 | userStatsRows.length > 0 ? toNumber(toDecimal(userStatsRows[0].currentUsageLimit)) : 0 |
| 72 | |
| 73 | if (newLimit > currentLimit) { |
| 74 | await db |
| 75 | .update(userStats) |
| 76 | .set({ currentUsageLimit: newLimit.toString() }) |
| 77 | .where(eq(userStats.userId, entityId)) |
| 78 | |
| 79 | logger.info('Set user usage limit to planBase + credits', { |