Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@devkiran
Copy link
Collaborator

@devkiran devkiran commented Jul 9, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new webhook event for "commission.created" with enriched commission data.
    • Added a Slack notification template for commission creation events.
    • Enhanced commission creation to trigger webhooks including related partner and customer details.
  • Improvements

    • Standardized and enriched commission data in API responses and documentation.
    • Updated type definitions and schemas for consistency across webhooks and APIs.
    • Improved validation and error messaging for partner-related webhook triggers.
  • Documentation

    • Added a sample webhook payload for "commission.created" events.
  • Refactor

    • Simplified and unified webhook trigger handling and type naming conventions.
    • Streamlined webhook trigger filtering logic in the user interface.
  • Chores

    • Added an optional user tracking field to commissions for manual creation.
    • Added guard clause to prevent errors in commission type icon rendering.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 9, 2025

Walkthrough

This update introduces the "commission.created" webhook event, enriching commission-related API responses and webhook payloads with additional partner and customer data. It standardizes and renames types and schemas across the codebase, updates Slack and Segment integration templates, adjusts validation logic for partner-related webhooks, and modifies the Prisma schema to include the commission creator's user ID. It also removes the workspaceId parameter from commission creation calls and enhances webhook trigger validation to cover multiple partner-related events.

Changes

File(s) / Path(s) Change Summary
.../api/commissions/[commissionId]/route.ts, .../api/commissions/route.ts Updated commission API endpoints to use CommissionEnrichedSchema for richer response validation.
.../lib/openapi/commissions/list-commissions.ts, .../update-commission.ts Changed OpenAPI response schemas from CommissionSchema to CommissionEnrichedSchema.
.../lib/types.ts, .../tests/commissions/index.test.ts Updated type aliases to infer from CommissionEnrichedSchema instead of CommissionResponseSchema.
.../lib/zod/schemas/commissions.ts Renamed exported schema to CommissionEnrichedSchema and clarified its usage in comments; added fields.
.../lib/partners/create-partner-commission.ts Added webhook notification on commission creation; included userId and enriched commission data; removed workspaceId.
.../lib/webhook/schemas.ts Added webhook event schema for "commission.created" using CommissionEnrichedSchema.
.../lib/webhook/types.ts Consolidated and standardized webhook payload types; added support for commission events.
.../lib/webhook/constants.ts Added PARTNERS_WEBHOOK_TRIGGERS and included "commission.created" in relevant constants.
.../lib/webhook/publish.ts, .../qstash.ts Unified webhook event payload types to use WebhookEventPayload.
.../lib/webhook/create-webhook.ts, .../api/webhooks/[webhookId]/route.ts Generalized partner trigger validation to use PARTNERS_WEBHOOK_TRIGGERS.
.../ui/webhooks/add-edit-webhook-form.tsx Refactored trigger filtering logic to use PARTNERS_WEBHOOK_TRIGGERS.
.../lib/integrations/segment/transform.ts, .../slack/transform.ts Updated event transformation and Slack template functions to new payload types; added commission template.
.../lib/webhook/sample-events/commission-created.json Added sample JSON payload for "commission.created" webhook event.
.../lib/webhook/sample-events/payload.ts Registered sample payload for "commission.created" event.
.../tests/webhooks/index.test.ts Added extended schema and event mapping for "commission.created" in webhook tests.
packages/prisma/schema/commission.prisma Added optional userId to the Commission model for manual commission tracking.
.../lib/actions/partners/create-clawback.ts, .../create-commission.ts Removed workspaceId parameter from calls to createPartnerCommission.
.../app/(ee)/api/embed/referrals/earnings/route.ts Modified commission earnings query to include nested relations without explicit commission field selection.
.../lib/zod/schemas/partner-profile.ts Updated PartnerEarningsSchema to omit certain fields and remove redundant merged fields.
.../ui/partners/comission-type-icon.tsx Added guard clause to prevent errors when type prop is falsy in CommissionTypeIcon component.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant API
    participant DB
    participant WebhookService

    User->>API: Create manual commission
    API->>DB: Insert commission (with userId)
    DB-->>API: Return enriched commission (with partner & customer)
    API->>WebhookService: Send "commission.created" webhook with enriched data
    WebhookService-->>External: Deliver webhook payload
