Skip to content

Add PartnerNetworkStatus enum#3876

Open
steven-tey wants to merge 16 commits intomainfrom
network-status
Open

Add PartnerNetworkStatus enum#3876
steven-tey wants to merge 16 commits intomainfrom
network-status

Conversation

@steven-tey
Copy link
Copy Markdown
Collaborator

@steven-tey steven-tey commented May 8, 2026

Summary by CodeRabbit

  • New Features

    • Network Approval Guide: expandable checklist, draft progress indicator, and "Submit application" confirmation with success/error toasts.
    • Admin: Network Applications list and Trusted Partners management (add/remove/verify) plus new Partners nav tabs and network applications page.
  • Refactor

    • Replaced prior discovery checklist with a unified network-approval flow and added partner network status tracking.
  • Style

    • Increased bottom spacing on invoices page.
  • Other

    • Reserved slugs updated to include "dub".

@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented May 8, 2026

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

Project Deployment Actions Updated (UTC)
dub Error Error May 10, 2026 6:42am

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 8, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Replaces the partner discovery checklist with a network-approval flow: DB and Zod schema additions for PartnerNetworkStatus, renamed checklist helpers, new NetworkApprovalGuide UI and submit action, admin APIs/pages for network applications and trusted partners, and related consumer updates and cleanup.

Changes

Partner Network Approval System

