Skip to content

[Feat] new scripts on migrate/seed/init run for internal#1421

Open
nams1570 wants to merge 2 commits into
devfrom
migrate-plans-and-products-ui
Open

[Feat] new scripts on migrate/seed/init run for internal#1421
nams1570 wants to merge 2 commits into
devfrom
migrate-plans-and-products-ui

Conversation

@nams1570
Copy link
Copy Markdown
Collaborator

@nams1570 nams1570 commented May 7, 2026

Context

One script grants free plan to any team which is a customer of the internal project who doesnt have it already.
We also want to migrate our users (internal) to the latest version of their products.

Needed because some subs on dev right now dont have a plan. And internal isnt using latest version of its own growth plan.

Describing the Paths we want to Account for

  1. Users on production who currently don't have a plan should get free plans, since this script is run with every migrate
  2. Users on production should get the latest version of each plan of ours. So a forced migration to latest version of internal project plans
  3. No other project's products/product lines should be affected. They will continue to have product versioning
  4. 2 should apply to test mode subscriptions as well, on top of stripe subscriptions. All of them should be refreshed
  5. Internal project itself should get latest version of its own growth plan
  6. If the bulldozer write fails, we should be able to recover on next migration (this should already be handled by init bulldozer script, because it checks if prisma db and bulldozer db are out of sync)
  7. if the regenerate or backfill fail, we should be able to recover just by rerunning the script
  8. Product version table should not balloon. No table should really balloon

Deployment strategy in prod

Run the backfill and the regen scripts once each after your migrations on the prod db.
pnpm db:backfill-internal-free-plans will make sure every team has a free plan at least if they dont have an existing plan (and it is idempotent).
After that, run pnpm db:regen-internal-subscriptions-to-latest which will migrate every user to the latest version of their plan (i.e latest snapshot). This should also be idempotent.

Summary by CodeRabbit

  • New Features

    • Automated backfill to grant internal free plans to qualifying billing teams.
    • Regeneration tool to refresh internal subscription snapshots to the latest product versions.
  • Chores

    • Added CLI commands and package scripts to run backfill and regen jobs.
    • Database init now runs payment initialization before backfill/regen.
  • Tests

    • Integration and unit tests added/updated to validate backfill, regeneration, and free-plan idempotency.

Review Change Stack

Copilot AI review requested due to automatic review settings May 7, 2026 02:50
@vercel
Copy link
Copy Markdown

vercel Bot commented May 7, 2026

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

Project Deployment Actions Updated (UTC)
stack-auth-hosted-components Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-auth-mcp Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-backend Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-dashboard Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-demo Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-docs Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-preview-backend Ready Ready Preview, Comment May 11, 2026 10:32pm
stack-preview-dashboard Ready Ready Preview, Comment May 11, 2026 10:32pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 7, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a bounded, batched backfill that grants the internal free plan to qualifying internal teams; changes ensureFreePlanForBillingTeam to return a boolean indicating whether a new subscription row was created; wires the backfill into migration CLI and npm scripts; and adds a subscription-regeneration runner with extensive real-DB integration tests.

Changes

Internal Free Plan Backfill

Layer / File(s) Summary
Return Type Contract
apps/backend/src/lib/payments/ensure-free-plan.ts
ensureFreePlanForBillingTeam changes from Promise<void> to Promise<boolean>, returning true only when a new free subscription row is created and false for misconfigured products, already-occupied product lines, race losses, or failed inserts.
Backfill Script Implementation
apps/backend/scripts/backfill-internal-free-plans.ts
New runBackfillInternalFreePlans() resolves internal tenancy, validates free product configuration, iterates billing teams via keyset pagination in fixed batches, calls ensureFreePlanForBillingTeam per team with isolated error handling, logs progress every 100 teams, and returns { granted, failed, total }.
Migration CLI and Script Integration
apps/backend/scripts/db-migrations.ts
Imports runBackfillInternalFreePlans, adds new backfill-internal-free-plans CLI command and help text, and ensures runBulldozerPaymentsInit runs before backfill/reset/regen flows.
Subscription Regen Runner
apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
Adds runRegenInternalSubscriptionsToLatest, regenSingleSubscription, isProductSnapshotCurrent, Stripe client types, counters, team iterator, skip/update logic, idempotent ProductVersion upserts, Stripe metadata rebasing when needed, tenancy-aware Prisma writes with retry, and Bulldozer dual-writes.
Regen Tests (integration)
apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts
Adds Vitest real-DB integration tests and a typed Stripe mock covering in-product and Stripe-backed cases, TEST_MODE handling, missing-product/ended skips, failure isolation, and a Bulldozer end-to-end check.
NPM Script Wiring
apps/backend/package.json, package.json
Adds backend script db:backfill-internal-free-plans and root delegations db:backfill-internal-free-plans and db:regen-internal-subscriptions-to-latest; fixes a small echo message in start-deps:no-delay.
Unit Test Updates
apps/backend/src/lib/payments/ensure-free-plan.test.ts
Unit tests updated to assert the boolean return from ensureFreePlanForBillingTeam across fast-path, incomplete, slow-path, idempotency, and ended-only scenarios while preserving existing state assertions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • N2D4

