Skip to content

billing: Fix P2025 error in Stripe sync#1173

Merged
elie222 merged 1 commit intomainfrom
fix/stripe-sync-p2025
Jan 2, 2026
Merged

billing: Fix P2025 error in Stripe sync#1173
elie222 merged 1 commit intomainfrom
fix/stripe-sync-p2025

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Jan 2, 2026

User description

Replaces prisma.premium.update() with upsert() in syncStripeDataToDb to handle cases where the Premium record doesn't exist yet.

  • Added error log for missing records to monitor and investigation
  • Refactored to reuse subscriptionData object between update and create in upsert
  • Added clarifying comments regarding system design (pre-creating customer IDs)

Generated description

Below is a concise technical summary of the changes proposed in this PR:

graph LR
syncStripeDataToDb_("syncStripeDataToDb"):::modified
STRIPE_("STRIPE"):::modified
PRISMA_("PRISMA"):::modified
LOOPS_SERVICE_("LOOPS_SERVICE"):::modified
syncStripeDataToDb_ -- "Now fetches subscriptions and handles absent Premium gracefully" --> STRIPE_
STRIPE_ -- "Response now used to build subscriptionData for upsert" --> syncStripeDataToDb_
syncStripeDataToDb_ -- "Replaces update with upsert; persists subscriptionData or nulls fields" --> PRISMA_
syncStripeDataToDb_ -- "Now upserts and returns premium/users before triggering Loops" --> LOOPS_SERVICE_
classDef added stroke:#15AA7A
classDef removed stroke:#CD5270
classDef modified stroke:#EDAC4C
linkStyle default stroke:#CBD5E1,font-size:13px
Loading

Replace prisma.premium.update() with prisma.premium.upsert() in the syncStripeDataToDb function to robustly handle cases where a Premium record might not exist, preventing P2025 errors, and log an error if a record is unexpectedly missing.

TopicDetails
Refactor Data Logic Refactor the assignment of subscription data to reuse the subscriptionData object across update and create operations within the upsert calls.
Modified files (1)
  • apps/web/ee/billing/stripe/sync-stripe.ts
Latest Contributors(1)
UserCommitDate
elie222loggerDecember 18, 2025
Improve Sync Robustness Enhance the Stripe data synchronization process by using upsert operations to prevent P2025 errors when Premium records are missing and add logging for unexpected missing records.
Modified files (1)
  • apps/web/ee/billing/stripe/sync-stripe.ts
Latest Contributors(1)
UserCommitDate
elie222loggerDecember 18, 2025
This pull request is reviewed by Baz. Review like a pro on (Baz).

Summary by CodeRabbit

  • Bug Fixes

    • Improved resilience of billing synchronization with enhanced error handling and automatic data recovery for subscription edge cases.
  • Refactor

    • Consolidated and unified subscription data handling to ensure consistent state across create and update operations, reducing code duplication.

✏️ Tip: You can customize this high-level summary in your review settings.

@vercel
Copy link

vercel bot commented Jan 2, 2026

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

Project Deployment Review Updated (UTC)
inbox-zero Ready Ready Preview Jan 2, 2026 8:32am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 2, 2026

📝 Walkthrough

Walkthrough

Refactored Stripe subscription synchronization logic to replace separate update/create paths with Prisma upsert operations. Consolidated subscription-related data fields into a unified object and added defensive checks for missing data with error logging.

Changes

Cohort / File(s) Summary
Stripe subscription sync refactoring
apps/web/ee/billing/stripe/sync-stripe.ts
Replaced direct update calls with upsert for both subscription and no-subscription cases. Consolidated stripe-related fields (tier, IDs, statuses, timestamps) into a single subscriptionData object. Added defensive validation for missing currentPremium with error logging. Ensured stripeCustomerId is initialized on create operations. Post-upsert logic (event loops, seat sync, email watches) now operates on upsert result.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • Loops billing #464: Modifies the same syncStripeDataToDb logic with prior-state retrieval and handleLoopsEvent call integration, affecting similar subscription update flows.
  • Fix duplicate pending and account premium #748: Affects the same file with changes to premium upsert/update and seat-sync logic, including user selection and pending-invite deduplication.

