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

Skip to content

Conversation

@devkiran
Copy link
Collaborator

@devkiran devkiran commented Jun 3, 2025

Summary by CodeRabbit

  • New Features

    • Partner groups now display distinct, randomized colors.
    • Commissions for sale events now store an associated rewardId.
    • Reward editor sheet updates URL params on close/update and limits available recurring durations.
  • Bug Fixes

    • Prevents creating new commissions when a reward is one-time, changed to a one-time reward, or recurrence limit is reached.
    • Fraud/canceled status from an initial commission is propagated to subsequent commissions.
  • Chores

    • Linked commissions <-> rewards in the database with an index.
    • Added backfill migration to populate existing commission reward links.

@vercel
Copy link
Contributor

vercel bot commented Jun 3, 2025

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

Project Deployment Preview Updated (UTC)
dub Ready Ready Preview Aug 20, 2025 3:51am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 3, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds rewardId tracking to Commission (schema + relation), updates commission-creation logic to respect prior commission reward/maxDuration and propagate fraud/canceled status, persists rewardId on new commissions, backfills existing commissions' rewardId, and sets colors for imported partner groups.

Changes

Cohort / File(s) Summary
Commission creation logic
apps/web/lib/partners/create-partner-commission.ts
Reads first commission (rewardId, status, createdAt); if prior rewardId differs fetches original reward and enforces one-time/recurrence (maxDuration) skip rules; computes months elapsed for recurring rewards; propagates fraud/canceled status; persists rewardId on created commissions; updated logging.
Prisma schema: Reward–Commission relation
packages/prisma/schema/commission.prisma, packages/prisma/schema/reward.prisma
Adds Commission.rewardId String? with @relation to Reward and @@index(rewardId); adds Reward.commissions Commission[] back-reference.
PartnerStack import: group color
apps/web/lib/partnerstack/import-groups.ts
Adds RESOURCE_COLORS and randomValue imports and sets color: randomValue(RESOURCE_COLORS) for created partner groups (non-default).
Data migration: backfill rewardId
apps/web/scripts/migrations/backfill-commissions-rewardId.ts
New migration script groups program enrollments by program & reward column (sale default), collects partnerIds, and updates Commission rows with null rewardId (excluding type: "custom") to backfill rewardId; logs progress.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant S as Sale Event
  participant CPC as createPartnerCommission()
  participant DB as DB (Commission/Reward)
  participant Log as Logger

  S->>CPC: invoke(programId, partnerId, reward)
  CPC->>DB: findFirst Commission by partner+program (select rewardId,status,createdAt)
  alt first commission exists
    CPC->>DB: if rewardId present && rewardId != reward.id → fetch original Reward (id,maxDuration)
    alt original reward maxDuration == 0
      CPC->>Log: log skip (one-time already rewarded)
      CPC-->>S: return (no commission)
    else original reward has numeric maxDuration
      CPC->>CPC: compute monthsElapsed since firstCommission.createdAt
      alt monthsElapsed >= maxDuration
        CPC->>Log: log skip (duration exceeded)
        CPC-->>S: return
      end
    end
  end
  CPC->>CPC: determine status (propagate fraud/canceled if applicable)
  CPC->>DB: create Commission { ..., rewardId: reward?.id }
  CPC-->>S: return created commission
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • devkiran

Poem

With twitching nose I trace each trail,
I tag rewards where commissions sail.
One-time crumbs I gently skip,
Recurring months I count and clip.
I color groups and fill the rows — hop! 🐇✨

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.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch reward-change-support

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.
    • 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.
  • 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 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 @coderabbitai help to get the list of available commands.

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

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.

@devkiran devkiran requested a review from steven-tey June 4, 2025 11:19
@devkiran devkiran marked this pull request as ready for review June 4, 2025 11:19
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 (1)
apps/web/scripts/backfill-commissions-reward.ts (1)

70-70: Fix misleading variable name.

The variable rewardsWithPartners is misleading when used for program-wide rewards that don't have specific partners.

Apply this diff:

