(userId: string)
| 619 | * Sync usage limits based on subscription changes |
| 620 | */ |
| 621 | export async function syncUsageLimitsFromSubscription(userId: string): Promise<void> { |
| 622 | const [subscription, currentUserStats] = await Promise.all([ |
| 623 | getHighestPrioritySubscription(userId), |
| 624 | db.select().from(userStats).where(eq(userStats.userId, userId)).limit(1), |
| 625 | ]) |
| 626 | |
| 627 | if (currentUserStats.length === 0) { |
| 628 | throw new Error(`User stats not found for userId: ${userId}`) |
| 629 | } |
| 630 | |
| 631 | const currentStats = currentUserStats[0] |
| 632 | |
| 633 | if (isOrgScopedSubscription(subscription, userId)) { |
| 634 | if (currentStats.currentUsageLimit !== null) { |
| 635 | await db |
| 636 | .update(userStats) |
| 637 | .set({ |
| 638 | currentUsageLimit: null, |
| 639 | usageLimitUpdatedAt: new Date(), |
| 640 | }) |
| 641 | .where(eq(userStats.userId, userId)) |
| 642 | |
| 643 | logger.info('Cleared individual limit for org-scoped member', { |
| 644 | userId, |
| 645 | plan: subscription?.plan, |
| 646 | }) |
| 647 | } |
| 648 | return |
| 649 | } |
| 650 | const defaultLimit = getPerUserMinimumLimit(subscription) |
| 651 | const currentLimit = currentStats.currentUsageLimit |
| 652 | ? toNumber(toDecimal(currentStats.currentUsageLimit)) |
| 653 | : 0 |
| 654 | |
| 655 | if (!subscription || !hasPaidSubscriptionStatus(subscription.status)) { |
| 656 | // Downgraded to free |
| 657 | await db |
| 658 | .update(userStats) |
| 659 | .set({ |
| 660 | currentUsageLimit: getFreeTierLimit().toString(), |
| 661 | usageLimitUpdatedAt: new Date(), |
| 662 | }) |
| 663 | .where(eq(userStats.userId, userId)) |
| 664 | |
| 665 | logger.info('Set limit to free tier', { userId }) |
| 666 | } else if (currentLimit < defaultLimit) { |
| 667 | await db |
| 668 | .update(userStats) |
| 669 | .set({ |
| 670 | currentUsageLimit: defaultLimit.toString(), |
| 671 | usageLimitUpdatedAt: new Date(), |
| 672 | }) |
| 673 | .where(eq(userStats.userId, userId)) |
| 674 | |
| 675 | logger.info('Raised limit to plan minimum', { |
| 676 | userId, |
| 677 | newLimit: defaultLimit, |
| 678 | }) |
no test coverage detected