Skip to content

feat(billing): add stripe transactions#1864

Closed
baktun14 wants to merge 4 commits intomainfrom
features/add-stripe-transactions
Closed

feat(billing): add stripe transactions#1864
baktun14 wants to merge 4 commits intomainfrom
features/add-stripe-transactions

Conversation

@baktun14
Copy link
Contributor

@baktun14 baktun14 commented Aug 28, 2025

Summary by CodeRabbit

  • New Features

    • Persist Stripe payment transactions and user coupons/discounts; webhook handling now records transactions and claims coupons idempotently.
    • Wallet top-ups integrate persisted transactions and automatic coupon consumption.
  • Chores

    • Database schema extended to support Stripe transactions and coupons.
  • Tests

    • Comprehensive unit tests for Stripe webhook flows.
    • New reusable webhook event seeders and updated seeder API for test data.

@baktun14 baktun14 requested a review from a team as a code owner August 28, 2025 10:06
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 28, 2025

Walkthrough

Adds Stripe transactions and coupons: DB migration and Drizzle snapshot, new Drizzle model schemas and repositories, StripeWebhookService extended to record payment-intent transactions and customer discounts, comprehensive unit tests, and test seeders for Stripe webhook events.

Changes

Cohort / File(s) Summary
Database migration & metadata
apps/api/drizzle/0019_robust_lady_ursula.sql, apps/api/drizzle/meta/0019_snapshot.json, apps/api/drizzle/meta/_journal.json
Creates stripe_transactions and stripe_coupons tables with UUID PKs, unique constraints, timestamps, JSON metadata, and FK references to public.userSetting(id); adds idempotent FK creation DO blocks; updates Drizzle snapshot and journal (version 7).
Model schemas
apps/api/src/billing/model-schemas/index.ts, apps/api/src/billing/model-schemas/stripe-transaction/stripe-transaction.schema.ts, apps/api/src/billing/model-schemas/stripe-coupon/stripe-coupon.schema.ts
Adds Drizzle pgTable definitions StripeTransactions and StripeCoupons with fields, relations to Users, type aliases, and re-exports in the barrel.
Repositories
apps/api/src/billing/repositories/index.ts, apps/api/src/billing/repositories/stripe-transaction/..., apps/api/src/billing/repositories/stripe-coupon/...
Introduces StripeTransactionRepository and StripeCouponRepository with DI, access-scoping (accessibleBy), and finder methods (findByStripeTransactionId, findByUserId); updates repository exports.
Stripe webhook service & tests
apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts, apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts
Injects new repositories into StripeWebhookService; extends routing to handle customer.discount.created; implements recordPaymentIntentTransaction and handleCustomerDiscountCreated; adds logging events; adds comprehensive Jest tests covering routing and handlers.
Test seeders
apps/api/test/seeders/index.ts, apps/api/test/seeders/stripe-webhook-events.seeder.ts, apps/api/test/seeders/stripe.seeder.ts
Adds webhook event seeder utilities and re-exports; introduces stripe-webhook-events seeder; changes Stripe seeder API from a free function to StripeSeeder.create() class-style factory and updates tests to use it.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Stripe as Stripe
  participant Webhook as StripeWebhookService
  participant Users as UserRepository
  participant TxRepo as StripeTransactionRepository
  participant CpRepo as StripeCouponRepository
  participant PMRepo as PaymentMethodRepository
  participant Checkout as CheckoutSessionRepository
  participant Refill as RefillService

  rect rgb(245,248,255)
  note over Stripe,Webhook: Event routing
  Stripe->>Webhook: webhook(event)
  alt checkout.session.completed / async_payment_succeeded
    Webhook->>Checkout: findBySessionId(...)
    Webhook->>Refill: topUpWallet(...)
    Webhook->>Checkout: deleteById(...)
  else payment_intent.succeeded
    Webhook->>Users: findByStripeCustomerId(...)
    Webhook->>TxRepo: findByStripeTransactionId(...)
    Webhook->>TxRepo: insert (if not exists)
    Webhook->>Refill: topUpWallet(...)
  else payment_method.attached/detached
    Webhook->>Users: findByStripeCustomerId(...)
    Webhook->>PMRepo: create/delete
  else customer.discount.created
    Webhook->>Users: findByStripeCustomerId(...)
    Webhook->>CpRepo: findByStripeCouponId(...)
    Webhook->>CpRepo: insert (if not exists)
  else unknown
    Webhook-->>Stripe: ignore
  end
  end