-    const rewardsWithPartners = programWideRewards.map((reward) => ({
+    const programRewards = programWideRewards.map((reward) => ({
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cf2f431 and b3266af.

📒 Files selected for processing (3)
  • apps/web/lib/partners/create-partner-commission.ts (3 hunks)
  • apps/web/scripts/backfill-commissions-reward.ts (1 hunks)
  • packages/prisma/schema/commission.prisma (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/web/lib/partners/create-partner-commission.ts (1)
apps/web/lib/types.ts (1)
  • RewardProps (472-472)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (3)
packages/prisma/schema/commission.prisma (1)

37-40: Schema changes look good for reward persistence.

The addition of nullable reward fields to the Commission model is well-designed and maintains backward compatibility with existing records.

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

26-29: Good type narrowing for API clarity.

Restricting the reward parameter to only the necessary fields from RewardProps improves the API contract and reduces unnecessary data passing.


179-181: Reward persistence implementation looks good.

The commission creation now properly persists reward details, aligning with the schema changes and supporting historical consistency.

@steven-tey
Copy link
Collaborator

@coderabbitai full review

1 similar comment
@steven-tey
Copy link
Collaborator

@coderabbitai full review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

✅ Actions performed

Full review triggered.

@steven-tey steven-tey requested a review from Copilot August 20, 2025 03:21
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

✅ Actions performed

Full review triggered.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds reward persistence to commission records by storing reward IDs directly in commissions, ensuring that commissions retain their original reward terms even when program reward settings change.

  • Added a rewardId field to the Commission model to link commissions to their specific reward terms
  • Created a backfill script to populate rewardId for existing commission records
  • Updated commission creation logic to check original reward terms for repeat sales

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
packages/prisma/schema/reward.prisma Added reverse relation to commissions for reward tracking
packages/prisma/schema/commission.prisma Added rewardId field and relation to Reward model
apps/web/scripts/migrations/backfill-commissions-rewardId.ts Migration script to populate rewardId for existing commissions
apps/web/lib/partnerstack/import-groups.ts Added color field to partner group creation (unrelated change)
apps/web/lib/partners/create-partner-commission.ts Updated commission creation to store rewardId and check original reward terms

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

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

Caution

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

⚠️ Outside diff range comments (2)
apps/web/lib/partners/create-partner-commission.ts (2)

87-101: Critical: firstCommission query is missing programId filter.

Without programId, a partner’s sale in another program (for the same customer) can incorrectly gate this program’s commissions.

Apply this diff to scope the lookup to the current program:

       const firstCommission = await prisma.commission.findFirst({
         where: {
           partnerId,
           customerId,
+          programId,
           type: "sale",
         },
         orderBy: {
           createdAt: "asc",
         },
         select: {
           rewardId: true,
           status: true,
           createdAt: true,
         },
       });

145-147: Use event timestamp when provided for duration checks, not new Date().

If createdAt is backdated or reprocessed, using new Date() can wrongly block/allow commissions.

Apply this diff:

-            const monthsDifference = differenceInMonths(
-              new Date(),
-              firstCommission.createdAt,
-            );
+            const referenceDate = createdAt ?? new Date();
+            const monthsDifference = differenceInMonths(
+              referenceDate,
+              firstCommission.createdAt,
+            );
🧹 Nitpick comments (5)
apps/web/lib/partnerstack/import-groups.ts (1)

51-51: Backfill color only when missing to avoid overwriting existing choices.

Randomizing color on create is fine, but existing groups that predate this change (color is null) won’t get a color with update: {}. Consider conditionally setting color only when absent.

Apply this diff within the loop to avoid overwriting existing colors while backfilling nulls:

-      await prisma.partnerGroup.upsert({
+      const existing = await prisma.partnerGroup.findUnique({
+        where: {
+          programId_slug: {
+            programId,
+            slug: group.slug,
+          },
+        },
+        select: { color: true },
+      });
+
+      await prisma.partnerGroup.upsert({
         where: {
           programId_slug: {
             programId,
             slug: group.slug,
           },
         },
         create: {
           id: createId({ prefix: "grp_" }),
           programId,
           name: group.name,
           slug: group.slug,
           color: randomValue(RESOURCE_COLORS),
         },
-        update: {},
+        update: existing?.color ? {} : { color: randomValue(RESOURCE_COLORS) },
       });
packages/prisma/schema/reward.prisma (1)

32-32: Reward → Commission backrelation is good; confirm delete semantics.

commissions: Commission[] is correct. Ensure your intended behavior on Reward deletion aligns with the Commission relation’s onDelete action (currently default Restrict via Commission side). If you want historical commissions to persist when a reward is deleted, prefer onDelete: SetNull (see suggestion in commission.prisma).

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

22-22: Add onDelete: SetNull and consider an index aligned with read patterns.

  • Make the relation tolerant to reward deletions to preserve historical commissions.
  • Optional: add a composite index to speed up the “first sale commission” lookup by partner/customer/program/type ordered by createdAt.

Apply this diff to the relation:

-  reward   Reward?   @relation(fields: [rewardId], references: [id])
+  reward   Reward?   @relation(fields: [rewardId], references: [id], onDelete: SetNull)

Additionally (outside these lines), you may add:

// Optional, supports queries like findFirst sale by partnerId+customerId+programId ordered by createdAt
@@index([programId, partnerId, customerId, type, createdAt])

Also applies to: 44-44, 54-54

apps/web/scripts/migrations/backfill-commissions-rewardId.ts (2)

8-8: Typo: rewarIdColumnrewardIdColumn.

Minor naming fix improves clarity and prevents propagation of typos.

Apply this diff:

-  const rewarIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
+  const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];

-    by: ["programId", rewarIdColumn],
+    by: ["programId", rewardIdColumn],

-    [rewarIdColumn]: rewardId,
+    [rewardIdColumn]: rewardId,

-        [rewarIdColumn]: rewardId!,
+        [rewardIdColumn]: rewardId!,

Also applies to: 11-11, 22-23, 31-31


62-62: Ensure clean shutdown and error handling for the script.

Add try/catch/finally with prisma.$disconnect() so the process exits cleanly and connections are released.

You can refactor outside the selected lines like this:

async function main() { /* ... */ }

main()
  .catch((e) => {
    console.error(e);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
📜 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 e2f4c9a and 5096e19.

📒 Files selected for processing (5)
  • apps/web/lib/partners/create-partner-commission.ts (2 hunks)
  • apps/web/lib/partnerstack/import-groups.ts (2 hunks)
  • apps/web/scripts/migrations/backfill-commissions-rewardId.ts (1 hunks)
  • packages/prisma/schema/commission.prisma (3 hunks)
  • packages/prisma/schema/reward.prisma (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: devkiran
PR: dubinc/dub#2735
File: apps/web/lib/actions/partners/delete-reward.ts:33-41
Timestamp: 2025-08-14T05:17:51.825Z
Learning: In the partner groups system, a rewardId can only belong to one group, establishing a one-to-one relationship between rewards and groups. This means using Prisma's `update` method (rather than `updateMany`) is appropriate when updating groups by rewardId.
📚 Learning: 2025-07-30T15:29:54.131Z
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/rewards-logic.tsx:268-275
Timestamp: 2025-07-30T15:29:54.131Z
Learning: In apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward condition, dependent fields (attribute, operator, value) should be reset rather than preserved because different entities (customer vs sale) have different available attributes. Maintaining existing fields when the entity changes would create invalid state combinations and confusing UX.

Applied to files:

  • apps/web/lib/partners/create-partner-commission.ts
📚 Learning: 2025-08-14T05:17:51.825Z
Learnt from: devkiran
PR: dubinc/dub#2735
File: apps/web/lib/actions/partners/delete-reward.ts:33-41
Timestamp: 2025-08-14T05:17:51.825Z
Learning: In the partner groups system, a rewardId can only belong to one group, establishing a one-to-one relationship between rewards and groups. This means using Prisma's `update` method (rather than `updateMany`) is appropriate when updating groups by rewardId.

Applied to files:

  • apps/web/lib/partners/create-partner-commission.ts
🔇 Additional comments (4)
apps/web/lib/partnerstack/import-groups.ts (1)

1-1: LGTM: imports look correct and scoped.

RESOURCE_COLORS and randomValue are appropriate for the new color assignment.

Also applies to: 3-3

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

104-129: Guard looks correct for “original reward was one-time” scenario.

Fetching the original reward by firstCommission.rewardId and skipping when maxDuration === 0 prevents accidental recurrence after configuration changes.


134-136: One-time reward check is correct and consistent with schema semantics.

Treating maxDuration === 0 as “first sale only” aligns with Reward.maxDuration docs.


211-211: Persisting rewardId on commission is the right move.

This enables backreferencing commissions to the reward used at creation time.

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

Caution

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

⚠️ Outside diff range comments (2)
apps/web/lib/partners/create-partner-commission.ts (2)

87-101: Scope firstCommission lookup to the program to avoid cross-program bleed.

If the same partner/customer exist across programs, this can fetch the wrong “first sale,” misapplying duration/one-time checks and status propagation.

       const firstCommission = await prisma.commission.findFirst({
         where: {
+          programId,
           partnerId,
           customerId,
           type: "sale",
         },

142-149: Use the event’s createdAt (when provided) for duration checks, not “now.”

Backfills or delayed creations should compute monthsElapsed relative to the event time, not the current time.

-            const monthsDifference = differenceInMonths(
-              new Date(),
-              firstCommission.createdAt,
-            );
+            const referenceDate = createdAt ?? new Date();
+            const monthsDifference = differenceInMonths(
+              referenceDate,
+              firstCommission.createdAt,
+            );
♻️ Duplicate comments (1)
apps/web/scripts/migrations/backfill-commissions-rewardId.ts (1)

44-54: Restrict the backfill to the target event type to avoid corrupting other commissions.

This currently updates all non-custom commissions (click/lead included). Limit updates to the selected event.

     await prisma.commission.updateMany({
       where: {
         programId,
         partnerId: {
           in: partnerIds,
         },
         rewardId: null,
-        type: {
-          not: "custom",
-        },
+        type: event,
       },
       data: {
         rewardId,
       },
     });
🧹 Nitpick comments (7)
apps/web/lib/partnerstack/import-groups.ts (1)

51-52: Choose group color deterministically to avoid drift across re-imports.

Randomizing colors can cause non-deterministic UI if groups are ever re-created. Consider hashing the slug to a stable color index.

-          color: randomValue(RESOURCE_COLORS),
+          color: RESOURCE_COLORS[hashSlug(group.slug) % RESOURCE_COLORS.length],

Add this helper once in the module (outside the selected lines):

// Simple, fast, stable hash
const hashSlug = (s: string) =>
  Array.from(s).reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 0);
packages/prisma/schema/commission.prisma (1)

44-45: Consider explicit onDelete semantics for the Reward relation.

Without an onDelete policy, deleting a Reward may be restricted by existing Commission rows. If you intend to allow Reward deletion while preserving Commission history, set the relation to SetNull.

-  reward   Reward?   @relation(fields: [rewardId], references: [id])
+  reward   Reward?   @relation(fields: [rewardId], references: [id], onDelete: SetNull)

Optional: If your common queries filter by programId and rewardId together, a composite index can help:

@@index([programId, rewardId])
apps/web/lib/partners/create-partner-commission.ts (2)

206-225: Avoid passing undefined for non-null Prisma fields; default currency server-side.

If currency is omitted, Prisma defaults apply only when the field is not present. Passing undefined can be error-prone; set a default explicitly.

         type: event,
-        currency,
+        currency: currency ?? "usd",

62-69: Wrap reward resolution in the try/catch or handle errors explicitly.

determinePartnerReward can throw (DB/network). Right now, such errors bypass the catch block (which only wraps the create call), leading to unlogged failures.

  • Option A: Move the try/catch to wrap the entire function body.
  • Option B: Add a local try/catch around determinePartnerReward and log consistently via log().
apps/web/scripts/migrations/backfill-commissions-rewardId.ts (3)

8-12: Fix variable typo (rewarIdColumn) to rewardIdColumn everywhere it’s used.

Minor, but reduces confusion and avoids accidental misuses in future edits.

-  const rewarIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
+  const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];

   const programEnrollments = await prisma.programEnrollment.groupBy({
-    by: ["programId", rewarIdColumn],
+    by: ["programId", rewardIdColumn],
     _count: {
       _all: true,
     },
   });

-  for (const {
+  for (const {
     _count,
     programId,
-    [rewarIdColumn]: rewardId,
+    [rewardIdColumn]: rewardId,
   } of programEnrollments) {

   const partners = await prisma.programEnrollment.findMany({
     where: {
       programId,
-      [rewarIdColumn]: rewardId!,
+      [rewardIdColumn]: rewardId!,
     },

Also applies to: 19-23, 28-33


24-26: Skip groups where rewardId is null.

Grouping can include null rewardId buckets; updating to null is a no-op and wastes queries.

-    if (_count._all === 0) {
+    if (_count._all === 0 || rewardId == null) {
       continue;
     }

7-8: Run the backfill across all events in one pass.

Small ergonomics upgrade; avoids manual edits/re-runs per event and keeps logic consistent.

// Replace the single-event approach with:
async function main() {
  const events = ["click", "lead", "sale"] as const;

  for (const event of events) {
    const rewardIdColumn = REWARD_EVENT_COLUMN_MAPPING[event];
    // ... reuse the existing logic per event
  }
}
📜 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 e2f4c9a and 5096e19.

📒 Files selected for processing (5)
  • apps/web/lib/partners/create-partner-commission.ts (2 hunks)
  • apps/web/lib/partnerstack/import-groups.ts (2 hunks)
  • apps/web/scripts/migrations/backfill-commissions-rewardId.ts (1 hunks)
  • packages/prisma/schema/commission.prisma (3 hunks)
  • packages/prisma/schema/reward.prisma (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-07-30T15:29:54.131Z
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/rewards-logic.tsx:268-275
Timestamp: 2025-07-30T15:29:54.131Z
Learning: In apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward condition, dependent fields (attribute, operator, value) should be reset rather than preserved because different entities (customer vs sale) have different available attributes. Maintaining existing fields when the entity changes would create invalid state combinations and confusing UX.

Applied to files:

  • apps/web/lib/partners/create-partner-commission.ts
📚 Learning: 2025-08-14T05:17:51.825Z
Learnt from: devkiran
PR: dubinc/dub#2735
File: apps/web/lib/actions/partners/delete-reward.ts:33-41
Timestamp: 2025-08-14T05:17:51.825Z
Learning: In the partner groups system, a rewardId can only belong to one group, establishing a one-to-one relationship between rewards and groups. This means using Prisma's `update` method (rather than `updateMany`) is appropriate when updating groups by rewardId.

Applied to files:

  • apps/web/scripts/migrations/backfill-commissions-rewardId.ts
🔇 Additional comments (1)
packages/prisma/schema/reward.prisma (1)

32-32: LGTM: Reward → Commission back-reference completes the relation.

This makes it straightforward to aggregate commissions by reward and aligns with the new Commission.rewardId field.

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

Caution

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

⚠️ Outside diff range comments (3)
apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx (3)

141-146: Update success clears URL param but may not close the sheet in non-URL-driven flows. Close both ways.

If this sheet is opened via local state (e.g., useRewardSheet) rather than from the rewardId URL param, calling only queryParams({ del: "rewardId" }) won’t close the UI. To be resilient across both entry points, also call setIsOpen(false).

Apply this diff:

   onSuccess: async () => {
-        queryParams({ del: "rewardId", scroll: false });
+        // Close the sheet for both URL-param-driven and local-state-driven usages
+        setIsOpen(false);
+        queryParams({ del: "rewardId", scroll: false });
         toast.success("Reward updated!");
         await mutateProgram();
         await mutateGroup();
       },

156-161: Deleting a reward should also clear rewardId from the URL.

Currently we only close the sheet (setIsOpen(false)) on delete success. If this flow was opened via rewardId in the URL, the param will remain, causing stale state and potential re-open on refresh.

Apply this diff:

   onSuccess: async () => {
-        setIsOpen(false);
+        // Keep URL and UI in sync on delete
+        setIsOpen(false);
+        queryParams({ del: "rewardId", scroll: false });
         toast.success("Reward deleted!");
         await mutate(`/api/programs/${defaultProgramId}`);
         await mutateGroup();
       },

384-391: Cancel button should also clear rewardId from the URL to avoid stale state.

Clicking Cancel only toggles local state. If the sheet was opened via rewardId, the param remains, and the sheet can re-open on navigation/refresh.

Apply one of these:

Option A (minimal change):

   <Button
     type="button"
     variant="secondary"
-    onClick={() => setIsOpen(false)}
+    onClick={() => {
+      setIsOpen(false);
+      queryParams({ del: "rewardId", scroll: false });
+    }}
     text="Cancel"
     className="w-fit"
     disabled={isCreating || isUpdating || isDeleting}
   />

Option B (route all closes through Sheet’s onClose):

-  <Button
-    type="button"
-    variant="secondary"
-    onClick={() => setIsOpen(false)}
-    text="Cancel"
-    className="w-fit"
-    disabled={isCreating || isUpdating || isDeleting}
-  />
+  <Sheet.Close asChild>
+    <Button
+      type="button"
+      variant="secondary"
+      text="Cancel"
+      className="w-fit"
+      disabled={isCreating || isUpdating || isDeleting}
+    />
+  </Sheet.Close>
🧹 Nitpick comments (1)
apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx (1)

339-344: Excluding 1-month from recurring durations: confirm product intent and handle existing maxDuration = 1.

You’ve removed 1 from the selectable options while still rendering existing values. This means:

  • Existing rewards with maxDuration = 1 will show “for 1 month” but users cannot re-select 1 month if they change and want to revert.
  • If intentional (e.g., product decision to discourage 1-month recurring), this is fine. Otherwise, consider conditionally including 1 when it is the current value to avoid trapping users.

If you want to allow editing existing 1-month rewards without promoting it for new ones, tweak the filter:

- ...RECURRING_MAX_DURATIONS.filter(
-   (v) => v !== 0 && v !== 1,
- ).map((v) => ({
+ ...RECURRING_MAX_DURATIONS
+   .filter((v) => v !== 0 && (v !== 1 || maxDuration === 1))
+   .map((v) => ({
      text: `for ${v} ${pluralize("month", Number(v))}`,
      value: v.toString(),
    })),
📜 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 5096e19 and c1b533e.

📒 Files selected for processing (2)
  • apps/web/lib/partners/create-partner-commission.ts (2 hunks)
  • apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/lib/partners/create-partner-commission.ts
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-07-30T15:25:13.936Z
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx:56-66
Timestamp: 2025-07-30T15:25:13.936Z
Learning: In apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx, the form schema uses partial condition objects to allow users to add empty/unconfigured condition fields without type errors, while submission validation uses strict schemas to ensure data integrity. This two-stage validation pattern improves UX by allowing progressive completion of complex forms.

Applied to files:

  • apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
📚 Learning: 2025-07-30T15:29:54.131Z
Learnt from: TWilson023
PR: dubinc/dub#2673
File: apps/web/ui/partners/rewards/rewards-logic.tsx:268-275
Timestamp: 2025-07-30T15:29:54.131Z
Learning: In apps/web/ui/partners/rewards/rewards-logic.tsx, when setting the entity field in a reward condition, dependent fields (attribute, operator, value) should be reset rather than preserved because different entities (customer vs sale) have different available attributes. Maintaining existing fields when the entity changes would create invalid state combinations and confusing UX.

Applied to files:

  • apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
📚 Learning: 2025-08-14T05:17:51.825Z
Learnt from: devkiran
PR: dubinc/dub#2735
File: apps/web/lib/actions/partners/delete-reward.ts:33-41
Timestamp: 2025-08-14T05:17:51.825Z
Learning: In the partner groups system, a rewardId can only belong to one group, establishing a one-to-one relationship between rewards and groups. This means using Prisma's `update` method (rather than `updateMany`) is appropriate when updating groups by rewardId.

Applied to files:

  • apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
⏰ 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
🔇 Additional comments (2)
apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx (2)

87-87: Good addition: centralizing URL param updates via useRouterStuff.

Bringing queryParams into component scope enables consistent URL-driven state transitions used elsewhere in this file.


491-499: LGTM: centralizing close behavior clears stale rewardId from URL.

Using onClose={() => queryParams({ del: "rewardId", scroll: false })} ensures the URL state is cleaned up when the sheet is dismissed via the built-in close triggers (header X, overlay click, ESC).

@steven-tey steven-tey merged commit a1cf6b5 into main Aug 20, 2025
7 of 8 checks passed
@steven-tey steven-tey deleted the reward-change-support branch August 20, 2025 03:54
@steven-tey steven-tey restored the reward-change-support branch August 20, 2025 03:55
@steven-tey steven-tey deleted the reward-change-support branch August 20, 2025 03:55
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