-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Add reward persistence to commissions #2475
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
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 unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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
rewardsWithPartnersis 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
📒 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.
|
@coderabbitai full review |
1 similar comment
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
✅ Actions performedFull review triggered. |
There was a problem hiding this 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
rewardIdfield to the Commission model to link commissions to their specific reward terms - Created a backfill script to populate
rewardIdfor 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.
There was a problem hiding this 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:firstCommissionquery is missingprogramIdfilter.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, notnew Date().If
createdAtis backdated or reprocessed, usingnew 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’sonDeleteaction (currently default Restrict via Commission side). If you want historical commissions to persist when a reward is deleted, preferonDelete: SetNull(see suggestion in commission.prisma).packages/prisma/schema/commission.prisma (1)
22-22: AddonDelete: SetNulland 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:rewarIdColumn→rewardIdColumn.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.
📒 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.rewardIdand skipping whenmaxDuration === 0prevents accidental recurrence after configuration changes.
134-136: One-time reward check is correct and consistent with schema semantics.Treating
maxDuration === 0as “first sale only” aligns with Reward.maxDuration docs.
211-211: PersistingrewardIdon commission is the right move.This enables backreferencing commissions to the reward used at creation time.
There was a problem hiding this 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.
📒 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.
There was a problem hiding this 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 therewardIdURL param, calling onlyqueryParams({ del: "rewardId" })won’t close the UI. To be resilient across both entry points, also callsetIsOpen(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 clearrewardIdfrom the URL.Currently we only close the sheet (
setIsOpen(false)) on delete success. If this flow was opened viarewardIdin 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 clearrewardIdfrom 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 existingmaxDuration = 1.You’ve removed 1 from the selectable options while still rendering existing values. This means:
- Existing rewards with
maxDuration = 1will 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.
📒 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 viauseRouterStuff.Bringing
queryParamsinto component scope enables consistent URL-driven state transitions used elsewhere in this file.
491-499: LGTM: centralizing close behavior clears stalerewardIdfrom 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).
Summary by CodeRabbit
New Features
Bug Fixes
Chores