Loading
sequenceDiagram
  autonumber
  participant Webhook as StripeWebhookService
  participant TxRepo as StripeTransactionRepository

  rect rgb(245,255,245)
  note over Webhook,TxRepo: Record PaymentIntent Transaction
  Webhook->>TxRepo: findByStripeTransactionId(pi.id)
  alt exists
    Webhook-->>Webhook: log PAYMENT_INTENT_TRANSACTION_ALREADY_EXISTS
  else not found
    Webhook->>TxRepo: insert {stripeTransactionId, userId, amount, currency, status, description, metadata, stripeCreatedAt}
    Webhook-->>Webhook: log PAYMENT_INTENT_TRANSACTION_RECORDED
  end
  end
Loading
sequenceDiagram
  autonumber
  participant Webhook as StripeWebhookService
  participant Users as UserRepository
  participant CpRepo as StripeCouponRepository

  rect rgb(255,248,240)
  note over Webhook,CpRepo: Handle customer.discount.created
  Webhook->>Users: findByStripeCustomerId(discount.customer)
  alt user found
    Webhook->>CpRepo: findByStripeCouponId(discount.id)
    alt not exists
      Webhook->>CpRepo: insert {stripeCouponId, userId, couponCode, discountAmount, stripeCreatedAt}
      Webhook-->>Webhook: log DISCOUNT_CLAIMED_RECORDED
    else exists
      Webhook-->>Webhook: log DISCOUNT_ALREADY_EXISTS
    end
  else user missing
    Webhook-->>Webhook: log USER_NOT_FOUND_FOR_DISCOUNT
  end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

Possibly related PRs

Suggested reviewers

  • ygrishajev
  • stalniy

Poem

I thump my paws at Stripe’s new tune,
Coupons sprout and ledgers croon,
Webhooks hop from queue to queue,
Transactions logged, IDs true,
I nibble the merge and dance—hooray! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 822731a and b7857b5.

📒 Files selected for processing (1)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch features/add-stripe-transactions

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@baktun14 baktun14 force-pushed the features/add-stripe-transactions branch from 8cbff4d to 489f6ef Compare August 28, 2025 10:20
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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/api/src/billing/services/stripe/stripe.service.spec.ts (5)

550-578: Remove as any and keep Stripe types in tests.

These casts violate our TS guideline. Replace with typed objects and use the existing stub() helper to satisfy return types.

-          amount_off: 1000,
-          percent_off: null as any,
+          amount_off: 1000,
+          percent_off: null,
...
-jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(mockPromotionCode as any);
+jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(stub(mockPromotionCode));

580-599: Avoid as any on promotion-code path (percent-based).

Use null and stub() to keep strong types.

-          percent_off: 20,
-          amount_off: null as any,
+          percent_off: 20,
+          amount_off: null,
...
-jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(mockPromotionCode as any);
+jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(stub(mockPromotionCode));

636-650: Avoid as any on coupon path (no amount_off).

-          percent_off: null as any,
-          amount_off: null as any,
+          percent_off: null,
+          amount_off: null,
...
-jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(null as any);
+jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(null);
...
-jest.spyOn(service, "listCoupons").mockResolvedValue({ coupons: [mockCoupon] } as any);
+jest.spyOn(service, "listCoupons").mockResolvedValue(stub({ coupons: [mockCoupon] }));

618-635: Avoid as any on percent-based coupon path.

-        percent_off: 20,
-        amount_off: null as any,
+        percent_off: 20,
+        amount_off: null,
...
-jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(null as any);
+jest.spyOn(service, "findPromotionCodeByCode").mockResolvedValue(null);
-jest.spyOn(service, "listCoupons").mockResolvedValue({ coupons: [mockCoupon] } as any);
+jest.spyOn(service, "listCoupons").mockResolvedValue(stub({ coupons: [mockCoupon] }));

977-985: Move setup() inside the root describe(StripeService.name, …) block
Place the function declaration at the bottom of that block instead of outside it.

apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (1)

80-85: Guard against undefined amounts; prefer amount_total when available.

amount_subtotal can be undefined; using a non-null assertion risks runtime errors.

-    if (checkoutSession.payment_status !== "unpaid") {
-      await this.refillService.topUpWallet(checkoutSession.amount_subtotal!, checkoutSessionCache.userId);
+    if (checkoutSession.payment_status !== "unpaid") {
+      const amount = checkoutSession.amount_total ?? checkoutSession.amount_subtotal;
+      if (typeof amount !== "number") {
+        this.logger.error({ event: "CHECKOUT_AMOUNT_MISSING", sessionId });
+        return;
+      }
+      await this.refillService.topUpWallet(amount, checkoutSessionCache.userId);
       await this.checkoutSessionRepository.deleteBy({ sessionId });
🧹 Nitpick comments (5)
apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (5)

36-54: Log unhandled events to aid observability.

Add a default branch so new/unsupported event types are visible.

       case "customer.discount.created":
         await this.handleCustomerDiscountCreated(event);
         break;
+      default:
+        this.logger.info({
+          event: "STRIPE_EVENT_UNHANDLED",
+          type: event.type,
+          id: event.id
+        });
+        break;

27-34: Correct “objectId” logging; it currently logs the object type.

Log both objectType and actual object id (when present) to avoid confusion.

-    this.logger.info({
-      event: "STRIPE_EVENT_RECEIVED",
-      type: event.type,
-      id: event.id,
-      objectId: event.data.object.object
-    });
+    const objectInfo = event.data.object as unknown as { id?: string; object: string };
+    this.logger.info({
+      event: "STRIPE_EVENT_RECEIVED",
+      type: event.type,
+      id: event.id,
+      objectType: objectInfo.object,
+      objectId: objectInfo.id
+    });

310-316: Use Stripe event timestamp for coupon record.

new Date() stores “now”, not when Stripe created the event/object. Prefer event.created.

-      stripeCreatedAt: new Date()
+      stripeCreatedAt: new Date(event.created * 1000)

203-209: Avoid duplicate “PAYMENT_METHOD_DETACHED” log events.

Rename the initial info log to indicate receipt, keeping the later one for post-DB state.

-    this.logger.info({
-      event: "PAYMENT_METHOD_DETACHED",
+    this.logger.info({
+      event: "PAYMENT_METHOD_DETACHED_RECEIVED",
       paymentMethodId: paymentMethod.id,
       customerId,
       fingerprint
     });

111-143: Minimize external calls within DB transaction.

consumeActiveDiscount hits Stripe inside a @WithTransaction method, extending transaction time and risk of lock contention. Consider performing the Stripe call before starting the transaction or after persisting an idempotency gate.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ad3c5ac and 489f6ef.

📒 Files selected for processing (15)
  • apps/api/drizzle/0019_robust_lady_ursula.sql (1 hunks)
  • apps/api/drizzle/meta/0019_snapshot.json (1 hunks)
  • apps/api/drizzle/meta/_journal.json (1 hunks)
  • apps/api/src/billing/model-schemas/index.ts (1 hunks)
  • apps/api/src/billing/model-schemas/stripe-coupon/stripe-coupon.schema.ts (1 hunks)
  • apps/api/src/billing/model-schemas/stripe-transaction/stripe-transaction.schema.ts (1 hunks)
  • apps/api/src/billing/repositories/index.ts (1 hunks)
  • apps/api/src/billing/repositories/stripe-coupon/stripe-coupon.repository.ts (1 hunks)
  • apps/api/src/billing/repositories/stripe-transaction/stripe-transaction.repository.ts (1 hunks)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts (1 hunks)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (5 hunks)
  • apps/api/src/billing/services/stripe/stripe.service.spec.ts (15 hunks)
  • apps/api/test/seeders/index.ts (1 hunks)
  • apps/api/test/seeders/stripe-webhook-events.seeder.ts (1 hunks)
  • apps/api/test/seeders/stripe.seeder.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/api/drizzle/meta/0019_snapshot.json
🚧 Files skipped from review as they are similar to previous changes (10)
  • apps/api/src/billing/repositories/index.ts
  • apps/api/drizzle/0019_robust_lady_ursula.sql
  • apps/api/drizzle/meta/_journal.json
  • apps/api/src/billing/model-schemas/index.ts
  • apps/api/src/billing/repositories/stripe-transaction/stripe-transaction.repository.ts
  • apps/api/test/seeders/index.ts
  • apps/api/src/billing/repositories/stripe-coupon/stripe-coupon.repository.ts
  • apps/api/src/billing/model-schemas/stripe-coupon/stripe-coupon.schema.ts
  • apps/api/src/billing/model-schemas/stripe-transaction/stripe-transaction.schema.ts
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.spec.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/no-jest-mock.mdc)

Don't use jest.mock() to mock dependencies in test files. Instead, use jest-mock-extended to create mocks and pass mocks as dependencies to the service under test.

**/*.spec.{ts,tsx}: Use setup function instead of beforeEach in test files
setup function must be at the bottom of the root describe block in test files
setup function creates an object under test and returns it
setup function should accept a single parameter with inline type definition
Don't use shared state in setup function
Don't specify return type of setup function

Files:

  • apps/api/src/billing/services/stripe/stripe.service.spec.ts
**/*.{ts,tsx}

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

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/api/src/billing/services/stripe/stripe.service.spec.ts
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts
  • apps/api/test/seeders/stripe-webhook-events.seeder.ts
  • apps/api/test/seeders/stripe.seeder.ts
**/*.{js,ts,tsx}

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

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/api/src/billing/services/stripe/stripe.service.spec.ts
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts
  • apps/api/test/seeders/stripe-webhook-events.seeder.ts
  • apps/api/test/seeders/stripe.seeder.ts
🧬 Code graph analysis (2)
apps/api/src/billing/services/stripe/stripe.service.spec.ts (1)
apps/api/test/seeders/stripe.seeder.ts (1)
  • StripeSeeder (11-212)
apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (1)
apps/api/src/core/services/tx/tx.service.ts (1)
  • WithTransaction (33-45)
⏰ 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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
🔇 Additional comments (5)
apps/api/test/seeders/stripe.seeder.ts (1)

11-211: Seeder API looks good; types are precise and data covers common paths.

Class-based API with typed return is clear. No blocking issues.

apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (4)

312-315: Coupon fields likely misnamed; store identifiers correctly and include currency.

couponCode is set to coupon.id (an internal id, not a human-facing code). If you want the public code, use promotion_code (and retrieve for .code), else rename to couponId/promotionCodeId. Also consider persisting currency for discountAmount.

Would you like me to adjust repository/schema and handler to:

  • store couponId: discount.coupon.id
  • store promotionCodeId: discount.promotion_code ?? null
  • store discountCurrency: discount.coupon.currency (when amount_off is set)
    and backfill tests accordingly?

51-53: Event routing addition looks good.

customer.discount.created is correctly routed to the new handler.


5-5: Wiring of repositories is consistent.

Constructor injection and imports for StripeTransactionRepository and StripeCouponRepository look correct.

Also applies to: 22-24


112-116: All amount units align. RefillService.topUpWallet expects cents (per its JSDoc), and paymentIntent.amount, metadata-derived originalAmount (fallback to amount), and checkoutSession.amount_subtotal are all provided in the smallest currency unit (cents) (docs.stripe.com)

@codecov
Copy link

codecov bot commented Aug 28, 2025

Codecov Report

❌ Patch coverage is 75.28090% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 43.96%. Comparing base (5090f75) to head (b7857b5).
⚠️ Report is 26 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
...sitories/stripe-coupon/stripe-coupon.repository.ts 52.63% 9 Missing ⚠️
...tripe-transaction/stripe-transaction.repository.ts 52.63% 9 Missing ⚠️
.../services/stripe-webhook/stripe-webhook.service.ts 94.87% 2 Missing ⚠️
...odel-schemas/stripe-coupon/stripe-coupon.schema.ts 83.33% 1 Missing ⚠️
...as/stripe-transaction/stripe-transaction.schema.ts 83.33% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (75.28%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1864      +/-   ##
==========================================
+ Coverage   43.65%   43.96%   +0.31%     
==========================================
  Files         962      966       +4     
  Lines       27104    27190      +86     
  Branches     7029     7038       +9     
==========================================
+ Hits        11832    11954     +122     
- Misses      14887    14936      +49     
+ Partials      385      300      -85     
Flag Coverage Δ *Carryforward flag
api 81.92% <75.28%> (+0.68%) ⬆️
deploy-web 21.18% <ø> (ø) Carriedforward from 822731a
log-collector 75.35% <ø> (ø)
notifications 87.92% <ø> (ø) Carriedforward from 822731a
provider-console 81.48% <ø> (ø) Carriedforward from 822731a
provider-proxy 84.37% <ø> (ø) Carriedforward from 822731a

*This pull request uses carry forward flags. Click here to find out more.

Files with missing lines Coverage Δ
...odel-schemas/stripe-coupon/stripe-coupon.schema.ts 83.33% <83.33%> (ø)
...as/stripe-transaction/stripe-transaction.schema.ts 83.33% <83.33%> (ø)
.../services/stripe-webhook/stripe-webhook.service.ts 92.14% <94.87%> (+54.64%) ⬆️
...sitories/stripe-coupon/stripe-coupon.repository.ts 52.63% <52.63%> (ø)
...tripe-transaction/stripe-transaction.repository.ts 52.63% <52.63%> (ø)

... and 32 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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: 4

🧹 Nitpick comments (2)
apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (2)

51-53: Add handlers for related discount lifecycle events.

Consider also handling customer.discount.deleted and customer.discount.updated to keep stored discounts in sync.


219-263: Duplicate log event names for detach flow.

You log PAYMENT_METHOD_DETACHED at Line 225 and again at Line 259 for different stages. Rename the first to PAYMENT_METHOD_DETACH_RECEIVED (or similar) for clarity.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 489f6ef and 822731a.

📒 Files selected for processing (3)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts (1 hunks)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (5 hunks)
  • apps/api/test/seeders/stripe-webhook-events.seeder.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.spec.ts
  • apps/api/test/seeders/stripe-webhook-events.seeder.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

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

Never use type any or cast to type any. Always define the proper TypeScript types.

Files:

  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts
**/*.{js,ts,tsx}

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

**/*.{js,ts,tsx}: Never use deprecated methods from libraries.
Don't add unnecessary comments to the code

Files:

  • apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.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). (2)
  • GitHub Check: validate / validate-app
  • GitHub Check: test-build
🔇 Additional comments (1)
apps/api/src/billing/services/stripe-webhook/stripe-webhook.service.ts (1)

5-5: Repository imports wiring — LGTM.

Imports for the new repositories look correct and consistent with the folder structure.

Comment on lines +268 to +279
const existingTransaction = await this.stripeTransactionRepository.findByStripeTransactionId(paymentIntent.id);
if (existingTransaction) {
this.logger.info({
event: "PAYMENT_INTENT_TRANSACTION_ALREADY_EXISTS",
paymentIntentId: paymentIntent.id,
userId
});
return false;
}

await this.stripeTransactionRepository.create({
stripeTransactionId: paymentIntent.id,
Copy link
Contributor

Choose a reason for hiding this comment

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

thought(non-blocking): this doesn't save from race condition, so better to rely on insert on conflict ignore or insert on conflict update

Comment on lines +323 to +339
const existingCoupon = await this.stripeCouponRepository.findByStripeCouponId(discount.id);
if (existingCoupon) {
this.logger.info({
event: "DISCOUNT_ALREADY_EXISTS",
discountId: discount.id,
userId: user.id
});
return;
}

await this.stripeCouponRepository.create({
stripeCouponId: discount.id,
userId: user.id,
couponCode: discount.coupon?.id,
discountAmount: discount.coupon?.amount_off ? discount.coupon.amount_off.toString() : null,
stripeCreatedAt: new Date()
});
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion(non-blocking): I can't predict consequences but this also can be affected by race condition. So, better to rely on unique key constraint in db

@baktun14 baktun14 closed this Sep 15, 2025
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.

2 participants

Comments