Loading
sequenceDiagram
    participant API
    participant WebhookConfig
    participant Workspace

    API->>WebhookConfig: Validate webhook triggers (PATCH/CREATE)
    WebhookConfig->>Workspace: Check if partners feature is enabled
    alt Any trigger in PARTNERS_WEBHOOK_TRIGGERS and partners not enabled
        WebhookConfig-->>API: Throw error listing required triggers
    else No restricted triggers or partners enabled
        WebhookConfig-->>API: Allow webhook configuration
    end
Loading

Possibly related PRs

  • Partners audit logs #2610: Introduces broad audit logging for partner-related actions including commissions, related by audit integration but does not modify commission API routes or webhook schemas directly.

Poem

Hopping through code with a twitch of my nose,
A new commission event—watch how it grows!
Webhooks now richer, with partners in tow,
User IDs tracked, and schemas in flow.
With every new trigger, this bunny’s delight—
The code garden blooms, all carrots in sight! 🥕


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df42d01 and 45faa7d.

📒 Files selected for processing (1)
  • apps/web/lib/actions/partners/create-commission.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/lib/actions/partners/create-commission.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). (1)
  • GitHub Check: build
✨ 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
🪧 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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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

Documentation and Community

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

@vercel
Copy link
Contributor

vercel bot commented Jul 9, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
dub ✅ Ready (Inspect) Visit Preview Jul 16, 2025 2:20pm

…ls in webhook data and validate with CommissionResponseSchema
…e customer and partner details in the response
@devkiran devkiran marked this pull request as ready for review July 10, 2025 12:46
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

🔭 Outside diff range comments (1)
apps/web/tests/commissions/index.test.ts (1)

37-37: Ensure GET /commissions returns HTTP 200 for valid queries

All tests in apps/web/tests/commissions/index.test.ts currently assert:

  • expect(status).toEqual(200)
  • No tests expect a 500 response

The pipeline failure indicates the endpoint is returning 500 on a valid filtered request. Please:

• Inspect the GET /commissions handler (e.g. in your server’s routes/controllers) to ensure it returns 200 for successful queries using the provided status, sortBy, and sortOrder parameters.
• If this PR intentionally changes the status code for certain conditions, update the tests in apps/web/tests/commissions/index.test.ts to reflect the new expected behavior.
• Otherwise, fix any logic errors causing the 500 so that valid requests pass with a 200 status.

🧹 Nitpick comments (2)
apps/web/lib/openapi/commissions/update-commission.ts (1)

6-6: Remove duplicate import of CommissionSchema.

There's a duplicate import of CommissionSchema on line 6 that's also imported from the same file in the updated import statement (lines 1-4).

-import { CommissionSchema } from "../../zod/schemas/commissions";
apps/web/lib/integrations/slack/transform.ts (1)

237-282: Consider enhancing the commission template with additional information.

The commission template implementation is correct and follows the established pattern. However, consider the following enhancements:

  1. Missing partner/customer context: According to the AI summary, the CommissionEnrichedSchema includes additional partner and customer data that could provide valuable context in the Slack notification.

  2. No "View on Dub" link: Unlike other templates, this one doesn't include a link to view the commission details in the Dub dashboard.

Consider adding partner information and a dashboard link:

