Skip to content

feat(scripts): add Stripe revenue trend backfill#2010

Merged
riderx merged 4 commits into
mainfrom
codex/stripe-revenue-trend-backfills
May 1, 2026
Merged

feat(scripts): add Stripe revenue trend backfill#2010
riderx merged 4 commits into
mainfrom
codex/stripe-revenue-trend-backfills

Conversation

@riderx
Copy link
Copy Markdown
Member

@riderx riderx commented May 1, 2026

Summary (AI generated)

  • Added a dry-run-first Stripe revenue trend backfill script for admin global_stats revenue charts.
  • Backfills subscription flow, subscription type, MRR, ARR, ARR by plan, churn revenue, and plan distribution trend fields.
  • Added focused unit tests for event replay, yearly/monthly plans, plan transitions, downgrades, activations, and cancel-at-period-end behavior.

Motivation (AI generated)

The admin revenue and user dashboards depend on historical global_stats columns that can be missing or stale for revenue trend charts. The script reconstructs daily subscription state from Stripe subscription events and plan pricing so those charts can be repaired without manual SQL.

Business Impact (AI generated)

Accurate revenue trend history improves visibility into subscription growth, churn, plan mix, MRR, ARR, and plan distribution. This helps Capgo monitor revenue movements and customer behavior from the admin dashboard.

Test Plan (AI generated)

  • bunx eslint --no-ignore scripts/backfill_revenue_trend_metrics.ts tests/backfill-revenue-trend-metrics.unit.test.ts
  • bunx tsc --ignoreConfig --noEmit --allowImportingTsExtensions --moduleResolution bundler --module ESNext --target ES2020 --lib DOM,ESNext --types bun,vitest --strict --esModuleInterop --skipLibCheck scripts/backfill_revenue_trend_metrics.ts tests/backfill-revenue-trend-metrics.unit.test.ts
  • bunx vitest run tests/backfill-retention-metrics.unit.test.ts tests/backfill-revenue-trend-metrics.unit.test.ts tests/logsnag-insights-revenue.unit.test.ts
  • bun lint

Generated with AI

Summary by CodeRabbit

  • Chores

    • Added a new CLI backfill command to recalculate daily revenue trend metrics from Stripe subscription history; supports date ranges, validation, dry-run logging by default and an --apply mode to persist updates.
    • Updated organization type to explicitly include nullable stats timestamp fields.
  • Tests

    • Added comprehensive unit tests for the revenue backfill logic covering subscription lifecycles and metric calculations.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 92f07aed-5b37-4354-97fa-59404cc51675

📥 Commits

Reviewing files that changed from the base of the PR and between 53446a6 and 26a5c24.

📒 Files selected for processing (4)
  • package.json
  • scripts/backfill_revenue_trend_metrics.ts
  • src/stores/organization.ts
  • tests/backfill-revenue-trend-metrics.unit.test.ts
✅ Files skipped from review due to trivial changes (3)
  • package.json
  • src/stores/organization.ts
  • scripts/backfill_revenue_trend_metrics.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/backfill-revenue-trend-metrics.unit.test.ts

📝 Walkthrough

Walkthrough

Adds a new backfill CLI and package script to compute daily revenue trend metrics from Stripe subscription events over a UTC date range, reconstructing per-customer subscription states, deriving daily metrics (MRR, churn, new paying orgs, plan counts, revenue totals), and optionally applying updates to Supabase with --apply.

Changes

