( userId: string, newLimit: number, setBy?: string // For team admin tracking )
| 428 | * Update a user's custom usage limit |
| 429 | */ |
| 430 | export async function updateUserUsageLimit( |
| 431 | userId: string, |
| 432 | newLimit: number, |
| 433 | setBy?: string // For team admin tracking |
| 434 | ): Promise<{ success: boolean; error?: string }> { |
| 435 | try { |
| 436 | const subscription = await getHighestPrioritySubscription(userId) |
| 437 | |
| 438 | if (isOrgScopedSubscription(subscription, userId)) { |
| 439 | return { |
| 440 | success: false, |
| 441 | error: |
| 442 | 'This subscription is managed at the organization level. Update the organization usage limit instead.', |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | // Only pro users can edit limits (free users cannot) |
| 447 | if (!subscription || isFree(subscription.plan)) { |
| 448 | return { success: false, error: 'Free plan users cannot edit usage limits' } |
| 449 | } |
| 450 | |
| 451 | const billingStatus = await getEffectiveBillingStatus(userId) |
| 452 | if (!hasUsableSubscriptionAccess(subscription.status, billingStatus.billingBlocked)) { |
| 453 | return { success: false, error: 'An active subscription is required to edit usage limits' } |
| 454 | } |
| 455 | |
| 456 | const minimumLimit = getPerUserMinimumLimit(subscription) |
| 457 | |
| 458 | logger.info('Applying plan-based validation', { |
| 459 | userId, |
| 460 | newLimit, |
| 461 | minimumLimit, |
| 462 | plan: subscription?.plan, |
| 463 | }) |
| 464 | |
| 465 | // Validate new limit is not below minimum |
| 466 | if (newLimit < minimumLimit) { |
| 467 | return { |
| 468 | success: false, |
| 469 | error: `Usage limit cannot be below plan minimum of $${minimumLimit}`, |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | await db |
| 474 | .update(userStats) |
| 475 | .set({ |
| 476 | currentUsageLimit: newLimit.toString(), |
| 477 | usageLimitUpdatedAt: new Date(), |
| 478 | }) |
| 479 | .where(eq(userStats.userId, userId)) |
| 480 | |
| 481 | logger.info('Updated user usage limit', { |
| 482 | userId, |
| 483 | newLimit, |
| 484 | setBy: setBy || userId, |
| 485 | planMinimum: minimumLimit, |
| 486 | plan: subscription?.plan, |
| 487 | }) |
no test coverage detected