Skip to content

Merge test into main#550

Merged
sweetmantech merged 1 commit into
mainfrom
test
May 11, 2026
Merged

Merge test into main#550
sweetmantech merged 1 commit into
mainfrom
test

Conversation

@sweetmantech
Copy link
Copy Markdown
Contributor

@sweetmantech sweetmantech commented May 11, 2026

Batched promotion of test → main.

Included PRs

🤖 Generated with Claude Code


Summary by cubic

Fixes credit seeding for new accounts by initializing balances based on plan (Pro vs Free). Centralizes subscription lookup and uses it in credit resets and account creation.

  • Bug Fixes

    • New initializeAccountCredits seeds credits_usage with PRO_CREDITS or DEFAULT_CREDITS based on getAccountSubscriptionState.
    • Account creation paths now call initializeAccountCredits instead of insertCreditsUsage.
  • Refactors

    • Added getAccountSubscriptionState (account wins on tie; checks both account and org) and used it in checkAndResetCredits.
    • Removed the default from insertCreditsUsage to force explicit, plan-aware balances; added focused tests for new helpers.

Written for commit 99d9cdd. Summary will update on new commits.

Brand-new accounts used to receive exactly 25 credits regardless of
plan, because insertCreditsUsage had a hard-coded DEFAULT_CREDITS=25
fallback that both call sites (agent signup + account create) relied
on. The new credits-balance endpoint exposes this as "25 / 333 used 308"
the moment an account is provisioned.

Fix at the API layer, reusing what PR #547 already gave us:

- New `lib/credits/getAccountSubscriptionState.ts` — single source of
  truth for "is this account pro?". Extracts the parallel
  getActiveSubscriptionDetails + getOrgSubscription lookup that
  checkAndResetCredits already did inline.

- `checkAndResetCredits` now delegates to that helper. Behavior
  unchanged; 7 lines collapse to 2.