Poem

🐰 I hop through teams in batches tight,

paging softly through the night,
granting free plans, one by one—
counters tick when work is done,
a quiet backfill, tidy and bright.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title '[Feat] new scripts on migrate/seed/init run for internal' accurately captures the main change: new scripts are introduced that run during database migrations/seeding for the internal project.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description comprehensively documents the context, desired paths, and deployment strategy for the two new scripts that grant free plans and migrate users to the latest product versions.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch migrate-plans-and-products-ui

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds deploy-time/internal maintenance scripts to ensure Internal tenancy billing teams always have a baseline free subscription and that existing internal subscriptions’ product snapshots (and Stripe metadata pointers for Stripe-backed subs) are refreshed to the latest product config. It wires these scripts into the backend DB lifecycle commands so dev/prod environments converge on consistent billing state.

Changes:

  • Add backfill-internal-free-plans.ts to grant the free plan to orphaned internal billing teams, and run it on db-migrations reset/seed/init/migrate.
  • Add regen-internal-subscriptions-to-latest.ts to rebase internal subscriptions onto the latest product snapshot (and Stripe metadata productVersionId where applicable), and run it on the same DB lifecycle commands.
  • Update ensureFreePlanForBillingTeam to return a boolean indicating whether it actually inserted a new free-plan subscription row, and expand real-DB test coverage for both scripts.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts Adds real-DB tests covering snapshot regeneration, Stripe-metadata rebasing behavior, failure isolation, and Bulldozer downstream effects.
apps/backend/src/lib/payments/ensure-free-plan.ts Changes ensureFreePlanForBillingTeam to return boolean and documents return semantics for deploy-time backfills.
apps/backend/src/lib/payments/ensure-free-plan.test.ts Updates tests to assert the new boolean return value and adds a regression test for ended-only subscriptions.
apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Introduces the internal subscription regeneration script (DB snapshot + Stripe metadata rebase + ProductVersion upsert).
apps/backend/scripts/db-migrations.ts Runs the new internal-tenancy backfills during reset/seed/init/migrate flows (after Bulldozer init).
apps/backend/scripts/backfill-internal-free-plans.ts Introduces the internal free-plan backfill script with keyset pagination and per-team failure isolation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Outdated
Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Outdated
Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Outdated
Comment thread apps/backend/scripts/backfill-internal-free-plans.ts
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented May 7, 2026

Greptile Summary

This PR adds two idempotent migration scripts — backfill-internal-free-plans and regen-internal-subscriptions-to-latest — for Stack Auth's internal billing project. It also updates ensureFreePlanForBillingTeam to return a boolean indicating whether a grant was actually made, and wires both scripts into the CLI with package.json shortcuts.

  • backfill-internal-free-plans uses cursor-based keyset pagination to iterate all teams and grants a free plan to any team that has no occupying subscription; covered by updated integration tests.
  • regen-internal-subscriptions-to-latest rebases every active internal subscription's stored JSON snapshot and Stripe metadata pointer to the latest product version, writing Stripe first so that a subsequent webhook self-heals any partial DB failure; covered by a comprehensive new test suite.
  • The reset CLI case gains a runBulldozerPaymentsInit call for consistency with init/seed/migrate, and both new CLI cases also run Bulldozer init first to ensure the LFold views are populated before reads.

Confidence Score: 5/5

Safe to merge — both scripts are idempotent, isolated to the internal billing tenancy, and the write ordering (Stripe-first, then DB) correctly handles partial failures via self-healing on the next run.

The core correctness concern from a previous review (whether a retry actually re-issues a stale Bulldozer write) was checked against the read path: getSubscriptionMapForCustomer reads from the Bulldozer LFold, not from Prisma, so a failed bulldozerWriteSubscription leaves the LFold with the old snapshot and the next run correctly re-enters the write branch. Both scripts have real-DB integration tests covering all branching paths. The only findings are observability gaps (counter state under partial failure, exit-code 0 on full failure) that do not affect migration correctness.

No files require special attention beyond the observability notes left inline on regen-internal-subscriptions-to-latest.ts and db-migrations.ts.

