Skip to main content

Documentation Index

Fetch the complete documentation index at: https://grantmaster.dev/llms.txt

Use this file to discover all available pages before exploring further.

Quota Service Reference

Source: src/shared/billing/QuotaService.ts
Enforces seat-based and feature-based quotas at the data layer. Prevents quota bypass by validating all create operations before writes. Architecture:
  • Called automatically by BaseService.validateQuota() before create operations
  • Emits QUOTA_EXCEEDED events for analytics and notification workflows
  • Emits QUOTA_WARNING events at 80% and 90% thresholds
  • Provides upgrade suggestions when quotas are exceeded
  • Tracks usage metrics in real-time

Quick Example

import { quotaService } from '@/shared/billing/QuotaService';

const quotaCheck = await quotaService.checkQuota({
  organizationId: 'org-123',
  resourceType: 'users',
  action: 'create',
  additionalCount: 1,
});

if (!quotaCheck.allowed) {
  // quotaCheck.reason contains user-friendly message
  // quotaCheck.suggestedTier contains next tier recommendation
  throw new BusinessLogicError(quotaCheck.reason);
}

Types

ResourceType

Billable resource categories tracked by the quota system. Each value maps to a corresponding field in Organization.usageMetrics and a limit defined per SubscriptionTier in TIER_LIMITS.
type ResourceType =
  | 'users'           // Team member seats
  | 'projects'        // Active projects
  | 'storage'         // Storage in GB
  | 'ai_generations'  // Gemini AI generations per month
  | 'agent_credits'   // Agent credits per month
  | 'agent_runs';     // Agent runs per month

QuotaCheckRequest

Input for quotaService.checkQuota().
FieldTypeRequiredDescription
organizationIdstringYesTenant isolation key
resourceTypeResourceTypeYesThe billable resource to check
action'create' | 'update'Yes'create' enforces limit; 'update' always passes
additionalCountnumberNoHow many new resources are being created (default: 1)

QuotaCheckResponse

Result returned by quotaService.checkQuota().
FieldTypeDescription
allowedbooleantrue if the requested action is within quota
reasonstring?Human-readable explanation when allowed is false
limitnumberMaximum allowed for this resource (or -1 for unlimited)
currentnumberCurrent usage count before the requested action
availablenumberRemaining capacity after the requested action (or -1 for unlimited)
requiresUpgradeboolean?true when the only way to proceed is to upgrade the subscription
suggestedTierSubscriptionTier?Next tier that would accommodate the request, if applicable
percentageUsednumberUsage as a percentage of the limit (0-100)

Methods

checkQuota()

Check if an organization can perform an action based on subscription quotas.
checkQuota(request: QuotaCheckRequest): Promise<QuotaCheckResponse>
Behavior:
  1. Fetches the organization document with subscription details
  2. Determines the resource limit from subscription.features or TIER_LIMITS
  3. Calculates available capacity
  4. For 'create' actions: validates additionalCount <= available
  5. For 'update' actions: always returns allowed: true
  6. Emits QUOTA_EXCEEDED event if denied
  7. Checks warning thresholds (80%, 90%) and emits QUOTA_WARNING if crossed
Throws: NotFoundError — If organization not found. Resource limit sources:
ResourceLimit SourceUsage Source
userssubscription.seats.total (or features.maxUsers)usageMetrics.activeUsers
projectsfeatures.maxProjectsusageMetrics.totalProjects
storagefeatures.storageGBusageMetrics.storageUsedGB
ai_generationsfeatures.aiGenerationsPerMonthusageMetrics.aiGenerationsThisMonth
agent_creditsfeatures.agentCreditsPerMonthusageMetrics.agentCreditsUsedThisMonth
agent_runsTIER_LIMITS[tier].maxAgentRunsPerMonthusageMetrics.agentRunsThisMonth

incrementUsage()

Increment usage counter after a successful operation. Non-blocking — failures are logged to Sentry but don’t break the operation.
incrementUsage(
  organizationId: string,
  resourceType: ResourceType,
  amount?: number
): Promise<void>
ParamTypeDescription
organizationIdstringOrganization ID
resourceTypeResourceTypeType of resource
amountnumberAmount to increment (default: 1)

decrementUsage()

Decrement usage counter (for deletions/deactivations). Non-blocking — failures are logged to Sentry but don’t break the operation.
decrementUsage(
  organizationId: string,
  resourceType: ResourceType,
  amount?: number
): Promise<void>
ParamTypeDescription
organizationIdstringOrganization ID
resourceTypeResourceTypeType of resource
amountnumberAmount to decrement (default: 1)

Warning Thresholds

The service emits QUOTA_WARNING events when usage crosses 80% or 90% of a resource limit. Warnings are emitted only once per threshold crossing (i.e., going from 79% to 80% triggers a warning, but 80% to 81% does not). Tier progression for upgrade suggestions:
  • POTENTIAL -> PROFESSIONAL
  • PROFESSIONAL -> ULTIMATE
  • ULTIMATE -> undefined (contact support for enterprise)

Singleton Export

import { quotaService } from '@/shared/billing/QuotaService';
The module exports a pre-instantiated QuotaService singleton using default logger, EventBus, and time provider.