Skip to content

feat(billing): subscription cancelAt + cancelAtPeriodEnd lifecycle fields#3741

Merged
PierreBrisorgueil merged 3 commits into
masterfrom
feat/subscription-cancel-at-fields
May 31, 2026
Merged

feat(billing): subscription cancelAt + cancelAtPeriodEnd lifecycle fields#3741
PierreBrisorgueil merged 3 commits into
masterfrom
feat/subscription-cancel-at-fields

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

Summary

  • Ports cancelAtPeriodEnd (Boolean, default null) and cancelAt (Date, default null) verbatim from trawl_node into devkit Node's Subscription Mongoose model and Zod schema
  • Strict gate for Task C.2 (customer.subscription.updated webhook handler): the handler currently silently downgrades paid plans to free on every Stripe event; C.2 fixes that and writes to these fields — but needs the model first
  • Both fields use default: null (honest semantics: null = not yet synced from Stripe, vs false = explicitly not cancelling)

Key design note

z.coerce.date() treats numbers as milliseconds, not seconds. The C.2 webhook handler must multiply Stripe's cancel_at (Unix seconds) by 1000 before passing to the schema: cancelAt: new Date(stripeEvent.cancel_at * 1000).

Zod/Mongoose asymmetry (intentional)

  • Mongoose cancelAtPeriodEnd: type: Boolean, default: null — DB can hold null for legacy/unsynced docs
  • Zod cancelAtPeriodEnd: z.boolean().optional() (NOT .nullable()) — new writes via schema validation must be boolean or omitted; null is rejected at the validation layer

This layering is intentional and matches the trawl_node production pattern.

Test coverage

New file billing.subscription.schema.unit.tests.js (15 tests) covers:

  • Happy path: both fields set (true + Date)
  • Backward compat: fields omitted → undefined
  • ISO string coercion → Date
  • Number (ms) coercion → Date with exact value assertion + ×1000 note for webhook handler
  • null cancelAt → null (nullable)
  • null cancelAtPeriodEnd → rejected (not nullable)
  • Non-boolean cancelAtPeriodEnd → rejected
  • SubscriptionUpdate partial patch for each field

Pre-push gate

Phase 0 DeepSeek review: OK with nits (2 test naming issues — fixed before push). 0 critical, 0 high findings.

Closes #3740

…e fields

Port pending-cancellation fields verbatim from trawl_node into devkit so every
downstream gets them. Required gate for the customer.subscription.updated webhook
handler (C.2) which writes these fields on Stripe cancel_at_period_end events.

Closes #3740
- Rename Unix-seconds test to clarify z.coerce.date() treats numbers as ms
  (not seconds); add exact date assertion to make the ×1000 contract explicit
- Rename null-rejection test so name matches assertion (was "accept both null",
  now "reject null cancelAtPeriodEnd — not nullable")
Copilot AI review requested due to automatic review settings May 31, 2026 17:28
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 31, 2026

Warning

Review limit reached

@PierreBrisorgueil, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 25 minutes and 55 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e46396f0-6d7e-4c49-8c2e-0d09daac05d5

📥 Commits

Reviewing files that changed from the base of the PR and between 5f757e6 and 78bb6ab.

📒 Files selected for processing (3)
  • modules/billing/models/billing.subscription.model.mongoose.js
  • modules/billing/models/billing.subscription.schema.js
  • modules/billing/tests/billing.subscription.schema.unit.tests.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/subscription-cancel-at-fields

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 31, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.92%. Comparing base (5f757e6) to head (78bb6ab).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #3741   +/-   ##
=======================================
  Coverage   89.92%   89.92%           
=======================================
  Files         148      148           
  Lines        4865     4865           
  Branches     1533     1533           
=======================================
  Hits         4375     4375           
  Misses        385      385           
  Partials      105      105           
Flag Coverage Δ
integration 59.95% <ø> (ø)
unit 67.62% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 5f757e6...78bb6ab. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

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

Adds Stripe pending-cancellation lifecycle fields to the Billing Subscription data model so upcoming customer.subscription.updated webhook work (Task C.2 / #3740) can persist cancel_at_period_end + cancel_at without overloading plan/status semantics.

Changes:

  • Extend the Billing Subscription Zod schema with cancelAtPeriodEnd (optional boolean) and cancelAt (optional nullable coerced Date).
  • Extend the Subscription Mongoose model with cancelAtPeriodEnd (Boolean, default null) and cancelAt (Date, default null).
  • Add focused unit tests covering coercion, nullability rules, and SubscriptionUpdate partial patches for the new fields.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
modules/billing/tests/billing.subscription.schema.unit.tests.js Adds unit coverage for the new cancellation lifecycle fields and update-schema patch behavior.
modules/billing/models/billing.subscription.schema.js Introduces the new fields to the Zod base shape (including Date coercion + nullability semantics).
modules/billing/models/billing.subscription.model.mongoose.js Persists the new fields in Mongo via the Subscription Mongoose schema with default: null for legacy/unsynced docs.

Comment thread modules/billing/models/billing.subscription.model.mongoose.js Outdated
Copilot review: "Unix date" was ambiguous. Changed to "Date (converted
from Stripe's cancel_at Unix seconds)" for clarity.
@PierreBrisorgueil PierreBrisorgueil merged commit 889626a into master May 31, 2026
8 checks passed
PierreBrisorgueil added a commit that referenced this pull request May 31, 2026
…#1250) (#3743)

* fix(billing): resolve plan via priceId map, not price.metadata.planId (#3742)

Port trawl's #1250 fix upstream: `customer.subscription.updated` was reading
`price.metadata.planId` which is empty in real Stripe webhook payloads (planId
lives on the Product, not the Price). Every paid org's plan was silently reset
to `free` on every Stripe subscription update event.

Fix:
- Add `buildPriceIdToPlanMap()` — builds `Map<priceId, planName>` from
  `config.stripe.prices` at boot (monthly + annual per plan)
- Rewrite `resolvePlan()` — looks up plan via priceId map first; falls back to
  `price.metadata.planId` for legacy test fixtures; final fallback `free` + warn
- Sync `cancelAt`/`cancelAtPeriodEnd` on `customer.subscription.updated` — writes
  the fields added by #3741 so the UI can show pending cancellation dates
- Use priceId map in `previousPlan` detection (plan change block in updated handler)
- Strip trawl-specific `analytics.capture('subscription_changed')` calls (not ported)

Also ports `retryWithBackoff` + `isNonTransientStripeError` patterns (already
in devkit from a prior PR — kept identical to trawl).

Adds 20 unit tests covering: priceId map resolution, annual/monthly variants,
unknown priceId fallback to free, legacy metadata fallback, priority of map over
metadata, cancelAt unix→Date conversion, null cancel clear, absent field guard,
handleSubscriptionCreated race safety (E11000 idempotency), and Dashboard
subscription creation path.

Closes #3742

* docs(billing): add ERRORS.md entry for price.metadata.planId empty in Stripe webhooks
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.

feat(billing): subscription cancelAt + cancelAtPeriodEnd lifecycle fields

2 participants