Important Files Changed

Filename Overview
apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Core regen logic with Stripe-first / DB-second write ordering; counter variables can be subtly misleading when bulldozerWriteSubscription throws after the Prisma commit
apps/backend/scripts/backfill-internal-free-plans.ts Keyset-paginated backfill; per-team error isolation is correct; iterateInternalTeamIds is duplicated from the regen script
apps/backend/src/lib/payments/ensure-free-plan.ts Return type narrowed from void to boolean; all early-exit paths correctly return false; Bulldozer write path unchanged
apps/backend/scripts/db-migrations.ts New CLI cases added with correct pre-conditions; reset case gains runBulldozerPaymentsInit for consistency; return values from backfill/regen are silently dropped
apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts Comprehensive real-DB test suite covering all counter paths, TEST_MODE gate, Stripe mock, Bulldozer end-to-end, and per-sub failure isolation

Sequence Diagram

sequenceDiagram
    participant CLI as db-migrations CLI
    participant BInit as runBulldozerPaymentsInit
    participant BF as runBackfillInternalFreePlans
    participant Regen as runRegenInternalSubscriptionsToLatest
    participant EFP as ensureFreePlanForBillingTeam
    participant Prisma as Prisma DB
    participant Bulldozer as Bulldozer LFold
    participant Stripe as Stripe API

    CLI->>BInit: await (Bulldozer LFold populated)
    BInit-->>CLI: done

    CLI->>BF: await
    BF->>Bulldozer: getSubscriptionMapForCustomer (per team)
    Bulldozer-->>BF: subMap
    BF->>EFP: ensureFreePlanForBillingTeam(teamId)
    EFP->>Prisma: SERIALIZABLE tx — insert subscription
    Prisma-->>EFP: createdSub
    EFP->>Bulldozer: bulldozerWriteSubscription
    Bulldozer-->>EFP: ok
    EFP-->>BF: true (granted)
    BF-->>CLI: "{ granted, failed, total }"

    CLI->>Regen: await
    Regen->>Bulldozer: getSubscriptionMapForCustomer (per team)
    Bulldozer-->>Regen: sub (with stored product snapshot)
    Note over Regen: compare sub.product vs latestProduct
    Regen->>Stripe: subscriptions.retrieve (Stripe-backed only)
    Stripe-->>Regen: existing metadata
    Regen->>Prisma: upsertProductVersion (content-hash, idempotent)
    Regen->>Stripe: subscriptions.update metadata (Stripe-first)
    Stripe-->>Regen: ok
    Regen->>Prisma: retryTransaction — subscription.update product snapshot
    Prisma-->>Regen: updated
    Regen->>Bulldozer: bulldozerWriteSubscription
    Bulldozer-->>Regen: ok
    Regen-->>CLI: Counters
Loading
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
apps/backend/scripts/regen-internal-subscriptions-to-latest.ts:521-551
**Counter state diverges when Stripe succeeds but the DB write throws**

`counters.stripeMetadataWrites` is incremented at line 521 before the Prisma/Bulldozer block. If `bulldozerWriteSubscription` (or even `retryTransaction`) then throws, the outer catch fires and increments `counters.skippedFailures` — but `counters.dbWrites` and `counters.mutated` are never reached. The final summary log would show `stripeMetadataWrites=1, dbWrites=0, mutated=0, skippedFailures=1` for that sub, making it look like no mutation happened when one actually did. The inverse case also holds: if the DB path completes but only Bulldozer fails, `counters.dbWrites` hasn't been incremented yet either (it sits after `bulldozerWriteSubscription` at line 547). Consider incrementing `dbWrites` right after the Prisma commit and `mutated` at the top of the DB/Stripe write section rather than at the very end.

### Issue 2 of 2
apps/backend/scripts/db-migrations.ts:239-256
**Partial failures exit with code 0**

Both `runBackfillInternalFreePlans()` and `runRegenInternalSubscriptionsToLatest()` swallow per-item errors internally and return a counters object. The callers here discard the return value entirely, so even a run where every team fails (e.g. a transient DB outage during the deploy window) exits with code 0. Any CI/CD pipeline gating on exit code would consider the step a success. The PR design deliberately accepts partial failures and retries on the next deploy, so this is a known trade-off — but if the intent is to surface systemic failures, checking `result.failed > 0` and optionally throwing (or at least printing a prominent warning to stderr) would make the gap more visible.

Reviews (3): Last reviewed commit: "feat(migration): Migrate internal teams ..." | Re-trigger Greptile

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
apps/backend/scripts/db-migrations.ts (1)

207-245: 💤 Low value

