Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 70 additions & 7 deletions lib/credits/__tests__/checkCreditsAvailable.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { describe, it, expect, vi, beforeEach } from "vitest";

const { selectCreditsUsageMock, resolveStripeCustomerMock, createCreditsSessionMock } = vi.hoisted(
() => ({
selectCreditsUsageMock: vi.fn(),
resolveStripeCustomerMock: vi.fn(),
createCreditsSessionMock: vi.fn(),
}),
);
const {
selectCreditsUsageMock,
resolveStripeCustomerMock,
createCreditsSessionMock,
checkAndResetCreditsMock,
} = vi.hoisted(() => ({
selectCreditsUsageMock: vi.fn(),
resolveStripeCustomerMock: vi.fn(),
createCreditsSessionMock: vi.fn(),
checkAndResetCreditsMock: vi.fn(),
}));

vi.mock("@/lib/supabase/credits_usage/selectCreditsUsage", () => ({
selectCreditsUsage: selectCreditsUsageMock,
Expand All @@ -18,6 +22,9 @@ vi.mock("@/lib/stripe/resolveStripeCustomerForAccount", () => ({
vi.mock("@/lib/stripe/createCreditsStripeSession", () => ({
createCreditsStripeSession: createCreditsSessionMock,
}));
vi.mock("@/lib/credits/checkAndResetCredits", () => ({
checkAndResetCredits: checkAndResetCreditsMock,
}));

const { checkCreditsAvailable } = await import("@/lib/credits/checkCreditsAvailable");

Expand All @@ -26,6 +33,11 @@ const params = { accountId: "acct_123", creditsToDeduct: 5 };
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(console, "error").mockImplementation(() => undefined);
// Default: no refill due — the row comes back unchanged.
checkAndResetCreditsMock.mockImplementation(async () => ({
creditsUsage: { remaining_credits: 0 },
isPro: false,
}));
});

describe("checkCreditsAvailable", () => {
Expand All @@ -37,6 +49,10 @@ describe("checkCreditsAvailable", () => {

it("returns insufficient_credits with the balance and the cost, and nothing else", async () => {
selectCreditsUsageMock.mockResolvedValue([{ remaining_credits: 2 }]);
checkAndResetCreditsMock.mockResolvedValue({
creditsUsage: { remaining_credits: 2 },
isPro: false,
});

expect(await checkCreditsAvailable(params)).toEqual({
kind: "insufficient_credits",
Expand Down Expand Up @@ -65,6 +81,7 @@ describe("checkCreditsAvailable", () => {

it("treats an empty credits_usage row as a zero balance", async () => {
selectCreditsUsageMock.mockResolvedValue([]);
checkAndResetCreditsMock.mockResolvedValue({ creditsUsage: null, isPro: false });

expect(await checkCreditsAvailable({ ...params, creditsToDeduct: 1 })).toEqual({
kind: "insufficient_credits",
Expand All @@ -78,4 +95,50 @@ describe("checkCreditsAvailable", () => {

expect(await checkCreditsAvailable(params)).toEqual({ kind: "available" });
});

describe("a due-but-unapplied monthly refill", () => {
it("is applied on a shortfall, so the first gated request after the boundary passes", async () => {
selectCreditsUsageMock.mockResolvedValue([{ remaining_credits: 0 }]);
checkAndResetCreditsMock.mockResolvedValue({
creditsUsage: { remaining_credits: 333 },
isPro: false,
});

expect(await checkCreditsAvailable(params)).toEqual({ kind: "available" });
expect(checkAndResetCreditsMock).toHaveBeenCalledWith("acct_123");
});

it("still 402s with the refreshed balance when the refilled total does not cover the cost", async () => {
selectCreditsUsageMock.mockResolvedValue([{ remaining_credits: 0 }]);
checkAndResetCreditsMock.mockResolvedValue({
creditsUsage: { remaining_credits: 3 },
isPro: false,
});

expect(await checkCreditsAvailable(params)).toEqual({
kind: "insufficient_credits",
remainingCredits: 3,
requiredCredits: 5,
});
});

it("is not consulted on the happy path — a sufficient balance stays a single read", async () => {
selectCreditsUsageMock.mockResolvedValue([{ remaining_credits: 100 }]);

await checkCreditsAvailable(params);

expect(checkAndResetCreditsMock).not.toHaveBeenCalled();
});

it("treats a missing row from the refill check as a zero balance", async () => {
selectCreditsUsageMock.mockResolvedValue([]);
checkAndResetCreditsMock.mockResolvedValue({ creditsUsage: null, isPro: false });

expect(await checkCreditsAvailable({ ...params, creditsToDeduct: 1 })).toEqual({
kind: "insufficient_credits",
remainingCredits: 0,
requiredCredits: 1,
});
});
});
});
14 changes: 13 additions & 1 deletion lib/credits/checkCreditsAvailable.ts
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;
Expand All @@ -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.
*
Expand All @@ -35,9 +42,14 @@ export async function checkCreditsAvailable(

if (remaining >= creditsToDeduct) return { kind: "available" };

const { creditsUsage } = await checkAndResetCredits(accountId);

Copy link
Copy Markdown

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
Check if this issue is valid — if so, understand the root cause and fix it. At lib/credits/checkCreditsAvailable.ts, line 45:

<comment>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.</comment>

<file context>
@@ -35,9 +42,14 @@ export async function checkCreditsAvailable(
 
   if (remaining >= creditsToDeduct) return { kind: "available" };
 
+  const { creditsUsage } = await checkAndResetCredits(accountId);
+  const refreshed = creditsUsage?.remaining_credits ?? 0;
+
</file context>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: On a shortfall, the gate now calls checkAndResetCredits, which can throw: it runs getAccountSubscriptionState and, when a refill is due, updateCreditsUsage — and both selectCreditsUsage/updateCreditsUsage throw on Supabase errors. ensureCreditsOrShortCircuit has no try/catch, so any of these failures now propagates and turns what used to be a guaranteed graceful 402 into a 500 on the shortfall path. The updated JSDoc also still claims "It reads, and does nothing else", which is no longer true once a refill is applied. Decide explicitly whether the gate should swallow refill errors (return the 402 with the pre-refill balance) or let them bubble, and update the doc comment to reflect that the shortfall path performs a write/refill.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/credits/checkCreditsAvailable.ts, line 45:

<comment>On a shortfall, the gate now calls `checkAndResetCredits`, which can throw: it runs `getAccountSubscriptionState` and, when a refill is due, `updateCreditsUsage` — and both `selectCreditsUsage`/`updateCreditsUsage` throw on Supabase errors. `ensureCreditsOrShortCircuit` has no try/catch, so any of these failures now propagates and turns what used to be a guaranteed graceful 402 into a 500 on the shortfall path. The updated JSDoc also still claims "It reads, and does nothing else", which is no longer true once a refill is applied. Decide explicitly whether the gate should swallow refill errors (return the 402 with the pre-refill balance) or let them bubble, and update the doc comment to reflect that the shortfall path performs a write/refill.</comment>

<file context>
@@ -35,9 +42,14 @@ export async function checkCreditsAvailable(
 
   if (remaining >= creditsToDeduct) return { kind: "available" };
 
+  const { creditsUsage } = await checkAndResetCredits(accountId);
+  const refreshed = creditsUsage?.remaining_credits ?? 0;
+
</file context>

const refreshed = creditsUsage?.remaining_credits ?? 0;

if (refreshed >= creditsToDeduct) return { kind: "available" };

return {
kind: "insufficient_credits",
remainingCredits: remaining,
remainingCredits: refreshed,
requiredCredits: creditsToDeduct,
};
}
Loading