const commissionCreatedTemplate = ({
  data,
}: {
  data: CommissionEventWebhookPayload;
}) => {
- const { id, amount, earnings } = data;
+ const { id, amount, earnings, partner, customer } = data;

  const formattedAmount = currencyFormatter(amount / 100, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

  const formattedEarnings = currencyFormatter(earnings / 100, {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

+ const linkToCommission = `${APP_DOMAIN}/commissions?id=${id}`;

  return {
    blocks: [
      {
        type: "section",
        text: {
          type: "mrkdwn",
          text: `*New commission created* :tada:`,
        },
      },
      {
        type: "section",
        fields: [
          {
            type: "mrkdwn",
            text: `*Commission ID*\n${id}`,
          },
          {
            type: "mrkdwn",
            text: `*Amount*\n${formattedAmount}`,
          },
          {
            type: "mrkdwn",
            text: `*Earnings*\n${formattedEarnings}`,
          },
+         ...(partner && {
+           type: "mrkdwn",
+           text: `*Partner*\n${partner.name}`,
+         }),
        ],
      },
+     {
+       type: "context",
+       elements: [
+         {
+           type: "mrkdwn",
+           text: `<${linkToCommission}|View on Dub>`,
+         },
+       ],
+     },
    ],
  };
};
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a0cf62 and 8dcebfb.

📒 Files selected for processing (22)
  • apps/web/app/(ee)/api/commissions/[commissionId]/route.ts (3 hunks)
  • apps/web/app/(ee)/api/commissions/route.ts (2 hunks)
  • apps/web/app/api/webhooks/[webhookId]/route.ts (2 hunks)
  • apps/web/lib/integrations/segment/transform.ts (5 hunks)
  • apps/web/lib/integrations/slack/transform.ts (7 hunks)
  • apps/web/lib/openapi/commissions/list-commissions.ts (2 hunks)
  • apps/web/lib/openapi/commissions/update-commission.ts (2 hunks)
  • apps/web/lib/partners/create-partner-commission.ts (4 hunks)
  • apps/web/lib/types.ts (2 hunks)
  • apps/web/lib/webhook/constants.ts (2 hunks)
  • apps/web/lib/webhook/create-webhook.ts (2 hunks)
  • apps/web/lib/webhook/publish.ts (2 hunks)
  • apps/web/lib/webhook/qstash.ts (2 hunks)
  • apps/web/lib/webhook/sample-events/commission-created.json (1 hunks)
  • apps/web/lib/webhook/sample-events/payload.ts (2 hunks)
  • apps/web/lib/webhook/schemas.ts (2 hunks)
  • apps/web/lib/webhook/types.ts (2 hunks)
  • apps/web/lib/zod/schemas/commissions.ts (1 hunks)
  • apps/web/tests/commissions/index.test.ts (1 hunks)
  • apps/web/tests/webhooks/index.test.ts (2 hunks)
  • apps/web/ui/webhooks/add-edit-webhook-form.tsx (2 hunks)
  • packages/prisma/schema/commission.prisma (1 hunks)
🧰 Additional context used
🧠 Learnings (8)
apps/web/app/(ee)/api/commissions/[commissionId]/route.ts (1)
Learnt from: TWilson023
PR: dubinc/dub#2538
File: apps/web/ui/partners/overview/blocks/commissions-block.tsx:16-27
Timestamp: 2025-06-18T20:26:25.177Z
Learning: In the Dub codebase, components that use workspace data (workspaceId, defaultProgramId) are wrapped in `WorkspaceAuth` which ensures these values are always available, making non-null assertions safe. This is acknowledged as a common pattern in their codebase, though not ideal.
apps/web/lib/webhook/create-webhook.ts (1)
Learnt from: devkiran
PR: dubinc/dub#2177
File: apps/web/lib/api/links/bulk-create-links.ts:66-84
Timestamp: 2025-06-06T07:59:03.120Z
Learning: In apps/web/lib/api/links/bulk-create-links.ts, the team accepts the risk of potential undefined results from links.find() operations when building invalidLinks arrays, because existing links are fetched from the database based on the input links, so matches are expected to always exist.
apps/web/app/(ee)/api/commissions/route.ts (1)
Learnt from: TWilson023
PR: dubinc/dub#2538
File: apps/web/ui/partners/overview/blocks/commissions-block.tsx:16-27
Timestamp: 2025-06-18T20:26:25.177Z
Learning: In the Dub codebase, components that use workspace data (workspaceId, defaultProgramId) are wrapped in `WorkspaceAuth` which ensures these values are always available, making non-null assertions safe. This is acknowledged as a common pattern in their codebase, though not ideal.
apps/web/lib/openapi/commissions/list-commissions.ts (1)
Learnt from: devkiran
PR: dubinc/dub#2433
File: apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts:74-76
Timestamp: 2025-05-29T09:47:33.583Z
Learning: When Zod enum validation is used (e.g., `z.enum(PAYMENT_METHOD_TYPES)`), it ensures the validated value is one of the valid enum values, making subsequent type casts to the corresponding TypeScript types safe without additional validation.
apps/web/app/api/webhooks/[webhookId]/route.ts (1)
Learnt from: steven-tey
PR: dubinc/dub#0
File: :0-0
Timestamp: 2025-06-19T01:46:45.723Z
Learning: PayPal webhook verification in the Dub codebase is handled at the route level in `apps/web/app/(ee)/api/paypal/webhook/route.ts` using the `verifySignature` function. Individual webhook handlers like `payoutsItemFailed` don't need to re-verify signatures since they're only called after successful verification.
apps/web/lib/webhook/constants.ts (3)
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:0-0
Timestamp: 2025-05-29T04:45:18.504Z
Learning: In the PartnerProgramSummary email template (packages/email/src/templates/partner-program-summary.tsx), the stat titles are hardcoded constants ("Clicks", "Leads", "Sales", "Earnings") that will always match the ICONS object keys after toLowerCase() conversion, so icon lookup failures are not possible.
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:254-254
Timestamp: 2025-05-29T04:49:42.842Z
Learning: In the Dub codebase, it's acceptable to keep `partners.dub.co` hardcoded rather than making it configurable for different environments.
Learnt from: steven-tey
PR: dubinc/dub#0
File: :0-0
Timestamp: 2025-06-19T01:46:45.723Z
Learning: PayPal webhook verification in the Dub codebase is handled at the route level in `apps/web/app/(ee)/api/paypal/webhook/route.ts` using the `verifySignature` function. Individual webhook handlers like `payoutsItemFailed` don't need to re-verify signatures since they're only called after successful verification.
apps/web/lib/integrations/segment/transform.ts (1)
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:0-0
Timestamp: 2025-05-29T04:45:18.504Z
Learning: In the PartnerProgramSummary email template (packages/email/src/templates/partner-program-summary.tsx), the stat titles are hardcoded constants ("Clicks", "Leads", "Sales", "Earnings") that will always match the ICONS object keys after toLowerCase() conversion, so icon lookup failures are not possible.
apps/web/lib/integrations/slack/transform.ts (2)
Learnt from: devkiran
PR: dubinc/dub#2448
File: packages/email/src/templates/partner-program-summary.tsx:0-0
Timestamp: 2025-05-29T04:45:18.504Z
Learning: In the PartnerProgramSummary email template (packages/email/src/templates/partner-program-summary.tsx), the stat titles are hardcoded constants ("Clicks", "Leads", "Sales", "Earnings") that will always match the ICONS object keys after toLowerCase() conversion, so icon lookup failures are not possible.
Learnt from: steven-tey
PR: dubinc/dub#0
File: :0-0
Timestamp: 2025-06-19T01:46:45.723Z
Learning: PayPal webhook verification in the Dub codebase is handled at the route level in `apps/web/app/(ee)/api/paypal/webhook/route.ts` using the `verifySignature` function. Individual webhook handlers like `payoutsItemFailed` don't need to re-verify signatures since they're only called after successful verification.
🧬 Code Graph Analysis (16)
apps/web/lib/types.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/app/(ee)/api/commissions/[commissionId]/route.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/ui/webhooks/add-edit-webhook-form.tsx (1)
apps/web/lib/webhook/constants.ts (1)
  • PARTNERS_WEBHOOK_TRIGGERS (12-15)
apps/web/lib/webhook/create-webhook.ts (1)
apps/web/lib/webhook/constants.ts (1)
  • PARTNERS_WEBHOOK_TRIGGERS (12-15)
apps/web/app/(ee)/api/commissions/route.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/webhook/qstash.ts (1)
apps/web/lib/webhook/types.ts (1)
  • WebhookEventPayload (26-32)
apps/web/tests/commissions/index.test.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/openapi/commissions/update-commission.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/openapi/commissions/list-commissions.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/webhook/publish.ts (1)
apps/web/lib/webhook/types.ts (1)
  • WebhookEventPayload (26-32)
apps/web/app/api/webhooks/[webhookId]/route.ts (2)
apps/web/lib/webhook/constants.ts (1)
  • PARTNERS_WEBHOOK_TRIGGERS (12-15)
apps/web/lib/api/errors.ts (1)
  • DubApiError (75-92)
apps/web/tests/webhooks/index.test.ts (1)
apps/web/lib/zod/schemas/partners.ts (1)
  • EnrolledPartnerSchema (221-285)
apps/web/lib/partners/create-partner-commission.ts (4)
apps/web/lib/auth/utils.ts (1)
  • Session (6-16)
apps/web/lib/api/partners/sync-total-commissions.ts (1)
  • syncTotalCommissions (4-35)
apps/web/lib/webhook/publish.ts (1)
  • sendWorkspaceWebhook (7-36)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/webhook/schemas.ts (1)
apps/web/lib/zod/schemas/commissions.ts (1)
  • CommissionEnrichedSchema (25-31)
apps/web/lib/integrations/segment/transform.ts (1)
apps/web/lib/webhook/types.ts (4)
  • ClickEventWebhookPayload (14-14)
  • LeadEventWebhookPayload (16-16)
  • SaleEventWebhookPayload (18-18)
  • PartnerEventWebhookPayload (20-20)
apps/web/lib/integrations/slack/transform.ts (2)
apps/web/lib/webhook/types.ts (5)
  • ClickEventWebhookPayload (14-14)
  • LeadEventWebhookPayload (16-16)
  • SaleEventWebhookPayload (18-18)
  • PartnerEventWebhookPayload (20-20)
  • CommissionEventWebhookPayload (22-24)
packages/utils/src/functions/currency-formatter.ts (1)
  • currencyFormatter (1-11)
🪛 GitHub Actions: Public API Tests
apps/web/tests/commissions/index.test.ts

[error] 37-37: Test failure: expected HTTP status 500 but received 200. AssertionError at line 37: expected 500 to deeply equal 200.

🔇 Additional comments (48)
apps/web/lib/webhook/sample-events/payload.ts (2)

2-2: LGTM! Sample payload import added correctly.

The import follows the consistent pattern used for other webhook event sample payloads.


19-19: LGTM! Commission created event mapping added.

The mapping correctly associates the "commission.created" webhook trigger with its sample payload, consistent with other webhook events in the object.

packages/prisma/schema/commission.prisma (1)

34-34: LGTM! User tracking field added appropriately.

The optional userId field is well-positioned and documented. Making it optional ensures backwards compatibility with existing commission records.

apps/web/lib/types.ts (2)

26-26: LGTM! Schema import updated to use enriched commission data.

The change from CommissionResponseSchema to CommissionEnrichedSchema aligns with the broader refactor to provide richer commission data including partner and customer information.


386-386: LGTM! Type alias updated consistently.

The CommissionResponse type now correctly uses CommissionEnrichedSchema, maintaining type safety while providing access to the enriched commission data structure.

apps/web/lib/webhook/qstash.ts (2)

12-12: LGTM! Webhook event payload import updated.

The change from EventDataProps to WebhookEventPayload aligns with the unified webhook event payload type system, improving type consistency across webhook handling.


23-23: LGTM! Function parameter type updated consistently.

The data parameter type correctly uses WebhookEventPayload, which is a union type that includes the new commission event payload alongside existing webhook event types.

apps/web/lib/openapi/commissions/list-commissions.ts (2)

4-4: LGTM! OpenAPI schema import updated to use enriched commission data.

The change from CommissionSchema to CommissionEnrichedSchema aligns with the broader refactor to provide richer commission data including partner and customer information in API responses.


22-22: LGTM! Response schema enriched with additional commission data.

The API response now returns an array of CommissionEnrichedSchema objects, providing consumers with richer commission data including partner and customer information alongside the core commission fields.

apps/web/lib/zod/schemas/commissions.ts (1)

24-31: LGTM! Schema rename and documentation improve clarity.

The rename from CommissionResponseSchema to CommissionEnrichedSchema better reflects the enriched nature of the data structure, and the descriptive comment clearly explains its usage context for webhooks and API responses.

apps/web/app/(ee)/api/commissions/route.ts (2)

5-5: LGTM! Import updated to use renamed schema.

The import correctly uses the renamed CommissionEnrichedSchema which aligns with the schema changes.


69-69: LGTM! Response validation updated consistently.

The response validation correctly uses CommissionEnrichedSchema which matches the data structure returned by the query (including customer and partner relations).

apps/web/tests/commissions/index.test.ts (2)

1-1: LGTM! Import updated to use renamed schema.

The import correctly uses the renamed CommissionEnrichedSchema which aligns with the schema changes across the codebase.


6-6: LGTM! Type inference updated consistently.

The type inference correctly uses CommissionEnrichedSchema which provides a more complete type definition including partner and customer data.

apps/web/lib/openapi/commissions/update-commission.ts (2)

1-4: LGTM! Import updated to include enriched schema.

The import correctly adds CommissionEnrichedSchema for use in the response schema.


30-30: LGTM! Response schema updated to use enriched schema.

The response schema correctly uses CommissionEnrichedSchema which provides a more complete commission data structure including partner and customer information.

apps/web/ui/webhooks/add-edit-webhook-form.tsx (2)

8-8: LGTM! Import updated to use partner webhook triggers constant.

The import correctly adds PARTNERS_WEBHOOK_TRIGGERS which supports the refactored filtering logic.


123-127: LGTM! Improved webhook trigger filtering logic.

The refactored filtering logic is more maintainable and extensible:

  • Uses the PARTNERS_WEBHOOK_TRIGGERS constant instead of hardcoded string comparison
  • Supports multiple partner-related webhook triggers (like the new "commission.created" event)
  • Maintains the same conditional logic while being more scalable
apps/web/app/(ee)/api/commissions/[commissionId]/route.ts (3)

11-11: Good schema upgrade for enriched commission data.

The switch to CommissionEnrichedSchema aligns with the broader enhancement to provide richer commission data including partner and customer information.


122-125: Proper inclusion of related entities.

The addition of customer and partner includes ensures the updated commission object contains the necessary related data for the enriched schema validation.


185-185: Consistent schema validation in response.

The use of CommissionEnrichedSchema.parse() ensures the API response meets the expected enriched data structure, providing consistency with the broader commission enhancement.

apps/web/lib/webhook/create-webhook.ts (2)

4-7: Good addition of centralized partner trigger constants.

Adding PARTNERS_WEBHOOK_TRIGGERS to the import improves maintainability by centralizing the list of partner-related triggers.


35-43: Excellent generalization of partner trigger validation.

The change from checking a single trigger to using PARTNERS_WEBHOOK_TRIGGERS.some() makes the code more maintainable and extensible. This approach automatically supports new partner-related triggers (like "commission.created") without requiring code changes here.

apps/web/app/api/webhooks/[webhookId]/route.ts (2)

7-7: Consistent import of partner trigger constants.

Good consistency with the pattern established in other webhook-related files.


129-141: Excellent generalization with improved error messaging.

The change from checking a single trigger to using PARTNERS_WEBHOOK_TRIGGERS.some() is consistent with other webhook validation logic. The updated error message that lists all partner triggers provides better user feedback than the previous single-trigger message.

apps/web/lib/webhook/publish.ts (2)

4-4: Good consolidation of webhook event types.

The switch to a unified WebhookEventPayload type simplifies the imports and makes the code more maintainable.


14-14: Cleaner type definition with unified payload type.

Using WebhookEventPayload as a single union type is cleaner than the previous union of multiple specific types, while maintaining the same type safety.

apps/web/tests/webhooks/index.test.ts (1)

60-60: Event schema registration looks correct.

The registration of the commission webhook event schema in the eventSchemas record is properly structured, pending the schema definition fix above.

apps/web/lib/webhook/constants.ts (3)

11-15: LGTM! Well-structured partner webhook triggers.

The new PARTNERS_WEBHOOK_TRIGGERS constant properly categorizes partner-related webhook events and will be useful for validation and feature gating.


24-24: Correctly added to workspace-level triggers.

The "commission.created" event is appropriately included in the workspace-level webhook triggers, maintaining consistency with the existing webhook infrastructure.


42-42: Clear and descriptive webhook trigger description.

The description "Commission created" is concise and follows the established naming convention for webhook trigger descriptions.

apps/web/lib/webhook/schemas.ts (2)

3-3: Proper import for enriched commission schema.

The import of CommissionEnrichedSchema is correctly placed and will be used for validating the enriched commission data in the webhook payload.


115-125: Well-structured commission webhook event schema.

The schema follows the established pattern for webhook events and properly uses the CommissionEnrichedSchema for data validation. The OpenAPI metadata is correctly configured for documentation generation.

apps/web/lib/partners/create-partner-commission.ts (6)

16-17: Proper imports for webhook functionality.

The imports for webhook publishing and commission schema validation are correctly added to support the new webhook feature.


53-53: Improved parameter documentation.

The updated comment clarifies that the user parameter represents the user who created the manual commission, improving code readability.


182-182: Proper user attribution for commissions.

Setting userId: user?.id correctly attributes the commission to the user who created it, supporting audit trails and user-specific operations.


192-195: Correct data inclusion for webhook payload.

Including partner and customer relations ensures the webhook payload contains the enriched commission data as expected by the CommissionEnrichedSchema.


203-211: Proper workspace fetching for webhook validation.

Fetching the workspace with webhookEnabled flag ensures webhooks are only sent when enabled, following the established webhook pattern.


219-223: Well-integrated webhook sending.

The webhook sending is properly integrated with the commission creation flow, using the correct trigger and validated data. The placement within Promise.allSettled ensures webhook failures don't affect commission creation.

apps/web/lib/integrations/segment/transform.ts (1)

3-6: Proper type alignment with unified payload types.

The updated imports align with the standardized webhook payload type naming convention, improving type consistency across the codebase while maintaining the same functionality.

apps/web/lib/webhook/sample-events/commission-created.json (1)

1-61: Comprehensive sample webhook event payload.

The sample event structure correctly represents a commission.created webhook payload with enriched commission data including partner and customer information. The JSON structure aligns with the CommissionEnrichedSchema and follows the established webhook event format.

apps/web/lib/webhook/types.ts (2)

2-2: LGTM - Import addition aligns with new webhook support.

The import of CommissionEnrichedSchema is correctly added to support the new commission webhook payload type.


12-32: LGTM - Type standardization and new commission payload type.

The type definitions are well-structured with consistent naming conventions using the WebhookPayload suffix. The new CommissionEventWebhookPayload type is properly integrated into the WebhookEventPayload union type, maintaining type safety across the webhook system.

apps/web/lib/integrations/slack/transform.ts (5)

1-1: LGTM - Currency formatter import added.

The import of currencyFormatter is correctly added to support the new commission template formatting needs.


7-11: LGTM - Type imports updated with consistent naming.

The payload type names are updated to use consistent Payload suffix, aligning with the standardization in the types file.


53-53: LGTM - Function parameter types updated consistently.

The parameter types for existing template functions are correctly updated to use the new standardized payload type names.

Also applies to: 105-105, 154-154, 204-204


244-252: Currency formatting implementation is correct.

The currency formatting correctly handles cent-based values by dividing by 100 and uses appropriate fraction digits settings. The override of maximumFractionDigits: 2 properly supersedes the default value of 0 from the currencyFormatter utility.


292-292: LGTM - Commission template correctly registered.

The commission template is properly registered in the slackTemplates mapping with the correct event key.

@steven-tey
Copy link
Collaborator

@CodeRabbit final review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 15, 2025

Tip

For best results, initiate chat on the files or code changes.

@steven-tey I've conducted a comprehensive final review of this PR. Here's my assessment:

📋 Final Review Summary

This PR successfully implements the commission.created webhook trigger with comprehensive integration across the platform. The implementation is well-structured and follows existing patterns, but introduces several breaking changes that require careful rollout planning.

🎯 Key Achievements

Complete webhook integration: New event properly integrated into webhook schemas, constants, and validation
Rich payload data: Commission webhooks include enriched partner and customer information
Integration support: Slack and Segment templates added for the new event
Database tracking: Optional userId field for manual commission tracking
Test coverage: Comprehensive test updates for new functionality
Type safety: Consistent type naming with *WebhookPayload convention

⚠️ Critical Breaking Changes

1. Schema Rename (HIGH IMPACT)

  • CommissionResponseSchemaCommissionEnrichedSchema
  • Risk: External consumers importing the old schema will break
  • Mitigation: Consider maintaining an alias during transition period

2. API Response Structure (HIGH IMPACT)

  • Commission endpoints now return enriched data with partner and customer objects
  • Affected: GET /api/commissions, PATCH /api/commissions/[id]
  • Risk: Strict API consumers expecting minimal response format may break

3. Webhook Type Renames (MEDIUM IMPACT)

  • Standardized naming: *EventDataProps*EventWebhookPayload
  • Impact: Integration code using old types needs updates

4. Function Signature (LOW IMPACT)

  • createPartnerCommission removed workspaceId parameter
  • Status: ✅ All internal calls already updated

🔧 Code Quality Observations

Strengths:

  • Consistent error handling and validation patterns
  • Proper type safety throughout the implementation
  • Well-structured webhook payload generation
  • Comprehensive test coverage updates
  • Clean integration with existing systems

Areas for attention:

  • The enriched commission data increases payload size significantly
  • Consider performance implications of always including related entities

📊 Impact Assessment

Area Impact Level Details
Internal Systems Low Function calls updated properly
External APIs High Response structure changes
SDK/Clients High Schema renames affect imports
Webhooks Low New event is additive
Database Low Optional field addition

🚀 Final Recommendations

Pre-deployment:

  1. Version the Commission APIs or provide migration path for response structure changes
  2. Document breaking changes in release notes with migration examples
  3. Consider phased rollout for webhook consumers

Post-deployment:

  1. Monitor webhook delivery for the new commission.created event
  2. Track API usage to identify affected external consumers
  3. Provide migration timeline for deprecated schema names

Deployment Readiness

The implementation is production-ready with proper error handling, validation, and test coverage. The breaking changes are well-documented and unavoidable for the feature requirements.

Recommendation: ✅ Approve for merge with coordinated rollout plan for breaking changes.

The code quality is excellent and the feature implementation is comprehensive. The breaking changes are justified by the enhanced functionality and improved type consistency.

@steven-tey
Copy link
Collaborator

@CodeRabbit final review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 16, 2025

Tip

For best results, initiate chat on the files or code changes.

@steven-tey I've already provided a comprehensive final review in this thread with a detailed assessment of the breaking changes and deployment readiness.

My previous recommendation remains: ✅ Approve for merge with coordinated rollout plan for breaking changes.

The key points from my final review were:

  • Production-ready implementation with proper error handling and test coverage
  • High-impact breaking changes (schema renames, API response structure changes)
  • Well-structured webhook integration following existing patterns
  • Requires coordinated rollout planning due to external API impacts

Is there a specific aspect you'd like me to focus on, or have there been changes since my last review that need assessment?

@steven-tey
Copy link
Collaborator

@CodeRabbit I made a few final changes, can you do a final review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 16, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@steven-tey I'll examine the latest changes and provide an updated final review.


🏁 Script executed:

#!/bin/bash
# Check the current state of key files that were part of the PR to identify recent changes
echo "=== Examining current state of commission schema ==="
cat apps/web/lib/zod/schemas/commissions.ts

echo -e "\n=== Checking webhook types and constants ==="
cat apps/web/lib/webhook/types.ts
cat apps/web/lib/webhook/constants.ts

echo -e "\n=== Examining create-partner-commission function ==="
cat apps/web/lib/partners/create-partner-commission.ts

echo -e "\n=== Checking API route files ==="
cat apps/web/app/\(ee\)/api/commissions/route.ts
cat apps/web/app/\(ee\)/api/commissions/\[commissionId\]/route.ts

echo -e "\n=== Checking recent test changes ==="
cat apps/web/tests/webhooks/index.test.ts | tail -20

Length of output: 24817


@steven-tey After examining the current state of the codebase, I can confirm that no significant changes have been made since my previous comprehensive review. My previous assessment stands:

Status Confirmation

The implementation remains production-ready with the same breaking changes I identified earlier:

Breaking Changes (Unchanged)

  1. Schema Rename: CommissionResponseSchemaCommissionEnrichedSchema (HIGH IMPACT)
  2. API Response Structure: Commission endpoints return enriched data (HIGH IMPACT)
  3. Webhook Type Renames: *EventDataProps*EventWebhookPayload (MEDIUM IMPACT)
  4. Function Signature: createPartnerCommission workspaceId removed (LOW IMPACT - all calls updated)

Current Implementation Quality

  • ✅ Proper webhook integration with commission.created event
  • ✅ Consistent error handling and validation
  • ✅ Complete test coverage for new functionality
  • ✅ Clean type safety with CommissionEnrichedSchema
  • ✅ Database schema properly supports optional userId tracking

🚀 Final Recommendation

✅ APPROVED FOR MERGE - Same recommendation as my previous review.

The code quality is excellent, the webhook integration is comprehensive, and all breaking changes are well-documented and justified for the enhanced functionality.

Next Steps: Coordinate rollout plan for the breaking changes, particularly for external API consumers and webhook integrations.

@steven-tey steven-tey merged commit b63b789 into main Jul 16, 2025
8 checks passed
@steven-tey steven-tey deleted the commission-created-webhook-event branch July 16, 2025 14:43
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.

3 participants