MCPcopy
hub / github.com/CodebuffAI/codebuff / revokeGrantByOperationId

Function revokeGrantByOperationId

packages/billing/src/grant-credits.ts:356–427  ·  view source on GitHub ↗
(params: {
  operationId: string
  reason: string
  logger: Logger
})

Source from the content-addressed store, hash-verified

354 * @returns true if the grant was found and revoked, false otherwise
355 */
356export async function revokeGrantByOperationId(params: {
357 operationId: string
358 reason: string
359 logger: Logger
360}): Promise<boolean> {
361 const { operationId, reason, logger } = params
362
363 // First, look up the grant to get the user_id for the advisory lock
364 const grant = await db.query.creditLedger.findFirst({
365 where: eq(schema.creditLedger.operation_id, operationId),
366 })
367
368 if (!grant) {
369 logger.warn({ operationId }, 'Attempted to revoke non-existent grant')
370 return false
371 }
372
373 // Determine lock key based on whether this is a user or org grant
374 const lockKey = grant.org_id ? `org:${grant.org_id}` : `user:${grant.user_id}`
375
376 const { result } = await withAdvisoryLockTransaction({
377 callback: async (tx) => {
378 // Re-fetch within transaction to get current state
379 const currentGrant = await tx.query.creditLedger.findFirst({
380 where: eq(schema.creditLedger.operation_id, operationId),
381 })
382
383 if (!currentGrant) {
384 logger.warn(
385 { operationId },
386 'Grant no longer exists after acquiring lock',
387 )
388 return false
389 }
390
391 if (currentGrant.balance < 0) {
392 logger.warn(
393 { operationId, currentBalance: currentGrant.balance },
394 'Cannot revoke grant with negative balance - user has already spent these credits',
395 )
396 return false
397 }
398
399 await tx
400 .update(schema.creditLedger)
401 .set({
402 principal: 0,
403 balance: 0,
404 description: `${currentGrant.description} (Revoked: ${reason})`,
405 })
406 .where(eq(schema.creditLedger.operation_id, operationId))
407
408 logger.info(
409 {
410 operationId,
411 userId: currentGrant.user_id,
412 orgId: currentGrant.org_id,
413 revokedAmount: currentGrant.balance,

Callers 1

webhookHandlerFunction · 0.90

Calls 2

setMethod · 0.80

Tested by

no test coverage detected