- New `lib/credits/initializeAccountCredits.ts` — plan-aware seeder.
  Looks up the subscription state via the new helper, then calls
  insertCreditsUsage with PRO_CREDITS=1000 or DEFAULT_CREDITS=333
  (the constants we already exported in PR #547).

- Both call sites swap insertCreditsUsage(id) for
  initializeAccountCredits(id):
  - lib/agents/createAccountWithEmail.ts
  - lib/accounts/createAccountHandler.ts

- Remove the booby-trap default from insertCreditsUsage. The
  remainingCredits parameter is now required, so any new caller that
  forgets to pick a plan-aware value gets a type error.

TDD: 4 new tests for getAccountSubscriptionState, 3 for
initializeAccountCredits, full checkAndResetCredits suite migrated to
mock the new helper instead of three Stripe functions. 234 tests
green across 39 files. lint clean. No typecheck regressions in
changed files (pre-existing AI-SDK type drift in getCreditUsage.test
and handleChatCredits.test is unchanged).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented May 11, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
api Ready Ready Preview May 11, 2026 9:17pm

Request Review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 11, 2026

Warning

Rate limit exceeded

@sweetmantech has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 26 minutes and 26 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c1a541f1-05fa-477d-8c12-f0d7b34b407d

📥 Commits

Reviewing files that changed from the base of the PR and between 6b885c2 and 99d9cdd.

⛔ Files ignored due to path filters (6)
  • lib/accounts/__tests__/createAccountHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/agents/__tests__/agentSignupHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/agents/__tests__/createAccountWithEmail.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/credits/__tests__/checkAndResetCredits.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/credits/__tests__/getAccountSubscriptionState.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • lib/credits/__tests__/initializeAccountCredits.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
📒 Files selected for processing (6)
  • lib/accounts/createAccountHandler.ts
  • lib/agents/createAccountWithEmail.ts
  • lib/credits/checkAndResetCredits.ts
  • lib/credits/getAccountSubscriptionState.ts
  • lib/credits/initializeAccountCredits.ts
  • lib/supabase/credits_usage/insertCreditsUsage.ts
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sweetmantech sweetmantech merged commit 710f789 into main May 11, 2026
7 checks passed
Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 12 files

Confidence score: 3/5

  • There is a concrete consistency risk in lib/accounts/createAccountHandler.ts: if initializeAccountCredits returns null, the handler can still return 200 even though the account is missing its credits row.
  • Given the high severity/confidence (7/10, 9/10) and direct user-facing impact, this is more than a minor issue and introduces some merge risk until handled explicitly.
  • Pay close attention to lib/accounts/createAccountHandler.ts - ensure null from credits initialization is treated as a failure path rather than a successful account creation response.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/accounts/createAccountHandler.ts">

<violation number="1" location="lib/accounts/createAccountHandler.ts:94">
P1: Handle `initializeAccountCredits` returning `null`; otherwise this path can return 200 for an account that was created without its credits row.</violation>
</file>
Architecture diagram
sequenceDiagram
    participant Handler as Account Creation Handler
    participant CreditsInit as initializeAccountCredits
    participant SubState as getAccountSubscriptionState
    participant StripeAcct as getActiveSubscriptionDetails
    participant StripeOrg as getOrgSubscription
    participant DB as Database
    participant CreditsUsage as insertCreditsUsage
    participant Reset as checkAndResetCredits

    Note over Handler,DB: NEW: Plan-aware credit seeding during account creation

    Handler->>CreditsInit: initializeAccountCredits(accountId)
    CreditsInit->>SubState: getAccountSubscriptionState(accountId)
    par Fetch subscriptions in parallel
        SubState->>StripeAcct: getActiveSubscriptionDetails(accountId)
        SubState->>StripeOrg: getOrgSubscription(accountId)
    end
    StripeAcct-->>SubState: account subscription (or null)
    StripeOrg-->>SubState: org subscription (or null)

    alt Account has active subscription
        SubState->>SubState: isPro=true, use account sub
    else Only org has active subscription
        SubState->>SubState: isPro=true, use org sub
    else Neither active
        SubState->>SubState: isPro=false
    end
    SubState-->>CreditsInit: { isPro, activeSubscription }

    alt isPro == true
        CreditsInit->>CreditsUsage: insertCreditsUsage(accountId, PRO_CREDITS)
    else isPro == false
        CreditsInit->>CreditsUsage: insertCreditsUsage(accountId, DEFAULT_CREDITS)
    end
    CreditsUsage->>DB: INSERT credits_usage row
    DB-->>CreditsUsage: Created row
    CreditsUsage-->>CreditsInit: credits_usage record or null
    CreditsInit-->>Handler: credits_usage record or null

    Note over Reset,DB: CHANGED: Subscription lookup consolidated in checkAndResetCredits

    Reset->>SubState: getAccountSubscriptionState(accountId)
    SubState-->>Reset: { isPro, activeSubscription }
    Reset->>DB: selectCreditsUsage(accountId)
    DB-->>Reset: credits_usage row

    alt Credits row exists
        Reset->>Reset: Check refill triggers (monthly + subscription start)
        alt Refill needed
            Reset->>DB: updateCreditsUsage with PRO_CREDITS or DEFAULT_CREDITS
            DB-->>Reset: Updated row
        end
    end
    Reset-->>Handler: { creditsUsage, isPro }
Loading

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

}

await insertCreditsUsage(newAccount.id);
await initializeAccountCredits(newAccount.id);
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: Handle initializeAccountCredits returning null; otherwise this path can return 200 for an account that was created without its credits row.

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

<comment>Handle `initializeAccountCredits` returning `null`; otherwise this path can return 200 for an account that was created without its credits row.</comment>

<file context>
@@ -91,7 +91,7 @@ export async function createAccountHandler(body: CreateAccountBody): Promise<Nex
     }
 
-    await insertCreditsUsage(newAccount.id);
+    await initializeAccountCredits(newAccount.id);
 
     const newAccountData: AccountDataResponse = {
</file context>
Suggested change
await initializeAccountCredits(newAccount.id);
const credits = await initializeAccountCredits(newAccount.id);
if (!credits) {
throw new Error("createAccountHandler: initializeAccountCredits returned null");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant