Skip to content

Dynamic UTM parameters for partner links - #4245

Open
devkiran wants to merge 11 commits into
mainfrom
dynamic-utm-params-partner-links
Open

Dynamic UTM parameters for partner links#4245
devkiran wants to merge 11 commits into
mainfrom
dynamic-utm-params-partner-links

Conversation

@devkiran

@devkiran devkiran commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator
image

Summary by CodeRabbit

  • New Features

    • Added partner-aware UTM macros for partner names and link keys.
    • Added autocomplete suggestions and keyboard navigation for UTM templates.
    • Applied partner macros consistently across generated, edited, and embedded links.
  • Improvements

    • Improved bulk UTM synchronization with background processing for larger groups.
    • UTM updates now refresh automatically when partner names change.
    • Updated AppsFlyer parameter handling to use shared partner macros.
  • Validation

    • Added clearer validation for supported UTM macros and invalid template values.

@vercel

vercel Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

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

Project Deployment Actions Updated (UTC)
dub Ready Ready Preview Jul 31, 2026 2:29pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 079cd3a6-0331-42b0-ae6e-f0f9812b253a

📥 Commits

Reviewing files that changed from the base of the PR and between e759ab1 and 2897b4a.

📒 Files selected for processing (4)
  • apps/web/lib/actions/partners/bulk-invite-partners.ts
  • apps/web/lib/api/utm/extract-and-resolve-utm-params.ts
  • apps/web/lib/zod/schemas/utm.ts
  • apps/web/ui/modals/add-partner-link-modal.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/web/lib/api/utm/extract-and-resolve-utm-params.ts
  • apps/web/lib/zod/schemas/utm.ts

📝 Walkthrough

Walkthrough

The PR adds shared partner UTM macros, applies resolved templates across link creation and update flows, adds UTM autocomplete suggestions, and moves group UTM synchronization into a paginated background job.

Changes

Partner UTM and synchronization

