MCPcopy Index your code
hub / github.com/CodebuffAI/codebuff / calculateUsageAndBalance

Function calculateUsageAndBalance

packages/billing/src/balance-calculator.ts:295–427  ·  view source on GitHub ↗
(
  params: OptionalFields<
    {
      userId: string
      quotaResetDate: Date
      now: Date
      conn: DbConn
      isPersonalContext: boolean
      includeSubscriptionCredits: boolean
      logger: Logger
    } & ParamsOf<typeof getOrderedActiveGrants>,
    'now' | 'conn' | 'isPersonalContext' | 'includeSubscriptionCredits'
  >,
)

Source from the content-addressed store, hash-verified

293 * This is more efficient than calculating them separately.
294 */
295export async function calculateUsageAndBalance(
296 params: OptionalFields<
297 {
298 userId: string
299 quotaResetDate: Date
300 now: Date
301 conn: DbConn
302 isPersonalContext: boolean
303 includeSubscriptionCredits: boolean
304 logger: Logger
305 } & ParamsOf<typeof getOrderedActiveGrants>,
306 'now' | 'conn' | 'isPersonalContext' | 'includeSubscriptionCredits'
307 >,
308): Promise<CreditUsageAndBalance> {
309 const withDefaults = {
310 now: new Date(),
311 conn: db, // Add optional conn parameter to pass transaction
312 isPersonalContext: false, // Add flag to exclude organization credits for personal usage
313 includeSubscriptionCredits: false,
314 ...params,
315 }
316 const {
317 userId,
318 quotaResetDate,
319 now,
320 isPersonalContext,
321 includeSubscriptionCredits,
322 logger,
323 } = withDefaults
324
325 // Get all relevant grants in one query, using the provided connection
326 const grants = await getOrderedActiveGrants(withDefaults)
327
328 // Initialize breakdown and principals with all grant types set to 0
329 const initialBreakdown: Record<GrantType, number> = {} as Record<
330 GrantType,
331 number
332 >
333 const initialPrincipals: Record<GrantType, number> = {} as Record<
334 GrantType,
335 number
336 >
337
338 for (const type of GrantTypeValues) {
339 initialBreakdown[type] = 0
340 initialPrincipals[type] = 0
341 }
342
343 // Initialize balance structure
344 const balance: CreditBalance = {
345 totalRemaining: 0,
346 totalDebt: 0,
347 netBalance: 0,
348 breakdown: initialBreakdown,
349 principals: initialPrincipals,
350 }
351
352 // Calculate both metrics in one pass

Callers 3

checkAndTriggerAutoTopupFunction · 0.90
getUserUsageDataFunction · 0.90

Calls 1

getOrderedActiveGrantsFunction · 0.85

Tested by

no test coverage detected