Cohort / File(s) Summary
Package Configuration
package.json
Added stripe:backfill-revenue-trends script mapping to the new Bun CLI.
Revenue Backfill Logic
scripts/backfill_revenue_trend_metrics.ts
New standalone CLI that replays Stripe subscription events, supports seeding opening state (baseline subscriptions or archived events), enforces date/order/limit validations, reconstructs per-customer states day-by-day, computes daily metrics (MRR, churn, new paying customers, plan counts, revenue totals), compares against global_stats, and conditionally persists updates to Supabase. Exports RevenueTrendMetricValues, RevenueTrendBackfillRow, summarizeRevenueSnapshot(), and buildRevenueTrendBackfillRows().
Unit Tests
tests/backfill-revenue-trend-metrics.unit.test.ts
New comprehensive unit tests covering subscription lifecycle scenarios (create/delete, reactivation, baseline attribution, downgrades, status-only activations, cancel-at-period-end), using deterministic timestamps and mocked Stripe events to validate per-day metrics.
Types / Store Update
src/stores/organization.ts
Adjusted Organization type to explicitly include `stats_refresh_requested_at: string

Sequence Diagram

sequenceDiagram
    participant CLI as Backfill CLI
    participant Stripe as Stripe API
    participant Archive as Event Archive
    participant State as Subscription State Engine
    participant Calc as Metrics Calculator
    participant Supabase as Supabase

    CLI->>Stripe: Fetch events (--from/--to, --limit)
    Stripe-->>CLI: Subscription events (paginated)
    CLI->>Archive: (optional) Load archived events / baseline subscriptions
    Archive-->>CLI: Historical events / baselines
    CLI->>State: Seed opening state (baseline + pre-range events)
    CLI->>State: Feed in-range events day-by-day
    State->>State: Replay events, expire subscriptions at end dates
    State-->>Calc: Daily subscription snapshots
    Calc->>Calc: Compute MRR, churn, new paying orgs, plan counts, revenue totals
    Calc-->>CLI: Backfill rows (pending)
    CLI->>Supabase: Fetch existing global_stats rows by date_id
    Supabase-->>CLI: Existing rows
    CLI->>CLI: Diff rows, show pending updates (dry-run)
    alt --apply flag set and events not truncated
        CLI->>Supabase: Update matching global_stats rows by date_id
        Supabase-->>CLI: Update confirmations
    end
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I hop through Stripe's event trail,
Replaying subs from hail to tail,
Daily numbers bloom and sigh,
MRR and churn counted by my eye,
With --apply, the charts set sail!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 clearly and concisely summarizes the main change: adding a Stripe revenue trend backfill script feature.
Description check ✅ Passed The description provides a comprehensive summary, detailed test plan with checkmarks, and business context, matching the template requirements well.
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.

✏️ 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 codex/stripe-revenue-trend-backfills

Review rate limit: 0/5 reviews remaining, refill in 54 minutes and 7 seconds.

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

@codspeed-hq
Copy link
Copy Markdown
Contributor

codspeed-hq Bot commented May 1, 2026

Merging this PR will not alter performance

✅ 28 untouched benchmarks


Comparing codex/stripe-revenue-trend-backfills (26a5c24) with main (a700840)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (9158f47) during the generation of this report, so a700840 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 594924745c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/backfill_revenue_trend_metrics.ts
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@socket-security
Copy link
Copy Markdown

socket-security Bot commented May 1, 2026

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 the current code and only fix it if needed.

Inline comments:
In `@scripts/backfill_revenue_trend_metrics.ts`:
- Around line 974-976: Add a guard that prevents running the destructive --apply
mode when a per-customer scope is specified: after the existing check that
validates customerId (the block that checks customerId.startsWith('cus_')), add
a check that if the --apply flag is set (the variable controlling apply mode,
e.g., apply or isApply) and customerId is provided, throw an Error explaining
that --apply cannot be used with --customer-id because it would overwrite
global_stats; this ensures the script never applies one-customer metrics into
the global_stats aggregate.
🪄 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: 8148281d-f716-4d70-ae9b-0722bf60217b

📥 Commits

Reviewing files that changed from the base of the PR and between dc4e426 and 53446a6.

📒 Files selected for processing (3)
  • package.json
  • scripts/backfill_revenue_trend_metrics.ts
  • tests/backfill-revenue-trend-metrics.unit.test.ts

Comment thread scripts/backfill_revenue_trend_metrics.ts
@riderx riderx force-pushed the codex/stripe-revenue-trend-backfills branch from 53446a6 to 907666b Compare May 1, 2026 18:15
@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector
Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented May 1, 2026

@riderx riderx merged commit ca2f66d into main May 1, 2026
50 checks passed
@riderx riderx deleted the codex/stripe-revenue-trend-backfills branch May 1, 2026 18:41
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