Layer / File(s) Summary
Schema & Type Definitions
packages/prisma/schema/partner.prisma, packages/prisma/schema/tag.prisma, apps/web/lib/zod/schemas/partners.ts, apps/web/lib/zod/schemas/partner-profile.ts
Adds PartnerNetworkStatus enum and networkStatus + addedToNetworkAt fields to Partner; updates Zod schemas to include networkStatus and renames platform/profile schema pieces; note: tag.prisma final } removal present in diff.
Core Library Refactoring
apps/web/lib/network/get-network-approval-requirements.ts, apps/web/lib/network/get-network-profile-checklist-progress.ts, callers...
Renames getDiscoverabilityRequirementsgetNetworkApprovalRequirements and getPartnerProfileChecklistProgressgetNetworkProfileChecklistProgress; updates callers (program header, create-program-application, referrals-token route) to use new helpers.
Network Approval Guide Component
apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx
New component fetches partner, computes checklist progress, shows draft progress or status badge, renders expandable checklist, and wires a confirmation modal that submits via a server action.
Profile Page Integration
apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx
ProfileSettingsPageClient now renders NetworkApprovalGuide when partner exists, replacing the removed discovery-guide conditional and simplifying imports.
Deprecated Code Removal
apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx, apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/use-partner-discovery-requirements.ts
Removes the old ProfileDiscoveryGuide component, its ConditionalLink helper, and the usePartnerDiscoveryRequirements hook.
Action & Schema Wiring
apps/web/lib/actions/partners/submit-network-profile.ts, apps/web/lib/actions/partners/update-partner-profile.ts, apps/web/lib/zod/schemas/program-application.ts
Adds submitNetworkProfileAction (records networkStatus change); updates updatePartnerProfileSchema to use PartnerProfileDetailsSchema and change username validation; PartnerApplicationSchema now uses OldPartnerPlatformsFields.shape.
Admin UI & API Changes
apps/web/app/(ee)/api/admin/partners/*, apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/*
Adds admin route for network applications and fraud under /api/admin/partners/..., new trusted partners admin APIs, new partners nav tabs and layouts, network applications page, trusted partners page, and re-exports/refactors of some admin routes.
Miscellaneous
apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx, packages/prisma/schema/application.prisma, apps/web/ui/partners/partner-avatar.tsx, apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx, packages/utils/src/constants/reserved-slugs.ts, apps/web/lib/zod/schemas/workspaces.ts
Small edits: invoice spacing, Prisma whitespace change, narrower PartnerAvatar prop type, username payload normalization on profile submit, add "dub" to RESERVED_SLUGS, and synchronous reserved-slug refinement for workspace slug.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • dubinc/dub#3614: Related edits touching PartnerSchema and partner-profile UI; overlapping schema/component changes.
  • dubinc/dub#3706: Related changes touching the admin fraud-alerts surface and partner data model (routes, schemas, UI).

Suggested reviewers

  • devkiran
  • pepeladeira

Poem

🐰 A network of partners takes shape with care,
New statuses drafted, submissions in the air,
Old guides hop away, while new flows brightly share,
A checklist, a modal, a toast to declare—
Hooray for small rabbits patching code with flair!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title 'Add PartnerNetworkStatus enum' is too narrow and misleading—it describes only a single data model change, while the changeset comprehensively refactors partner network approval workflows across UI, actions, and APIs, renames related utilities, reorganizes admin dashboards, and restructures multiple schema definitions. Revise the title to reflect the core objective, such as 'Refactor partner approval workflow with network status tracking' or 'Introduce partner network approval system with status tracking and admin dashboard'.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch network-status

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

❤️ Share

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

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx (1)

143-156: 💤 Low value

ConditionalLink spreads Partial<HTMLProps<HTMLAnchorElement>> onto Next.js Link — minor type mismatch.

HTMLProps<HTMLAnchorElement> and Next.js Link's prop type are different shapes (Link expects href: string | UrlObject, not string | undefined). TypeScript may complain in strict mode when ...rest is spread. Consider using ComponentProps<typeof Link> instead, or an explicit union type:

-function ConditionalLink({
-  href,
-  className,
-  children,
-  ...rest
-}: Partial<HTMLProps<HTMLAnchorElement>>) {
+function ConditionalLink({
+  href,
+  className,
+  children,
+  ...rest
+}: Omit<ComponentProps<typeof Link>, "href"> & { href?: string }) {
🤖 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)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx
around lines 143 - 156, The ConditionalLink component currently types its props
as Partial<HTMLProps<HTMLAnchorElement>> which mismatches Next.js Link props and
causes TypeScript errors when spreading ...rest; change the prop typing for
ConditionalLink to use ComponentProps<typeof Link> (or a narrow union that
matches Link's href type and anchor props) and include href as the
Link-compatible type (string | UrlObject | undefined) so that spreading ...rest
onto <Link> is type-safe; update the function signature and prop destructuring
(the ConditionalLink identifier) to that new prop type and keep the same runtime
logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/web/app/`(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx:
- Around line 21-38: Move all React hooks to the top of the component so they
run unconditionally: call useState (isExpanded, setIsExpanded) and
useConfirmModal (setShowConfirmModal, confirmModal) before the early return and
before invoking getNetworkProfileChecklistProgress. Keep the pure helper call
getNetworkProfileChecklistProgress guarded by a conditional/ternary that uses
partner ? getNetworkProfileChecklistProgress({ partner }) : { tasks: [],
completedCount: 0, totalCount: 0, isComplete: false } (or similar safe defaults)
so the rest of the render can use tasks/completedCount/totalCount/isComplete
without calling hooks conditionally. Ensure you still early-return null when
partner is absent if that’s required, but do not place any hook calls after that
return.
- Around line 35-37: The onConfirm handler currently only calls toast.success
and never submits the application; update the onConfirm in
network-approval-guide.tsx to call the server action
submitNetworkApplicationAction (await its result), then on success show
toast.success and ensure partner.networkStatus is updated (or refetch/refresh
the parent data) so it no longer remains "draft"; also handle and surface errors
by catching exceptions and calling toast.error with a helpful message if
submitNetworkApplicationAction fails.

---

Nitpick comments:
In
`@apps/web/app/`(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx:
- Around line 143-156: The ConditionalLink component currently types its props
as Partial<HTMLProps<HTMLAnchorElement>> which mismatches Next.js Link props and
causes TypeScript errors when spreading ...rest; change the prop typing for
ConditionalLink to use ComponentProps<typeof Link> (or a narrow union that
matches Link's href type and anchor props) and include href as the
Link-compatible type (string | UrlObject | undefined) so that spreading ...rest
onto <Link> is type-safe; update the function signature and prop destructuring
(the ConditionalLink identifier) to that new prop type and keep the same runtime
logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: bd6b5feb-d041-459d-beed-ba3b9e80bb20

📥 Commits

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

📒 Files selected for processing (14)
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/page-client.tsx
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/use-partner-discovery-requirements.ts
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
  • apps/web/app/api/user/referrals-token/route.ts
  • apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/invoices/page.tsx
  • apps/web/lib/actions/partners/create-program-application.ts
  • apps/web/lib/network/get-network-approval-requirements.ts
  • apps/web/lib/network/get-network-profile-checklist-progress.ts
  • apps/web/lib/zod/schemas/partners.ts
  • packages/prisma/schema/application.prisma
  • packages/prisma/schema/partner.prisma
  • packages/prisma/schema/tag.prisma
💤 Files with no reviewable changes (2)
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/use-partner-discovery-requirements.ts
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-discovery-guide.tsx

Comment on lines +21 to +38
if (!partner) return null;

const { tasks, completedCount, totalCount, isComplete } =
getNetworkProfileChecklistProgress({
partner,
});

const [isExpanded, setIsExpanded] = useState(isComplete ? false : true);

const { setShowConfirmModal, confirmModal } = useConfirmModal({
title: "Submit application",
description:
"Are you sure you want to submit your Dub Network application for review? You won't be able to make changes to your application after submitting it.",
confirmText: "Confirm submission",
onConfirm: () => {
toast.success("Application submitted successfully");
},
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical: Rules of Hooks violation — useState and useConfirmModal called after an early return.

Hooks must always be used at the top level of a React function, before any early returns. Both useState (line 28) and useConfirmModal (line 30) are invoked only when partner is truthy, skipping them entirely on renders where partner is undefined. This will produce a runtime error: "React Hook 'useState' is called conditionally. React Hooks must be called in the exact same order in every component render."

Move all hooks above the early return and guard the pure-function call with a ternary:

🐛 Proposed fix
 export function NetworkApprovalGuide() {
   const { partner } = usePartnerProfile();

-  if (!partner) return null;
-
-  const { tasks, completedCount, totalCount, isComplete } =
-    getNetworkProfileChecklistProgress({
-      partner,
-    });
-
-  const [isExpanded, setIsExpanded] = useState(isComplete ? false : true);
-
-  const { setShowConfirmModal, confirmModal } = useConfirmModal({
+  const { tasks, completedCount, totalCount, isComplete } = partner
+    ? getNetworkProfileChecklistProgress({ partner })
+    : { tasks: [], completedCount: 0, totalCount: 0, isComplete: false };
+
+  const [isExpanded, setIsExpanded] = useState(!isComplete);
+
+  const { setShowConfirmModal, confirmModal } = useConfirmModal({
     title: "Submit application",
     description:
       "Are you sure you want to submit your Dub Network application for review? You won't be able to make changes to your application after submitting it.",
     confirmText: "Confirm submission",
     onConfirm: () => {
       toast.success("Application submitted successfully");
     },
   });

+  if (!partner) return null;
+
   return (
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!partner) return null;
const { tasks, completedCount, totalCount, isComplete } =
getNetworkProfileChecklistProgress({
partner,
});
const [isExpanded, setIsExpanded] = useState(isComplete ? false : true);
const { setShowConfirmModal, confirmModal } = useConfirmModal({
title: "Submit application",
description:
"Are you sure you want to submit your Dub Network application for review? You won't be able to make changes to your application after submitting it.",
confirmText: "Confirm submission",
onConfirm: () => {
toast.success("Application submitted successfully");
},
});
const { tasks, completedCount, totalCount, isComplete } = partner
? getNetworkProfileChecklistProgress({ partner })
: { tasks: [], completedCount: 0, totalCount: 0, isComplete: false };
const [isExpanded, setIsExpanded] = useState(!isComplete);
const { setShowConfirmModal, confirmModal } = useConfirmModal({
title: "Submit application",
description:
"Are you sure you want to submit your Dub Network application for review? You won't be able to make changes to your application after submitting it.",
confirmText: "Confirm submission",
onConfirm: () => {
toast.success("Application submitted successfully");
},
});
if (!partner) return null;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/web/app/`(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx
around lines 21 - 38, Move all React hooks to the top of the component so they
run unconditionally: call useState (isExpanded, setIsExpanded) and
useConfirmModal (setShowConfirmModal, confirmModal) before the early return and
before invoking getNetworkProfileChecklistProgress. Keep the pure helper call
getNetworkProfileChecklistProgress guarded by a conditional/ternary that uses
partner ? getNetworkProfileChecklistProgress({ partner }) : { tasks: [],
completedCount: 0, totalCount: 0, isComplete: false } (or similar safe defaults)
so the rest of the render can use tasks/completedCount/totalCount/isComplete
without calling hooks conditionally. Ensure you still early-return null when
partner is absent if that’s required, but do not place any hook calls after that
return.

Comment thread apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/web/lib/actions/partners/update-partner-profile.ts (1)

62-73: ⚡ Quick win

Attach the company-name refine error to the companyName field.

The cross-field .refine has no path, so the error surfaces at the form root. The form reads errors.companyName to render the inline error styling on the Legal company name input, so users won't see this message where it's expected.

♻️ Proposed fix
   .refine(
     (data) => {
       if (data.profileType === "company") {
         return !!data.companyName;
       }

       return true;
     },
     {
       message: "Legal company name is required when profile type is 'company'.",
+      path: ["companyName"],
     },
   );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/lib/actions/partners/update-partner-profile.ts` around lines 62 -
73, The cross-field zod .refine on the schema (used in update-partner-profile)
currently validates that when data.profileType === "company" a companyName
exists but has no path, so the error is attached to the form root; change the
.refine call to include a path pointing to the companyName field (e.g., path:
["companyName"]) so the validation error is attached to errors.companyName and
shows inline on the Legal company name input while keeping the same message and
condition.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/app/`(ee)/admin.dub.co/(dashboard)/partners/trusted/page.tsx:
- Around line 502-506: The partner details card currently renders a raw <img>
with src={activePartner.image || ""} which can produce broken requests when
image is missing; replace that <img> block with the existing PartnerAvatar
component (use the same className, alt text from activePartner.name, and pass
activePartner.image as the image prop) so PartnerAvatar can provide the safe
fallback/no-src behavior instead of rendering an empty src; update the JSX in
the activePartner rendering area (replace the img element) to use <PartnerAvatar
image={activePartner.image} alt={activePartner.name} className="size-12 shrink-0
rounded-full border border-neutral-100 bg-neutral-100 object-cover" /> and
ensure PartnerAvatar is imported if not already.

In `@apps/web/lib/actions/partners/submit-network-profile.ts`:
- Around line 18-41: The current check uses the request-scoped
partner.networkStatus but then calls prisma.partner.update({ where: { id:
partner.id } }) which can overwrite a concurrent change; make the status
transition atomic by including the expected status in the update predicate and
checking the result. Replace the plain update with an updateMany (or update with
a compound where) that includes where: { id: partner.id, networkStatus: 'draft'
} and set data: { networkStatus: 'submitted', changeHistoryLog:
partnerChangeHistoryLog }; then verify the affected count (or catch a
not-found/no-rows-affected) and throw an error if no row was updated so you
don’t overwrite concurrent transitions. Ensure you still build
partnerChangeHistoryLog before the update and reference partner.networkStatus,
partnerChangeHistoryLog, and prisma.partner.update/updateMany in the fix.

In `@apps/web/lib/actions/partners/update-partner-profile.ts`:
- Around line 34-50: The username validation currently runs reserved-slug and
async reserved-username checks on every save and can reject unchanged usernames;
modify the logic so those checks are skipped when the submitted username equals
the stored partner username: move the reserved-slug/RESERVED_SLUGS,
validSlugRegex and isReservedUsername() checks out of the zod refine or
short-circuit them, and instead run them inside updatePartnerProfileAction only
when username is provided and username !== partner.username (i.e., guard the
validity checks and the uniqueness check so they execute only for a changed
username), ensuring existing partners with unchanged reserved usernames can
still update their profiles.

---

Nitpick comments:
In `@apps/web/lib/actions/partners/update-partner-profile.ts`:
- Around line 62-73: The cross-field zod .refine on the schema (used in
update-partner-profile) currently validates that when data.profileType ===
"company" a companyName exists but has no path, so the error is attached to the
form root; change the .refine call to include a path pointing to the companyName
field (e.g., path: ["companyName"]) so the validation error is attached to
errors.companyName and shows inline on the Legal company name input while
keeping the same message and condition.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fbd52dd5-8e40-4fab-a097-2c83cb1724c7

📥 Commits

Reviewing files that changed from the base of the PR and between 89f1d1b and 48f7ea4.

📒 Files selected for processing (23)
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/fraud/page.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/fraud/review-fraud-alert-sheet.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/layout.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/network/page.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/page.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/partners-nav-tabs.tsx
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/partners/trusted/page.tsx
  • apps/web/app/(ee)/api/admin/fraud-alerts/route.ts
  • apps/web/app/(ee)/api/admin/partners/[partnerId]/platforms/route.ts
  • apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts
  • apps/web/app/(ee)/api/admin/partners/fraud/route.ts
  • apps/web/app/(ee)/api/admin/partners/network/route.ts
  • apps/web/app/(ee)/api/admin/partners/route.ts
  • apps/web/app/(ee)/api/admin/partners/trusted/route.ts
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx
  • apps/web/lib/actions/partners/submit-network-profile.ts
  • apps/web/lib/actions/partners/update-partner-profile.ts
  • apps/web/lib/zod/schemas/partner-profile.ts
  • apps/web/lib/zod/schemas/workspaces.ts
  • apps/web/ui/partners/partner-avatar.tsx
  • packages/utils/src/constants/reserved-slugs.ts
💤 Files with no reviewable changes (1)
  • apps/web/app/(ee)/admin.dub.co/(dashboard)/layout-nav-client.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/network-approval-guide.tsx

Comment on lines +502 to +506
<img
src={activePartner.image || ""}
alt={activePartner.name}
className="size-12 shrink-0 rounded-full border border-neutral-100 bg-neutral-100 object-cover"
/>
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Avoid rendering an empty image src in the partner details card.

On Line 503, src={activePartner.image || ""} can render a broken image and trigger avoidable requests when image is missing. Reuse PartnerAvatar here for a safe fallback.

Suggested fix
-                  <div className="flex items-start gap-3">
-                    <img
-                      src={activePartner.image || ""}
-                      alt={activePartner.name}
-                      className="size-12 shrink-0 rounded-full border border-neutral-100 bg-neutral-100 object-cover"
-                    />
+                  <div className="flex items-start gap-3">
+                    <PartnerAvatar
+                      partner={{
+                        id: activePartner.id,
+                        name: activePartner.name,
+                        image: activePartner.image,
+                      }}
+                      className="size-12 shrink-0 border border-neutral-100 bg-neutral-100 object-cover"
+                    />
                     <div className="min-w-0">
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<img
src={activePartner.image || ""}
alt={activePartner.name}
className="size-12 shrink-0 rounded-full border border-neutral-100 bg-neutral-100 object-cover"
/>
<div className="flex items-start gap-3">
<PartnerAvatar
partner={{
id: activePartner.id,
name: activePartner.name,
image: activePartner.image,
}}
className="size-12 shrink-0 border border-neutral-100 bg-neutral-100 object-cover"
/>
<div className="min-w-0">
🤖 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)/admin.dub.co/(dashboard)/partners/trusted/page.tsx around
lines 502 - 506, The partner details card currently renders a raw <img> with
src={activePartner.image || ""} which can produce broken requests when image is
missing; replace that <img> block with the existing PartnerAvatar component (use
the same className, alt text from activePartner.name, and pass
activePartner.image as the image prop) so PartnerAvatar can provide the safe
fallback/no-src behavior instead of rendering an empty src; update the JSX in
the activePartner rendering area (replace the img element) to use <PartnerAvatar
image={activePartner.image} alt={activePartner.name} className="size-12 shrink-0
rounded-full border border-neutral-100 bg-neutral-100 object-cover" /> and
ensure PartnerAvatar is imported if not already.

Comment on lines +18 to +41
if (partner.networkStatus !== "draft") {
throw new Error("Partner network profile not in 'draft' status");
}

const partnerChangeHistoryLog = partner.changeHistoryLog
? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)
: [];

partnerChangeHistoryLog.push({
field: "networkStatus",
from: partner.networkStatus,
to: "submitted",
changedAt: new Date(),
});

await prisma.partner.update({
where: {
id: partner.id,
},
data: {
networkStatus: "submitted",
changeHistoryLog: partnerChangeHistoryLog,
},
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Guard the status transition at write time.

Line 18 validates networkStatus on the request-scoped partner, but Line 33 updates by id only. A concurrent approval/rejection or profile update in between can be overwritten back to "submitted", along with a stale changeHistoryLog.

Suggested fix
-    if (partner.networkStatus !== "draft") {
-      throw new Error("Partner network profile not in 'draft' status");
-    }
-
-    const partnerChangeHistoryLog = partner.changeHistoryLog
-      ? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)
-      : [];
-
-    partnerChangeHistoryLog.push({
-      field: "networkStatus",
-      from: partner.networkStatus,
-      to: "submitted",
-      changedAt: new Date(),
-    });
-
-    await prisma.partner.update({
-      where: {
-        id: partner.id,
-      },
-      data: {
-        networkStatus: "submitted",
-        changeHistoryLog: partnerChangeHistoryLog,
-      },
-    });
+    await prisma.$transaction(async (tx) => {
+      const freshPartner = await tx.partner.findUnique({
+        where: { id: partner.id },
+        select: {
+          networkStatus: true,
+          changeHistoryLog: true,
+        },
+      });
+
+      if (!freshPartner || freshPartner.networkStatus !== "draft") {
+        throw new Error("Partner network profile not in 'draft' status");
+      }
+
+      const partnerChangeHistoryLog = freshPartner.changeHistoryLog
+        ? partnerProfileChangeHistoryLogSchema.parse(
+            freshPartner.changeHistoryLog,
+          )
+        : [];
+
+      partnerChangeHistoryLog.push({
+        field: "networkStatus",
+        from: freshPartner.networkStatus,
+        to: "submitted",
+        changedAt: new Date(),
+      });
+
+      await tx.partner.update({
+        where: { id: partner.id },
+        data: {
+          networkStatus: "submitted",
+          changeHistoryLog: partnerChangeHistoryLog,
+        },
+      });
+    });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (partner.networkStatus !== "draft") {
throw new Error("Partner network profile not in 'draft' status");
}
const partnerChangeHistoryLog = partner.changeHistoryLog
? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)
: [];
partnerChangeHistoryLog.push({
field: "networkStatus",
from: partner.networkStatus,
to: "submitted",
changedAt: new Date(),
});
await prisma.partner.update({
where: {
id: partner.id,
},
data: {
networkStatus: "submitted",
changeHistoryLog: partnerChangeHistoryLog,
},
});
await prisma.$transaction(async (tx) => {
const freshPartner = await tx.partner.findUnique({
where: { id: partner.id },
select: {
networkStatus: true,
changeHistoryLog: true,
},
});
if (!freshPartner || freshPartner.networkStatus !== "draft") {
throw new Error("Partner network profile not in 'draft' status");
}
const partnerChangeHistoryLog = freshPartner.changeHistoryLog
? partnerProfileChangeHistoryLogSchema.parse(
freshPartner.changeHistoryLog,
)
: [];
partnerChangeHistoryLog.push({
field: "networkStatus",
from: freshPartner.networkStatus,
to: "submitted",
changedAt: new Date(),
});
await tx.partner.update({
where: { id: partner.id },
data: {
networkStatus: "submitted",
changeHistoryLog: partnerChangeHistoryLog,
},
});
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/lib/actions/partners/submit-network-profile.ts` around lines 18 -
41, The current check uses the request-scoped partner.networkStatus but then
calls prisma.partner.update({ where: { id: partner.id } }) which can overwrite a
concurrent change; make the status transition atomic by including the expected
status in the update predicate and checking the result. Replace the plain update
with an updateMany (or update with a compound where) that includes where: { id:
partner.id, networkStatus: 'draft' } and set data: { networkStatus: 'submitted',
changeHistoryLog: partnerChangeHistoryLog }; then verify the affected count (or
catch a not-found/no-rows-affected) and throw an error if no row was updated so
you don’t overwrite concurrent transitions. Ensure you still build
partnerChangeHistoryLog before the update and reference partner.networkStatus,
partnerChangeHistoryLog, and prisma.partner.update/updateMany in the fix.

Comment on lines +34 to +50
username: z
.string()
.trim()
.toLowerCase()
.min(3)
.max(100)
.refine(
async (v) => {
if (!v) return true;
if (!validSlugRegex.test(v) || RESERVED_SLUGS.includes(v))
return false;
if (await isReservedUsername(v)) return false;
return true;
},
{ message: "Invalid username" },
)
.optional(),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm whether any partners currently have a username that is now reserved
# (and therefore would be locked out by this validation).
rg -nP --type=ts -C2 'RESERVED_SLUGS\s*=\s*\[' 
rg -nP --type=ts -C2 '\bisReservedUsername\s*\(' 
rg -nP --type=ts -C3 '\bpartner\.username\b'

Repository: dubinc/dub

Length of output: 4447


🏁 Script executed:

#!/bin/bash
# Get the complete update-partner-profile.ts file
wc -l apps/web/lib/actions/partners/update-partner-profile.ts

Repository: dubinc/dub

Length of output: 114


🏁 Script executed:

#!/bin/bash
# Read the full update-partner-profile.ts file
cat -n apps/web/lib/actions/partners/update-partner-profile.ts

Repository: dubinc/dub

Length of output: 10561


🏁 Script executed:

#!/bin/bash
# Check the profile form to understand form field handling
rg -nP --type=ts -A10 -B5 'data\.username.*\|\|' apps/web/components/partners/profile-details-form.tsx

Repository: dubinc/dub

Length of output: 148


🏁 Script executed:

#!/bin/bash
# Find the profile details form
fd -type f -name '*profile*form*' apps/web/

Repository: dubinc/dub

Length of output: 225


🏁 Script executed:

#!/bin/bash
# Also search for any form files that might handle partner profile
fd -type f -name '*details*form*' apps/web/components/partners/

Repository: dubinc/dub

Length of output: 225


🏁 Script executed:

#!/bin/bash
# Find the profile details form
fd -name '*profile*form*' apps/web/

Repository: dubinc/dub

Length of output: 285


🏁 Script executed:

#!/bin/bash
# Search for any form-related files in partners components
fd -name '*form*' apps/web/components/partners/

Repository: dubinc/dub

Length of output: 285


🏁 Script executed:

#!/bin/bash
# Search for references to updatePartnerProfileAction
rg -l 'updatePartnerProfileAction' apps/web/

Repository: dubinc/dub

Length of output: 338


🏁 Script executed:

#!/bin/bash
# Read the profile-details-form.tsx file
wc -l apps/web/app/\(ee\)/partners.dub.co/\(dashboard\)/profile/profile-details-form.tsx

Repository: dubinc/dub

Length of output: 137


🏁 Script executed:

#!/bin/bash
# Read the profile-details-form.tsx file
cat -n "apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx"

Repository: dubinc/dub

Length of output: 21515


Reserved-username check runs on every profile save and can lock out existing partners.

The schema validation (lines 34-50) checks username against validSlugRegex, RESERVED_SLUGS, and the async isReservedUsername() on every form submission. Since the username field is commented out in the form (profile-details-form.tsx lines 345-367) and the form always re-submits data.username || undefined from the stored partner username, any existing partner whose username is now in RESERVED_SLUGS becomes unable to update their profile.

For example, this PR adds "dub" to RESERVED_SLUGS, so any partner with partner.username === "dub" will fail schema validation when saving any profile changes—but they cannot edit the username field to fix it.

The check at line 119 only validates for duplicate usernames; it does not prevent the reserved-slug/reserved-username validation from blocking the request. Skip these checks when the value matches the stored username.

🛡️ Proposed fix (action layer)
-    username: z
-      .string()
-      .trim()
-      .toLowerCase()
-      .min(3)
-      .max(100)
-      .refine(
-        async (v) => {
-          if (!v) return true;
-          if (!validSlugRegex.test(v) || RESERVED_SLUGS.includes(v))
-            return false;
-          if (await isReservedUsername(v)) return false;
-          return true;
-        },
-        { message: "Invalid username" },
-      )
-      .optional(),
+    username: z.string().trim().toLowerCase().min(3).max(100).optional(),

Then validate inside updatePartnerProfileAction only when username && username !== partner.username:

if (username && username !== partner.username) {
  if (!validSlugRegex.test(username) || RESERVED_SLUGS.includes(username)) {
    throw new Error("Invalid username");
  }
  if (await isReservedUsername(username)) {
    throw new Error("Invalid username");
  }
  // ...existing uniqueness check
}

Side notes: The if (!v) return true branch is unreachable because .min(3) runs before the refine; and the single "Invalid username" message conflates three distinct failure modes.

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

In `@apps/web/lib/actions/partners/update-partner-profile.ts` around lines 34 -
50, The username validation currently runs reserved-slug and async
reserved-username checks on every save and can reject unchanged usernames;
modify the logic so those checks are skipped when the submitted username equals
the stored partner username: move the reserved-slug/RESERVED_SLUGS,
validSlugRegex and isReservedUsername() checks out of the zod refine or
short-circuit them, and instead run them inside updatePartnerProfileAction only
when username is provided and username !== partner.username (i.e., guard the
validity checks and the uniqueness check so they execute only for a changed
username), ensuring existing partners with unchanged reserved usernames can
still update their profiles.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

Inline comments:
In
`@apps/web/app/`(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx:
- Around line 101-104: The onConfirm handler currently awaits
submitNetworkProfileAction() directly so thrown errors are hidden by
next-safe-action; wrap submitNetworkProfileAction with useAction (as done in
network-approval-guide.tsx) and call that wrapper inside onConfirm, providing
onSuccess to call mutate() and onError to handle/report the error (and prevent
mutate on failure); update the handler to use the returned action runner from
useAction for submitNetworkProfileAction and wire onSuccess/onError callbacks to
keep UI state consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a5574464-8339-4921-99be-a0c7af10e411

📥 Commits

Reviewing files that changed from the base of the PR and between bea329e and 3696033.

📒 Files selected for processing (2)
  • apps/web/app/(ee)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
  • apps/web/lib/actions/partners/submit-network-profile.ts

Comment on lines +101 to +104
onConfirm: async () => {
await submitNetworkProfileAction();
await mutate();
},
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Verify next-safe-action usage patterns in the codebase to confirm error handling conventions

# Check how other actions handle results and errors
rg -n -A5 -B2 'executeAsync|\.action\(' --type=ts --type=tsx -g '!node_modules' | head -80

Repository: dubinc/dub

Length of output: 82


🏁 Script executed:

#!/bin/bash
# Find the specific file and examine the context
find . -type f -name "header-controls.tsx" -path "*programs/marketplace*"

Repository: dubinc/dub

Length of output: 157


🏁 Script executed:

#!/bin/bash
# Search for action usage patterns with corrected file type flag
rg -n -A5 -B2 'executeAsync|\.action\(' --type=ts -g '!node_modules' | head -100

Repository: dubinc/dub

Length of output: 7860


🏁 Script executed:

#!/bin/bash
# Search for submitNetworkProfileAction definition
rg -n 'submitNetworkProfileAction' --type=ts --type=js -g '!node_modules'

Repository: dubinc/dub

Length of output: 820


🏁 Script executed:

#!/bin/bash
# Examine the header-controls.tsx file around the problematic lines
cat -n apps/web/app/\(ee\)/partners.dub.co/\(dashboard\)/programs/marketplace/\[programSlug\]/header-controls.tsx | sed -n '90,115p'

Repository: dubinc/dub

Length of output: 1004


🏁 Script executed:

#!/bin/bash
# Examine the submitNetworkProfileAction definition
cat -n apps/web/lib/actions/partners/submit-network-profile.ts

Repository: dubinc/dub

Length of output: 2734


🏁 Script executed:

#!/bin/bash
# Examine how it's used in network-approval-guide.tsx
cat -n apps/web/app/\(ee\)/partners.dub.co/\(dashboard\)/profile/network-approval-guide.tsx | sed -n '40,70p'

Repository: dubinc/dub

Length of output: 1183


🏁 Script executed:

#!/bin/bash
# Look for how other actions handle results in callbacks/executeAsync
rg -n -A10 'executeAsync.*await' --type=ts -g '!node_modules' | head -150

Repository: dubinc/dub

Length of output: 36


🏁 Script executed:

#!/bin/bash
# Check if header-controls.tsx imports useAction and what other imports it has
head -30 apps/web/app/\(ee\)/partners.dub.co/\(dashboard\)/programs/marketplace/\[programSlug\]/header-controls.tsx

Repository: dubinc/dub

Length of output: 1341


🏁 Script executed:

#!/bin/bash
# Look for useAction hook definition/import patterns
rg -n 'from.*useAction|export.*useAction' --type=ts -g '!node_modules' | head -20

Repository: dubinc/dub

Length of output: 36


Wrap submitNetworkProfileAction with useAction to properly handle errors.

The onConfirm handler calls submitNetworkProfileAction() directly without error handling. Since next-safe-action wraps thrown errors into the result object (rather than rejecting), direct awaits won't throw—errors will be silent and mutate() will execute regardless, leaving the UI inconsistent.

The same action is properly handled in network-approval-guide.tsx (lines 47-56) using useAction with onSuccess and onError callbacks. Apply that pattern here:

Suggested approach

Replace the direct call with useAction wrapper:

+  const { executeAsync: submitNetworkProfile } = useAction(
+    submitNetworkProfileAction,
+    {
+      onSuccess: () => {
+        toast.success("Application submitted successfully!");
+      },
+      onError: ({ error }) => {
+        toast.error(error.serverError);
+      },
+    },
+  );
+
   const { setShowConfirmModal, confirmModal } = useConfirmModal({
     title: "Submit application",
     description:
       "Are you sure you want to submit your Dub Network application for review? You won't be able to make changes to your application after submitting it.",
     confirmText: "Confirm submission",
     onConfirm: async () => {
-      await submitNetworkProfileAction();
+      await submitNetworkProfile();
       await mutate();
     },
   });
🤖 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)/partners.dub.co/(dashboard)/programs/marketplace/[programSlug]/header-controls.tsx
around lines 101 - 104, The onConfirm handler currently awaits
submitNetworkProfileAction() directly so thrown errors are hidden by
next-safe-action; wrap submitNetworkProfileAction with useAction (as done in
network-approval-guide.tsx) and call that wrapper inside onConfirm, providing
onSuccess to call mutate() and onError to handle/report the error (and prevent
mutate on failure); update the handler to use the returned action runner from
useAction for submitNetworkProfileAction and wire onSuccess/onError callbacks to
keep UI state consistent.

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