Poem

🐰 With upsert spells, this rabbit hops with glee,
No more split paths—one query sets things free!
Stripe subscriptions dance in unified arrays,
Self-healing data through defensive malaise. ✨

Pre-merge checks and finishing touches

❌ 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%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'billing: Fix P2025 error in Stripe sync' directly and clearly describes the main change: fixing a Prisma P2025 error in the billing Stripe sync functionality. This accurately reflects the primary objective of replacing update() with upsert() to handle missing Premium records.
✨ Finishing touches
  • 📝 Generate docstrings

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.

@macroscopeapp
Copy link
Contributor

macroscopeapp bot commented Jan 2, 2026

Fix P2025 by upserting Premium records during Stripe sync in apps/web/ee/billing/stripe/sync-stripe.ts

Replace prisma.premium.update with prisma.premium.upsert in syncStripeDataToDb, factor payload into subscriptionData, and add an error log when no Premium exists for the Stripe customer.

📍Where to Start

Start with the syncStripeDataToDb function in sync-stripe.ts.


Macroscope summarized c57a7bf.

Copy link
Contributor

@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.

No issues found across 1 file

Copy link
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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 71610c7 and c57a7bf.

📒 Files selected for processing (1)
  • apps/web/ee/billing/stripe/sync-stripe.ts
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/data-fetching.mdc)

**/*.{ts,tsx}: For API GET requests to server, use the swr package
Use result?.serverError with toastError from @/components/Toast for error handling in async operations

**/*.{ts,tsx}: Use wrapper functions for Gmail message operations (get, list, batch, etc.) from @/utils/gmail/message.ts instead of direct API calls
Use wrapper functions for Gmail thread operations from @/utils/gmail/thread.ts instead of direct API calls
Use wrapper functions for Gmail label operations from @/utils/gmail/label.ts instead of direct API calls