Layer / File(s) Summary
Shared partner macro foundation
apps/web/lib/partners/macros.ts, apps/web/lib/api/utm/..., apps/web/lib/zod/schemas/utm.ts, apps/web/lib/integrations/appsflyer/...
Shared partner macros provide validation, resolution, UTM extraction, and AppsFlyer parameter handling.
Context-aware link generation
apps/web/lib/api/utm/apply-group-utm-to-link.ts, apps/web/ui/modals/add-partner-link-modal.tsx, apps/web/app/(ee)/api/cron/groups/*, apps/web/lib/api/partners/create-partner-default-links.ts, apps/web/lib/actions/partners/bulk-invite-partners.ts, apps/web/tests/misc/*
Generated links receive group UTM templates after link processing. Resolved URL parameters and stored UTM fields use partner context.
Partner link API integration
apps/web/app/(ee)/api/embed/referrals/links/..., apps/web/app/(ee)/api/partner-profile/..., apps/web/app/(ee)/api/partners/links/...
Partner link routes load partner names and apply group UTM templates before link creation or update.
Partner macro autocomplete
packages/ui/src/utm-builder.tsx, apps/web/app/app.dub.co/.../group-link-settings.tsx
UTM inputs support filtered macro suggestions, keyboard selection, and a portaled suggestion menu.
Paginated group UTM job
apps/web/lib/jobs/handlers/sync-group-utm-job.ts, apps/web/lib/jobs/registry.ts, apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts, apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts, apps/web/app/api/utm/[id]/route.ts
Group UTM synchronization runs through a registered paginated job. Cron and application routes dispatch the job directly.
Partner identity synchronization
apps/web/lib/partners/dispatch-partner-utm-sync.ts, apps/web/lib/partners/sync-partner-identity.ts, apps/web/lib/actions/partners/update-partner-profile.ts
Partner name changes dispatch group UTM synchronization in the background.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant PartnerUpdate
  participant DispatchGroupUtmSyncForPartner
  participant SyncGroupUtmJob
  participant Database
  participant Redis
  PartnerUpdate->>DispatchGroupUtmSyncForPartner: dispatch after partner name change
  DispatchGroupUtmSyncForPartner->>SyncGroupUtmJob: dispatch for each group
  SyncGroupUtmJob->>Database: load enrollments and links
  SyncGroupUtmJob->>Database: batch update resolved URLs and UTM fields
  SyncGroupUtmJob->>Redis: expire link cache entries
  SyncGroupUtmJob->>SyncGroupUtmJob: dispatch next enrollment page
Loading

Possibly related PRs

  • dubinc/dub#3588: Updates overlapping AppsFlyer and default-link handling.
  • dubinc/dub#3747: Modifies the related default-link remapping and group UTM synchronization flow.
  • dubinc/dub#4064: Modifies overlapping partner profile and identity synchronization behavior.

Suggested reviewers: steven-tey, pepeladeira

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.37% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the PR's primary change: adding dynamic UTM parameters for partner links.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch dynamic-utm-params-partner-links
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch dynamic-utm-params-partner-links

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@devkiran
devkiran marked this pull request as ready for review July 31, 2026 05:45

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (3)
apps/web/app/(ee)/api/partners/links/route.ts (1)

131-148: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Resolve macros only after determining the effective link key.

Both routes build utmContext from the optional request key, but pass undefined to processLink when no key is provided. processLink then generates the actual key after {{PARTNER_LINK_KEY}} has already been resolved.

  • apps/web/app/(ee)/api/partners/links/route.ts#L131-L148: generate or reserve the key before resolving the group UTM template, then use it in utmContext and the link payload.
  • apps/web/app/(ee)/api/partners/links/upsert/route.ts#L201-L219: apply the same effective-key flow in the create branch.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/app/`(ee)/api/partners/links/route.ts around lines 131 - 148,
Resolve an effective partner link key before processing UTM macros. In
apps/web/app/(ee)/api/partners/links/route.ts lines 131-148, generate or reserve
the key when the request key is absent, then use that key consistently in
utmContext and the processLink payload. Apply the same effective-key flow in the
create branch of apps/web/app/(ee)/api/partners/links/upsert/route.ts lines
201-219.
apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts (1)

140-189: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Resolve PARTNER_LINK_KEY after duplicate-key handling.

generatePartnerLink appends a suffix when the requested key already exists. Both callers resolve UTM values before this retry. The persisted short-link key can then differ from the URL and UTM-column value for {{PARTNER_LINK_KEY}}.

  • apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts#L140-L189: resolve UTM values with the final currentKey.
  • apps/web/lib/api/partners/create-partner-default-links.ts#L69-L93: resolve UTM values with the final currentKey.

Move this resolution into generatePartnerLink, or return the final key before constructing the URL and UTM columns. Add a duplicate-key test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/app/`(ee)/api/cron/groups/create-default-links/route.ts around lines
140 - 189, Ensure UTM values use the final partner link key after duplicate-key
handling, so {{PARTNER_LINK_KEY}} matches the persisted short-link key. Update
generatePartnerLink or both callers to resolve the URL and UTM columns only
after the final currentKey is determined; apply this in
apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts lines 140-189
and apps/web/lib/api/partners/create-partner-default-links.ts lines 69-93, then
add a duplicate-key test covering the suffixed key.
apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/route.ts (1)

112-125: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Derive and persist the same fallback key before resolving macros.

When the request omits key, partnerLinkKey becomes "". {{PARTNER_LINK_KEY}} then resolves to partner.name, which can differ from the generated short-link key. For example, "John Doe" is not the derived key "john-doe".

Use derivePartnerLinkKey for the macro context. Pass that derived key to processLink when the request omits key. Add coverage for a request without key.

Proposed fix
+import { derivePartnerLinkKey } from "`@/lib/api/partners/generate-partner-link`";
 
-    const partnerLinkKey = key || "";
+    const partnerLinkKey = derivePartnerLinkKey({
+      key,
+      username: partner.username,
+      name: partner.name,
+      email: partner.email,
+    });
     const utmContext = {
       partnerName: partner.name || partnerLinkKey,
-      partnerLinkKey: partnerLinkKey || partner.name || "",
+      partnerLinkKey,
     };
 
     const { link, error, code } = await processLink({
       payload: {
         domain: program.domain,
-        key: key || undefined,
+        key: partnerLinkKey,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/app/`(ee)/api/partner-profile/programs/[programId]/links/route.ts
around lines 112 - 125, Update the link creation flow around partnerLinkKey and
processLink to derive the fallback key with derivePartnerLinkKey when the
request omits key, use that same derived value for the UTM macro context’s
partnerLinkKey, and pass it to processLink so macro resolution and persisted
short-link creation remain consistent. Add coverage for a request without key.
🧹 Nitpick comments (3)
packages/ui/src/utm-builder.tsx (2)

97-100: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the redundant match clause.

value.includes(q) already matches everything that value.slice(2).startsWith(q) matches, because slice(2) is a substring of value. The second clause never changes the result.

♻️ Proposed refactor
-  return suggestions.filter((s) => {
-    const value = s.value.toLowerCase();
-    return value.includes(q) || value.slice(2).startsWith(q);
-  });
+  return suggestions.filter((s) => s.value.toLowerCase().includes(q));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/utm-builder.tsx` around lines 97 - 100, Remove the redundant
value.slice(2).startsWith(q) condition from the suggestions filter in the UTM
builder, leaving the filter based solely on value.includes(q).

258-330: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add combobox semantics to the autocomplete.

The input and the portaled menu carry no ARIA relationship. Screen readers do not announce that the list opened, and they do not announce the highlighted option. The <button> elements also sit at the end of document.body, so Tab moves focus out of the form into the menu.

Wire the pattern explicitly:

  • On the input: role="combobox", aria-expanded, aria-controls, aria-autocomplete="list", aria-activedescendant pointing at the highlighted option id.
  • On the menu: role="listbox" with an id, and role="option" plus aria-selected on each item.
  • On each item: tabIndex={-1}, so keyboard focus stays in the input.
♿ Proposed wiring
         <input
           type="text"
           id={id}
           ref={setInputRef}
+          role="combobox"
+          aria-expanded={menuOpen && filtered.length > 0}
+          aria-controls={`${id}-listbox`}
+          aria-autocomplete="list"
+          aria-activedescendant={
+            menuOpen && filtered.length > 0
+              ? `${id}-option-${highlightedIndex}`
+              : undefined
+          }
           placeholder={placeholder}
           <div
             style={menuStyle}
+            id={`${id}-listbox`}
+            role="listbox"
             className="border-border-subtle flex flex-col rounded-lg border bg-white p-1 shadow-sm"
           >
             {filtered.map((suggestion, index) => (
               <button
                 key={suggestion.value}
                 type="button"
+                id={`${id}-option-${index}`}
+                role="option"
+                aria-selected={highlightedIndex === index}
+                tabIndex={-1}
                 onMouseDown={(e) => e.preventDefault()}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/ui/src/utm-builder.tsx` around lines 258 - 330, Update the
autocomplete input and portaled suggestion menu to use explicit combobox
semantics: add a stable listbox id and connect it through the input’s role,
aria-expanded, aria-controls, aria-autocomplete, and aria-activedescendant
attributes. Mark the menu as role="listbox", each suggestion button as
role="option" with aria-selected tied to highlightedIndex and a unique option
id, and set each item’s tabIndex to -1 so focus remains on the input.
apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-link-settings.tsx (1)

282-286: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the helper text from PARTNER_MACROS.

The prose repeats the macro names that are already imported. If the shared module gains or renames a macro, this text becomes wrong while the autocomplete stays correct. Render the list from the same source.

♻️ Proposed refactor
-                <p className="text-content-muted text-xs">
-                  Dynamic values:{" "}
-                  <code className="font-mono">{"{{PARTNER_NAME}}"}</code>,{" "}
-                  <code className="font-mono">{"{{PARTNER_LINK_KEY}}"}</code>
-                </p>
+                <p className="text-content-muted text-xs">
+                  Dynamic values:{" "}
+                  {PARTNER_MACROS.map((m, idx) => (
+                    <Fragment key={m.macro}>
+                      {idx > 0 && ", "}
+                      <code className="font-mono">{m.macro}</code>
+                    </Fragment>
+                  ))}
+                </p>

Add the Fragment import:

import { Fragment, useState } from "react";
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/web/app/app.dub.co/`(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-link-settings.tsx
around lines 282 - 286, Update the helper text near the group-link settings UI
to derive its macro list from the imported PARTNER_MACROS source instead of
hardcoded names. Render each macro name from that collection with the existing
styling and punctuation, adding the React Fragment import if needed for list
rendering.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/ui/src/utm-builder.tsx`:
- Around line 176-184: Update insertSuggestion to consume the full open or
completed macro when replacing a suggestion: use the detected token’s end
position, including the closing }} when present, instead of always slicing the
tail from caret. Preserve the existing fallback behavior for values without a
detected token, and ensure nextCaret is based on the replacement start plus
suggestion.value.length.

---

Outside diff comments:
In `@apps/web/app/`(ee)/api/cron/groups/create-default-links/route.ts:
- Around line 140-189: Ensure UTM values use the final partner link key after
duplicate-key handling, so {{PARTNER_LINK_KEY}} matches the persisted short-link
key. Update generatePartnerLink or both callers to resolve the URL and UTM
columns only after the final currentKey is determined; apply this in
apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts lines 140-189
and apps/web/lib/api/partners/create-partner-default-links.ts lines 69-93, then
add a duplicate-key test covering the suffixed key.

In `@apps/web/app/`(ee)/api/partner-profile/programs/[programId]/links/route.ts:
- Around line 112-125: Update the link creation flow around partnerLinkKey and
processLink to derive the fallback key with derivePartnerLinkKey when the
request omits key, use that same derived value for the UTM macro context’s
partnerLinkKey, and pass it to processLink so macro resolution and persisted
short-link creation remain consistent. Add coverage for a request without key.

In `@apps/web/app/`(ee)/api/partners/links/route.ts:
- Around line 131-148: Resolve an effective partner link key before processing
UTM macros. In apps/web/app/(ee)/api/partners/links/route.ts lines 131-148,
generate or reserve the key when the request key is absent, then use that key
consistently in utmContext and the processLink payload. Apply the same
effective-key flow in the create branch of
apps/web/app/(ee)/api/partners/links/upsert/route.ts lines 201-219.

---

Nitpick comments:
In
`@apps/web/app/app.dub.co/`(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-link-settings.tsx:
- Around line 282-286: Update the helper text near the group-link settings UI to
derive its macro list from the imported PARTNER_MACROS source instead of
hardcoded names. Render each macro name from that collection with the existing
styling and punctuation, adding the React Fragment import if needed for list
rendering.

In `@packages/ui/src/utm-builder.tsx`:
- Around line 97-100: Remove the redundant value.slice(2).startsWith(q)
condition from the suggestions filter in the UTM builder, leaving the filter
based solely on value.includes(q).
- Around line 258-330: Update the autocomplete input and portaled suggestion
menu to use explicit combobox semantics: add a stable listbox id and connect it
through the input’s role, aria-expanded, aria-controls, aria-autocomplete, and
aria-activedescendant attributes. Mark the menu as role="listbox", each
suggestion button as role="option" with aria-selected tied to highlightedIndex
and a unique option id, and set each item’s tabIndex to -1 so focus remains on
the input.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 808a48a3-ccf8-46ae-9ce9-0546a44ec1a7

📥 Commits

Reviewing files that changed from the base of the PR and between dc81d39 and bf54757.

📒 Files selected for processing (25)
  • apps/web/app/(ee)/api/cron/groups/create-default-links/route.ts
  • apps/web/app/(ee)/api/cron/groups/remap-default-links/route.ts
  • apps/web/app/(ee)/api/cron/groups/sync-utm/route.ts
  • apps/web/app/(ee)/api/cron/groups/update-default-links/route.ts
  • apps/web/app/(ee)/api/groups/[groupIdOrSlug]/route.ts
  • apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/[linkId]/route.ts
  • apps/web/app/(ee)/api/partner-profile/programs/[programId]/links/route.ts
  • apps/web/app/(ee)/api/partners/links/route.ts
  • apps/web/app/(ee)/api/partners/links/upsert/route.ts
  • apps/web/app/api/utm/[id]/route.ts
  • apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/links/group-link-settings.tsx
  • apps/web/lib/api/partners/create-partner-default-links.ts
  • apps/web/lib/api/utm/extract-and-resolve-utm-params.ts
  • apps/web/lib/integrations/appsflyer/apply-parameters.ts
  • apps/web/lib/integrations/appsflyer/constants.ts
  • apps/web/lib/integrations/appsflyer/macro-template.ts
  • apps/web/lib/integrations/appsflyer/schema.ts
  • apps/web/lib/integrations/appsflyer/ui/settings.tsx
  • apps/web/lib/jobs/handlers/sync-group-utm-job.ts
  • apps/web/lib/jobs/registry.ts
  • apps/web/lib/partners/macros.ts
  • apps/web/lib/zod/schemas/utm.ts
  • apps/web/tests/misc/partner-macros.test.ts
  • apps/web/ui/modals/add-partner-link-modal.tsx
  • packages/ui/src/utm-builder.tsx
💤 Files with no reviewable changes (2)
  • apps/web/lib/integrations/appsflyer/constants.ts
  • apps/web/lib/integrations/appsflyer/macro-template.ts

Comment thread packages/ui/src/utm-builder.tsx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant