Skip to content

Commit 13e8fc0

Browse files
committed
Create a credit block when you send a message
1 parent 66edcaa commit 13e8fc0

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

web/src/app/api/v1/chat/completions/_post.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ import type {
1717
Logger,
1818
LoggerWithContextFn,
1919
} from '@codebuff/common/types/contracts/logger'
20+
21+
import type {
22+
BlockGrantResult,
23+
SubscriptionRow,
24+
} from '@codebuff/billing/subscription'
2025
import type { NextRequest } from 'next/server'
2126

2227
import type { ChatCompletionRequestBody } from '@/llm-api/types'
@@ -78,6 +83,8 @@ export async function postChatCompletions(params: {
7883
getAgentRunFromId: GetAgentRunFromIdFn
7984
fetch: typeof globalThis.fetch
8085
insertMessageBigquery: InsertMessageBigqueryFn
86+
getActiveSubscription?: (params: { userId: string; logger: Logger }) => Promise<SubscriptionRow | null>
87+
ensureActiveBlockGrant?: (params: { userId: string; subscription: SubscriptionRow; logger: Logger }) => Promise<BlockGrantResult>
8188
}) {
8289
const {
8390
req,
@@ -88,6 +95,8 @@ export async function postChatCompletions(params: {
8895
getAgentRunFromId,
8996
fetch,
9097
insertMessageBigquery,
98+
getActiveSubscription,
99+
ensureActiveBlockGrant,
91100
} = params
92101
let { logger } = params
93102

@@ -182,6 +191,22 @@ export async function postChatCompletions(params: {
182191
logger,
183192
})
184193

194+
// For subscribers, ensure a block grant exists before checking balance.
195+
// This is done here block grants should only start when the user begins working.
196+
if (getActiveSubscription && ensureActiveBlockGrant) {
197+
try {
198+
const activeSub = await getActiveSubscription({ userId, logger })
199+
if (activeSub) {
200+
await ensureActiveBlockGrant({ userId, subscription: activeSub, logger })
201+
}
202+
} catch (error) {
203+
logger.error(
204+
{ error: getErrorObject(error), userId },
205+
'Error ensuring subscription block grant',
206+
)
207+
}
208+
}
209+
185210
// Check user credits
186211
const {
187212
balance: { totalRemaining },

web/src/app/api/v1/chat/completions/route.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
import { insertMessageBigquery } from '@codebuff/bigquery'
2+
import {
3+
ensureActiveBlockGrant,
4+
getActiveSubscription,
5+
} from '@codebuff/billing/subscription'
26
import { getUserUsageData } from '@codebuff/billing/usage-service'
37
import { trackEvent } from '@codebuff/common/analytics'
48

@@ -21,5 +25,7 @@ export async function POST(req: NextRequest) {
2125
getAgentRunFromId,
2226
fetch,
2327
insertMessageBigquery,
28+
getActiveSubscription,
29+
ensureActiveBlockGrant,
2430
})
2531
}

0 commit comments

Comments
 (0)