Skip to content

Include partner info in "New customer" lead webhook#3875

Open
pepeladeira wants to merge 1 commit into
mainfrom
stripe-webhook-new-customer-partner-slack
Open

Include partner info in "New customer" lead webhook#3875
pepeladeira wants to merge 1 commit into
mainfrom
stripe-webhook-new-customer-partner-slack

Conversation

@pepeladeira
Copy link
Copy Markdown
Collaborator

@pepeladeira pepeladeira commented May 8, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved customer data handling with fallback logic for missing customer names.
  • Chores

    • Enhanced webhook dispatch to include partner information when available, improving partner integration data accuracy.
    • Refactored internal helper functions for better code modularity.

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented May 8, 2026

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

Project Deployment Actions Updated (UTC)
dub Ready Ready Preview May 8, 2026 8:12pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 8, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

The PR enhances Stripe webhook handling to include partner context in lead events. A utility function for constructing partner objects is exported, imported into the webhook handler, and integrated into the "lead.created" event dispatch flow. Customer naming fallback logic is also refined to prefer email before random name generation.

Changes

Lead Webhook Partner Context Enhancement

Layer / File(s) Summary
Export Partner Constructor
apps/web/lib/partners/create-partner-commission.ts
constructWebhookPartner is exported, making it available for cross-module use in webhook handlers.
Webhook Handler Enhancement
apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
Import constructWebhookPartner; refactor "lead.created" dispatch to conditionally fetch programEnrollment, construct optional webhookPartner, pass partner into transformLeadEventData, and execute delivery via async IIFE with waitUntil.
Customer Name Fallback
apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
Customer name field now falls back to stripeCustomer.email before generateRandomName().

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A partner awakens within the webhook's dance,
Where leads and enrollment exchange their sweet prance,
Email as Name when the stripe has no call,
Now every webhook enriches them all! 🌟

🚥 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: including partner information in the webhook for new customers created via Stripe integration.
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 stripe-webhook-new-customer-partner-slack

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

@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

🧹 Nitpick comments (1)
apps/web/lib/partners/create-partner-commission.ts (1)

48-62: ⚡ Quick win

Extract constructWebhookPartner into a standalone helper.

Making this mapper public from create-partner-commission.ts means the Stripe webhook path now depends on the entire commission-creation module. A small shared helper file would avoid pulling audit/workflow/commission-only imports into that path and keep the boundary cleaner.

🤖 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/web/lib/partners/create-partner-commission.ts` around lines 48 - 62, The
constructWebhookPartner mapper is currently exported from
create-partner-commission.ts which pulls heavy commission/audit/workflow imports
into the Stripe webhook path; extract constructWebhookPartner into a small
standalone helper module (e.g., a new file exporting a named function
constructWebhookPartner) that only depends on ProgramEnrollment, Partner, Link,
aggregatePartnerLinksStats and toCentsNumber types/utilities, move the
implementation there, export it, then update all callers (including the Stripe
webhook handler) to import constructWebhookPartner from the new helper instead
of create-partner-commission; preserve the exact function signature and behavior
(including totalCommissionsParam handling) and ensure the helper has no
commission/audit/workflow imports so the webhook path no longer pulls those
modules.
🤖 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/web/app/`(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts:
- Around line 149-168: The prisma.programEnrollment.findUnique lookup used to
build webhookPartner can reject and block the Promise.allSettled that runs
sendWorkspaceWebhook and sendPartnerPostback; change the programEnrollment fetch
(the call to prisma.programEnrollment.findUnique) to handle errors (e.g., append
.catch(() => null) or try/catch) so it returns null on failure, then pass the
possibly-null result into constructWebhookPartner as before; this ensures
webhookPartner resolution won't throw and allows Promise.allSettled (which calls
sendWorkspaceWebhook and sendPartnerPostback) to run regardless of enrichment
failures.

---

Nitpick comments:
In `@apps/web/lib/partners/create-partner-commission.ts`:
- Around line 48-62: The constructWebhookPartner mapper is currently exported
from create-partner-commission.ts which pulls heavy commission/audit/workflow
imports into the Stripe webhook path; extract constructWebhookPartner into a
small standalone helper module (e.g., a new file exporting a named function
constructWebhookPartner) that only depends on ProgramEnrollment, Partner, Link,
aggregatePartnerLinksStats and toCentsNumber types/utilities, move the
implementation there, export it, then update all callers (including the Stripe
webhook handler) to import constructWebhookPartner from the new helper instead
of create-partner-commission; preserve the exact function signature and behavior
(including totalCommissionsParam handling) and ensure the helper has no
commission/audit/workflow imports so the webhook path no longer pulls those
modules.
🪄 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: 025e982c-ccd2-4c9f-b2f7-60a2e989ecc3

📥 Commits

Reviewing files that changed from the base of the PR and between a5fa025 and 56b02ee.

📒 Files selected for processing (2)
  • apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
  • apps/web/lib/partners/create-partner-commission.ts

Comment on lines +149 to +168
(async () => {
const programEnrollment =
link.programId && link.partnerId
? await prisma.programEnrollment.findUnique({
where: {
partnerId_programId: {
partnerId: link.partnerId,
programId: link.programId,
},
},
include: {
partner: true,
links: true,
},
}),
]
: []),
]),
})
: null;

const webhookPartner = programEnrollment
? constructWebhookPartner(programEnrollment)
: undefined;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Don't let partner enrichment block lead webhooks.

The await prisma.programEnrollment.findUnique(...) call at lines 150–167 lacks error handling and blocks the Promise.allSettled(...) block containing both sendWorkspaceWebhook() and sendPartnerPostback(). If the lookup rejects, neither webhook runs, turning optional partner enrichment into a hard dependency for all lead notifications on partner links.

Wrap the lookup in .catch() to return null on failure and let the webhooks proceed:

Suggested fix
       const programEnrollment =
         link.programId && link.partnerId
           ? await prisma.programEnrollment
+              .findUnique(...)
+              .catch((error) => {
+                console.error(
+                  "Failed to load program enrollment for lead webhook partner context",
+                  error,
+                );
+                return null;
+              })
-              .findUnique(...)
           : null;
🤖 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/web/app/`(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts
around lines 149 - 168, The prisma.programEnrollment.findUnique lookup used to
build webhookPartner can reject and block the Promise.allSettled that runs
sendWorkspaceWebhook and sendPartnerPostback; change the programEnrollment fetch
(the call to prisma.programEnrollment.findUnique) to handle errors (e.g., append
.catch(() => null) or try/catch) so it returns null on failure, then pass the
possibly-null result into constructWebhookPartner as before; this ensures
webhookPartner resolution won't throw and allows Promise.allSettled (which calls
sendWorkspaceWebhook and sendPartnerPostback) to run regardless of enrichment
failures.

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