Sequencing and idempotency rationale are well-documented.

Order (Bulldozer init → free-plan backfill → regen) is correct given the stated dependencies (regen dual-writes into stored tables; free-plan backfill reads the Subscription LFold). Both helpers are documented as idempotent so running on every deploy and every dev DB lifecycle is safe.

Minor optional thought: the same trio runBulldozerPaymentsInit / runBackfillInternalFreePlans / runRegenInternalSubscriptionsToLatest is repeated verbatim in 4 branches. A small runPostMigrationInternalSetup() helper would deduplicate and ensure future steps stay in lockstep across branches — but the explicitness has its own value, so deferable.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/backend/scripts/db-migrations.ts` around lines 207 - 245, The repeated
trio of calls runBulldozerPaymentsInit(globalPrismaClient),
runBackfillInternalFreePlans(), and runRegenInternalSubscriptionsToLatest()
should be extracted into a single helper (e.g., runPostMigrationInternalSetup)
to remove duplication and keep future changes in one place; create a function
runPostMigrationInternalSetup that invokes those three helpers (accepting any
needed args like globalPrismaClient) and replace the verbatim calls in the
branches ('generate-migration-file', 'seed', 'init', 'migrate' and the earlier
default/init branch) with a single await runPostMigrationInternalSetup(...)
call.
apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts (1)

225-225: ⚡ Quick win

Replace Object.keys(...)[0]! with ?? throwErr(...) per coding guidelines.

Lines 225, 310, 412, and 462 all use the Object.keys(growth.includedItems)[0]! pattern. If growth ever ships without includedItems (config drift, future seed change, etc.), withoutItem(growth, undefined) would no-op and the test would silently pass on a non-stale snapshot rather than flagging the violated precondition.

♻️ Suggested refactor (illustrative)
-    const stale = withoutItem(growth, Object.keys(growth.includedItems)[0]!);
+    const someItemId = Object.keys(growth.includedItems)[0]
+      ?? throwErr("growth has no includedItems to drop");
+    const stale = withoutItem(growth, someItemId);

Apply at lines 225, 310, 412, and 462. Line 154 already extracts someItemId via an explicit length === 0 throw — that pattern is preferred here too.

As per coding guidelines: "Code defensively and prefer ?? throwErr(...) over non-null assertions, with explicit error messages stating the violated assumption".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts` at
line 225, Replace the non-null assertion usage
Object.keys(growth.includedItems)[0]! with a defensive null-check that throws
when the assumption is violated: obtain the first key from
Object.keys(growth.includedItems) and if it is undefined call throwErr(...) with
a clear message (e.g., "expected growth.includedItems to contain at least one
item") before passing it to withoutItem; apply this change for each occurrence
that uses Object.keys(growth.includedItems)[0]! (the call sites around
withoutItem and any related test setup) so tests will fail fast on missing
includedItems instead of silently no-oping.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@apps/backend/scripts/db-migrations.ts`:
- Around line 207-245: The repeated trio of calls
runBulldozerPaymentsInit(globalPrismaClient), runBackfillInternalFreePlans(),
and runRegenInternalSubscriptionsToLatest() should be extracted into a single
helper (e.g., runPostMigrationInternalSetup) to remove duplication and keep
future changes in one place; create a function runPostMigrationInternalSetup
that invokes those three helpers (accepting any needed args like
globalPrismaClient) and replace the verbatim calls in the branches
('generate-migration-file', 'seed', 'init', 'migrate' and the earlier
default/init branch) with a single await runPostMigrationInternalSetup(...)
call.

In `@apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts`:
- Line 225: Replace the non-null assertion usage
Object.keys(growth.includedItems)[0]! with a defensive null-check that throws
when the assumption is violated: obtain the first key from
Object.keys(growth.includedItems) and if it is undefined call throwErr(...) with
a clear message (e.g., "expected growth.includedItems to contain at least one
item") before passing it to withoutItem; apply this change for each occurrence
that uses Object.keys(growth.includedItems)[0]! (the call sites around
withoutItem and any related test setup) so tests will fail fast on missing
includedItems instead of silently no-oping.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 039860b7-acba-44d0-8a07-864abff8843e

📥 Commits

Reviewing files that changed from the base of the PR and between d69773c and bc1883f.

📒 Files selected for processing (6)
  • apps/backend/scripts/backfill-internal-free-plans.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/src/lib/payments/ensure-free-plan.ts
  • apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/backend/scripts/backfill-internal-free-plans.ts`:
- Around line 95-99: The loop currently awaits each
ensureFreePlanForBillingTeam(teamId) sequentially which slows large backfills;
change to a bounded-concurrency pattern (small worker pool) so multiple teamIds
are processed in parallel while limiting DB pressure: use iterateInternalTeamIds
to produce IDs and dispatch ensureFreePlanForBillingTeam(teamId) into a
concurrency limiter (e.g., p-limit or a simple semaphore) sized to a small
constant (e.g., 5–20), await all inflight promises before finishing each batch,
and preserve/error-handle incrementing total and granted counters inside each
task; keep TEAM_BATCH_SIZE for outer batching if desired.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 809a0dc1-fe89-4cae-b273-28fc16a747a2

📥 Commits

Reviewing files that changed from the base of the PR and between bc1883f and 28ad379.

📒 Files selected for processing (6)
  • apps/backend/scripts/backfill-internal-free-plans.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/src/lib/payments/ensure-free-plan.ts
  • apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts
  • apps/backend/scripts/regen-internal-subscriptions-to-latest.ts

Comment thread apps/backend/scripts/backfill-internal-free-plans.ts
@nams1570
Copy link
Copy Markdown
Collaborator Author

nams1570 commented May 7, 2026

@greptileai please rereview, and read the updated PR description

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@package.json`:
- Line 39: The package.json script "start-deps:no-delay" contains a stray
trailing "n" after the closing quote in the echo command, causing the printed
message to end with "n"; open the "start-deps:no-delay" script and remove the
extraneous trailing "n" so the echo argument ends with the closing quote only
(i.e., ensure the echo string is "\\nDependencies started... 'pnpm run
stop-deps' to stop them" with no characters after the final quote).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 378403af-9aba-4bd2-9924-c53d116b7a9b

📥 Commits

Reviewing files that changed from the base of the PR and between 28ad379 and ca2d729.

📒 Files selected for processing (6)
  • apps/backend/package.json
  • apps/backend/scripts/backfill-internal-free-plans.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/src/lib/payments/ensure-free-plan.ts
  • package.json
✅ Files skipped from review due to trivial changes (2)
  • apps/backend/package.json
  • apps/backend/src/lib/payments/ensure-free-plan.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/backend/scripts/backfill-internal-free-plans.ts
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/scripts/db-migrations.ts

Comment thread package.json Outdated
This gives every team on internal proj w/o a plan the free plan.
It is idempotent - only gives a plan if team has no other plans in the pricing plans product line.
Copy link
Copy Markdown

@vercel vercel Bot left a comment

Choose a reason for hiding this comment

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

Additional Suggestion:

Stray 'n' character outside the closing quote in the echo command in the 'start-deps:no-delay' script

Fix on Vercel

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/backend/scripts/regen-internal-subscriptions-to-latest.ts`:
- Around line 163-168: The current code casts getStripeForAccount's result with
"as unknown as Promise<StripeClientForRegen>", which circumvents TypeScript
safety; replace the cast by adding a small async wrapper (e.g.,
getStripeClientForRegen) that calls getStripeForAccount({ tenancy:
internalTenancy }), extracts and returns only the subscriptions API as a
StripeClientForRegen shape, and then set getStripe to initialize stripePromise
via getStripeClientForRegen(internalTenancy) when options.stripeClient is null;
this removes the double type-cast and makes intent explicit while keeping usage
in getStripe unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f12c1538-5bba-483b-8e7f-4a727bd96a8b

📥 Commits

Reviewing files that changed from the base of the PR and between ca2d729 and b6ea8a5.

📒 Files selected for processing (8)
  • apps/backend/package.json
  • apps/backend/scripts/backfill-internal-free-plans.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/scripts/regen-internal-subscriptions-to-latest.ts
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/src/lib/payments/ensure-free-plan.ts
  • apps/backend/src/scripts/regen-internal-subscriptions-to-latest.test.ts
  • package.json
✅ Files skipped from review due to trivial changes (1)
  • package.json
🚧 Files skipped from review as they are similar to previous changes (5)
  • apps/backend/package.json
  • apps/backend/src/lib/payments/ensure-free-plan.test.ts
  • apps/backend/src/lib/payments/ensure-free-plan.ts
  • apps/backend/scripts/db-migrations.ts
  • apps/backend/scripts/backfill-internal-free-plans.ts

Comment thread apps/backend/scripts/regen-internal-subscriptions-to-latest.ts Outdated
Stripe subscriptions need to have their product version updated in the stripe metadata, else on stripe webhook event they will be reset back to old prod snapshot.
These two scripts will need to be run explicitly in prod. They're not part of the db:migrate script.
@nams1570
Copy link
Copy Markdown
Collaborator Author

@greptileai please do a full rereview

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.

4 participants