**/*.{ts,tsx}: For early access feature flags, create hooks using the naming convention use[FeatureName]Enabled that return a boolean from useFeatureFlagEnabled("flag-key")
For A/B test variant flags, create hooks using the naming convention use[FeatureName]Variant that define variant types, use useFeatureFlagVariantKey() with type casting, and provide a default "control" fallback
Use kebab-case for PostHog feature flag keys (e.g., inbox-cleaner, pricing-options-2)
Always define types for A/B test variant flags (e.g., type PricingVariant = "control" | "variant-a" | "variant-b") and provide type safety through type casting

**/*.{ts,tsx}: Don't use primitive type aliases or misleading types
Don't use empty type parameters in type aliases and interfaces
Don't use this and super in static contexts
Don't use any or unknown as type constraints
Don't use the TypeScript directive @ts-ignore
Don't use TypeScript enums
Don't export imported variables
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions
Don't use TypeScript namespaces
Don't use non-null assertions with the ! postfix operator
Don't use parameter properties in class constructors
Don't use user-defined types
Use as const instead of literal types and type annotations
Use either T[] or Array<T> consistently
Initialize each enum member value explicitly
Use export type for types
Use `impo...

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/prisma-enum-imports.mdc)

Always import Prisma enums from @/generated/prisma/enums instead of @/generated/prisma/client to avoid Next.js bundling errors in client components

Import Prisma using the project's centralized utility: import prisma from '@/utils/prisma'

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Import specific lodash functions rather than entire lodash library to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Do not export types/interfaces that are only used within the same file. Export later if needed

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

**/*.ts: ALL database queries MUST be scoped to the authenticated user/account by including user/account filtering in WHERE clauses to prevent unauthorized data access
Always validate that resources belong to the authenticated user before performing operations, using ownership checks in WHERE clauses or relationships
Always validate all input parameters for type, format, and length before using them in database queries
Use SafeError for error responses to prevent information disclosure. Generic error messages should not reveal internal IDs, logic, or resource ownership details
Only return necessary fields in API responses using Prisma's select option. Never expose sensitive data such as password hashes, private keys, or system flags
Prevent Insecure Direct Object References (IDOR) by validating resource ownership before operations. All findUnique/findFirst calls MUST include ownership filters
Prevent mass assignment vulnerabilities by explicitly whitelisting allowed fields in update operations instead of accepting all user-provided data
Prevent privilege escalation by never allowing users to modify system fields, ownership fields, or admin-only attributes through user input
All findMany queries MUST be scoped to the user's data by including appropriate WHERE filters to prevent returning data from other users
Use Prisma relationships for access control by leveraging nested where clauses (e.g., emailAccount: { id: emailAccountId }) to validate ownership

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.{tsx,ts}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

**/*.{tsx,ts}: Use Shadcn UI and Tailwind for components and styling
Use next/image package for images
For API GET requests to server, use the swr package with hooks like useSWR to fetch data
For text inputs, use the Input component with registerProps for form integration and error handling

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.{tsx,ts,css}

📄 CodeRabbit inference engine (.cursor/rules/ui-components.mdc)

Implement responsive design with Tailwind CSS using a mobile-first approach

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use accessKey attribute on any HTML element
Don't set aria-hidden="true" on focusable elements
Don't add ARIA roles, states, and properties to elements that don't support them
Don't use distracting elements like <marquee> or <blink>
Only use the scope prop on <th> elements
Don't assign non-interactive ARIA roles to interactive HTML elements
Make sure label elements have text content and are associated with an input
Don't assign interactive ARIA roles to non-interactive HTML elements
Don't assign tabIndex to non-interactive HTML elements
Don't use positive integers for tabIndex property
Don't include "image", "picture", or "photo" in img alt prop
Don't use explicit role property that's the same as the implicit/default role
Make static elements with click handlers use a valid role attribute
Always include a title element for SVG elements
Give all elements requiring alt text meaningful information for screen readers
Make sure anchors have content that's accessible to screen readers
Assign tabIndex to non-interactive HTML elements with aria-activedescendant
Include all required ARIA attributes for elements with ARIA roles
Make sure ARIA properties are valid for the element's supported roles
Always include a type attribute for button elements
Make elements with interactive roles and handlers focusable
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden)
Always include a lang attribute on the html element
Always include a title attribute for iframe elements
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress
Accompany onMouseOver/onMouseOut with onFocus/onBlur
Include caption tracks for audio and video elements
Use semantic elements instead of role attributes in JSX
Make sure all anchors are valid and navigable
Ensure all ARIA properties (aria-*) are valid
Use valid, non-abstract ARIA roles for elements with ARIA roles
Use valid AR...

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
!(pages/_document).{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

Don't use the next/head module in pages/_document.js on Next.js projects

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/utilities.mdc)

**/*.{js,ts,jsx,tsx}: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size (e.g., import groupBy from 'lodash/groupBy')

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
apps/web/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx,js,jsx}: Use @/ path aliases for imports from project root
Prefer self-documenting code over comments; use descriptive variable and function names instead of explaining intent with comments
Add helper functions to the bottom of files, not the top
All imports go at the top of files, no mid-file dynamic imports

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
apps/web/**/*.{ts,tsx,js,jsx,json,css}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Format code with Prettier

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
apps/web/**/*.{example,ts,json}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

Add environment variables to .env.example, env.ts, and turbo.json

Files:

  • apps/web/ee/billing/stripe/sync-stripe.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Baz Reviewer
  • GitHub Check: Macroscope - Correctness Check
  • GitHub Check: test
🔇 Additional comments (3)
apps/web/ee/billing/stripe/sync-stripe.ts (3)

32-38: LGTM! Good defensive error handling.

The error logging and self-healing approach via upsert is appropriate. The comment clearly explains the expected system behavior (customer IDs pre-created).


113-131: LGTM! Excellent refactoring with enhanced lifecycle tracking.

The consolidation into a subscriptionData object improves maintainability, and the addition of stripeCanceledAt and stripeEndedAt fields provides better subscription lifecycle visibility. The type handling for product (string vs object) is appropriate.


133-144: LGTM! Successfully addresses the P2025 error.

The replacement of update with upsert correctly handles cases where the Premium record doesn't exist, preventing the P2025 error. The use of the consolidated subscriptionData object ensures consistency between update and create operations.

Comment on lines +55 to 73
const subscriptionData = {
stripeSubscriptionId: null,
stripeSubscriptionItemId: null,
stripePriceId: null,
stripeProductId: null,
stripeSubscriptionStatus: null,
stripeCancelAtPeriodEnd: null,
stripeRenewsAt: null,
stripeTrialEnd: null,
};

await prisma.premium.upsert({
where: { stripeCustomerId: customerId },
data: {
stripeSubscriptionId: null,
stripeSubscriptionItemId: null,
stripePriceId: null,
stripeProductId: null,
stripeSubscriptionStatus: null, // Or 'none', 'canceled' depending on desired state
stripeCancelAtPeriodEnd: null,
stripeRenewsAt: null,
stripeTrialEnd: null,
// Keep stripeCanceledAt and stripeEndedAt as they might be relevant if it *was* canceled/ended previously
update: subscriptionData,
create: {
...subscriptionData,
stripeCustomerId: customerId,
},
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Consider including tier in the no-subscription data.

The subscriptionData object for the no-subscription case doesn't include the tier field, but the active subscription case (lines 113-131) does. When a customer has no subscription, should the tier be reset to null to prevent users from retaining premium access?

🔎 Proposed fix to include tier in no-subscription data
 const subscriptionData = {
+  tier: null,
   stripeSubscriptionId: null,
   stripeSubscriptionItemId: null,
   stripePriceId: null,
   stripeProductId: null,
   stripeSubscriptionStatus: null,
   stripeCancelAtPeriodEnd: null,
   stripeRenewsAt: null,
   stripeTrialEnd: null,
 };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const subscriptionData = {
stripeSubscriptionId: null,
stripeSubscriptionItemId: null,
stripePriceId: null,
stripeProductId: null,
stripeSubscriptionStatus: null,
stripeCancelAtPeriodEnd: null,
stripeRenewsAt: null,
stripeTrialEnd: null,
};
await prisma.premium.upsert({
where: { stripeCustomerId: customerId },
data: {
stripeSubscriptionId: null,
stripeSubscriptionItemId: null,
stripePriceId: null,
stripeProductId: null,
stripeSubscriptionStatus: null, // Or 'none', 'canceled' depending on desired state
stripeCancelAtPeriodEnd: null,
stripeRenewsAt: null,
stripeTrialEnd: null,
// Keep stripeCanceledAt and stripeEndedAt as they might be relevant if it *was* canceled/ended previously
update: subscriptionData,
create: {
...subscriptionData,
stripeCustomerId: customerId,
},
});
const subscriptionData = {
tier: null,
stripeSubscriptionId: null,
stripeSubscriptionItemId: null,
stripePriceId: null,
stripeProductId: null,
stripeSubscriptionStatus: null,
stripeCancelAtPeriodEnd: null,
stripeRenewsAt: null,
stripeTrialEnd: null,
};
await prisma.premium.upsert({
where: { stripeCustomerId: customerId },
update: subscriptionData,
create: {
...subscriptionData,
stripeCustomerId: customerId,
},
});
🤖 Prompt for AI Agents
In apps/web/ee/billing/stripe/sync-stripe.ts around lines 55 to 73, the
subscriptionData object for the no-subscription case omits the tier field so
upsert won't clear a previous premium tier; add tier: null to subscriptionData
and ensure the create branch also includes tier: null (alongside
stripeCustomerId) so customers without a Stripe subscription have their tier
reset to null.

@elie222 elie222 merged commit 345ea28 into main Jan 2, 2026
20 checks passed
@elie222 elie222 deleted the fix/stripe-sync-p2025 branch January 2, 2026 09:28
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