Repository navigation
fix(credits): apply a due monthly refill at the gate before denying #839
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| import { selectCreditsUsage } from "@/lib/supabase/credits_usage/selectCreditsUsage"; | ||
| import { checkAndResetCredits } from "@/lib/credits/checkAndResetCredits"; | ||
|
|
||
| export type CheckCreditsAvailableParams = { | ||
| accountId: string; | ||
|
|
@@ -18,6 +19,12 @@ export type CheckCreditsAvailableResult = | |
| * covers `creditsToDeduct`. It reads, and does nothing else: no charge, and no | ||
| * Stripe object created as a side effect of a failed authorization. | ||
| * | ||
| * A sufficient balance is decided on a single read. On a shortfall, a monthly | ||
| * refill may be due but unapplied (the refill normally runs from the balance | ||
| * GET), so the gate applies it via `checkAndResetCredits` and re-evaluates | ||
| * before denying. The refill is a floor, so it can only raise the balance — | ||
| * which is why the happy path can skip it safely. | ||
| * | ||
| * Does **not** deduct either; that stays with the caller, so the existing | ||
| * pattern of "do the work first, deduct on success" survives. | ||
| * | ||
|
|
@@ -35,9 +42,14 @@ export async function checkCreditsAvailable( | |
|
|
||
| if (remaining >= creditsToDeduct) return { kind: "available" }; | ||
|
|
||
| const { creditsUsage } = await checkAndResetCredits(accountId); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: On a shortfall, the gate now calls Prompt for AI agents |
||
| const refreshed = creditsUsage?.remaining_credits ?? 0; | ||
|
|
||
| if (refreshed >= creditsToDeduct) return { kind: "available" }; | ||
|
|
||
| return { | ||
| kind: "insufficient_credits", | ||
| remainingCredits: remaining, | ||
| remainingCredits: refreshed, | ||
| requiredCredits: creditsToDeduct, | ||
| }; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1: When concurrent requests hit a due, low balance, this call can apply the same monthly refill twice. Make the refill conditional or serialize it so only one caller can raise the balance before authorization.
Prompt for AI agents