The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
let partners update their country from profile settings
Pedro Ladeira16b30bd6dca4
diff --git a/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts b/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.tsindex 2577b4e930..a4bd3e06d7 100644--- a/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts+++ b/apps/web/app/(ee)/api/admin/partners/[partnerId]/route.ts@@ -1,10 +1,7 @@-import { queuePartnerSearchSync } from "@/lib/api/partners/queue-partner-search-sync";import { withAdmin } from "@/lib/auth";-import { qstash } from "@/lib/cron";+import { updatePartnerCountry } from "@/lib/partners/update-partner-country";import { prisma } from "@/lib/prisma";-import { partnerProfileChangeHistoryLogSchema } from "@/lib/zod/schemas/partner-profile";-import { APP_DOMAIN_WITH_NGROK, COUNTRIES } from "@dub/utils";-import { waitUntil } from "@vercel/functions";+import { COUNTRIES } from "@dub/utils";import { NextResponse } from "next/server";import * as z from "zod/v4";@@ -118,9 +115,6 @@ export const PATCH = withAdmin(async ({ params, req }) => {select: {id: true,country: true,- changeHistoryLog: true,- veriffSessionId: true,- identityVerifiedAt: true,},});@@ -132,49 +126,10 @@ export const PATCH = withAdmin(async ({ params, req }) => {return new Response("Partner is already in this country.", { status: 400 });}- const partnerChangeHistoryLog = partner.changeHistoryLog- ? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)- : [];-- partnerChangeHistoryLog.push({- field: "country",- from: partner.country,- to: country,- changedAt: new Date(),- });-- await prisma.partner.update({- where: {- id: partner.id,- },- data: {- country,- changeHistoryLog: partnerChangeHistoryLog,- // reset all payout fields- defaultPayoutMethod: null,- payoutsEnabledAt: null,- paypalEmail: null,- stripeConnectId: null,- stripeRecipientId: null,- payoutMethodHash: null,- cryptoWalletAddress: null,- },+ await updatePartnerCountry({+ partnerId: partner.id,+ country,});- // Queue an index update because an admin corrected the partner country (filterable field)- waitUntil(queuePartnerSearchSync({ partnerIds: [partner.id] }));-- // if there was an existing veriff session, trigger a country change verification- if (partner.identityVerifiedAt) {- waitUntil(- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/verify-country-change`,- body: {- partnerId: partner.id,- },- }),- );- }-return NextResponse.json({ success: true });});diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsxindex d98440b830..c31efaa271 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/profile/profile-details-form.tsx@@ -14,6 +14,7 @@ import {PartnerPlatformsForm,usePartnerPlatformsForm,} from "@/ui/partners/partner-platforms-form";+import { useCountryChangeWarningModal } from "@/ui/partners/use-country-change-warning-modal";import { CustomToast } from "@/ui/shared/custom-toast";import {Button,@@ -307,6 +308,9 @@ function BasicInfoForm({pendingSubmitRef.current = null;};+ const { modal: countryChangeWarningModal, acknowledgeAndContinue } =+ useCountryChangeWarningModal();+const { setShowModal: setShowConfirmModal, confirmModal } =useIdentitySyncConfirmModal({title: "Also update your user account?",@@ -328,6 +332,7 @@ function BasicInfoForm({return (<>+ {countryChangeWarningModal}{confirmModal}<formref={formRef}@@ -341,6 +346,19 @@ function BasicInfoForm({onSubmitAction();}}onSubmit={handleSubmit(async (data) => {+ if (partner?.country === "US" && data.country !== partner.country) {+ const acknowledged = await new Promise<boolean>((resolve) => {+ acknowledgeAndContinue(+ () => resolve(true),+ () => resolve(false),+ );+ });++ if (!acknowledged) {+ return;+ }+ }+const imageChanged = data.image !== partner?.image;const syncCandidates = getProfileSyncCandidates({data,@@ -503,12 +521,16 @@ function BasicInfoForm({value={field.value || ""}onChange={field.onChange}disabledTooltip={- <TooltipContent- title="Your profile country is based on your current location and cannot be changed. If you need to update your country, please contact support."- cta="Contact support"- href="https://dub.co/support"- target="_blank"- />+ partner?.country !== "US" ? (+ <TooltipContent+ title="Your profile country is based on your current location and cannot be changed. If you need to update your country, please contact support."+ cta="Contact support"+ href="https://dub.co/support"+ target="_blank"+ />+ ) : disabled ? (+ <TooltipContent title="You don't have permission to update this field" />+ ) : undefined}/>)}diff --git a/apps/web/app/api/ai/support-chat/route.ts b/apps/web/app/api/ai/support-chat/route.tsindex 467f8c8f15..69c36c8c4d 100644--- a/apps/web/app/api/ai/support-chat/route.ts+++ b/apps/web/app/api/ai/support-chat/route.ts@@ -9,6 +9,7 @@ import { getProgramPerformanceTool } from "@/lib/ai/get-program-performance";import { getWorkspaceDetailsTool } from "@/lib/ai/get-workspace-details";import { requestSupportTicketTool } from "@/lib/ai/request-support-ticket";import { withSession } from "@/lib/auth";+import { prisma } from "@/lib/prisma";import { getSlackClient } from "@/lib/slack/client";import { ratelimit } from "@/lib/upstash/ratelimit";import { anthropic } from "@ai-sdk/anthropic";@@ -189,9 +190,30 @@ export const POST = withSession(async ({ req, session }) => {});}+ let partnerCountry: string | null | undefined;++ if (+ globalContext?.accountType === "partner" &&+ session.user.defaultPartnerId+ ) {+ const partner = await prisma.partner.findUnique({+ where: {+ id: session.user.defaultPartnerId,+ },+ select: {+ country: true,+ },+ });++ partnerCountry = partner?.country;+ }+const result = streamText({model: anthropic("claude-sonnet-4-6"),- system: buildSystemPrompt(globalContext),+ system: buildSystemPrompt({+ ...globalContext,+ partnerCountry,+ }),messages: await convertToModelMessages(modelMessages),stopWhen: stepCountIs(5),tools: {diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.tsindex 2c32fd43e2..d57fdee816 100644--- a/apps/web/lib/actions/partners/update-partner-profile.ts+++ b/apps/web/lib/actions/partners/update-partner-profile.ts@@ -12,6 +12,7 @@ import {requestSyncedEmailChange,syncNameAndImageToUser,} from "@/lib/partners/sync-partner-identity";+import { updatePartnerCountry } from "@/lib/partners/update-partner-country";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";@@ -23,6 +24,7 @@ import {} from "@/lib/zod/schemas/partners";import {APP_DOMAIN_WITH_NGROK,+ COUNTRIES,deepEqual,nanoid,PARTNERS_DOMAIN,@@ -44,6 +46,7 @@ const updatePartnerProfileSchema = zdescription: z.string().max(MAX_PARTNER_DESCRIPTION_LENGTH).nullish(),profileType: z.enum(PartnerProfileType).optional(),companyName: z.string().nullish(),+ country: z.string().optional(),syncIdentity: z.boolean().optional(),}).extend(PartnerProfileDetailsSchema.partial().shape)@@ -88,9 +91,24 @@ export const updatePartnerProfileAction = authPartnerActionClientpreferredEarningStructures,salesChannels,username,+ country,syncIdentity,} = parsedInput;+ const countryChanged = Boolean(country) && country !== partner.country;++ if (countryChanged) {+ if (partner.country !== "US") {+ throw new Error(+ "Your profile country cannot be changed. Contact support to update it.",+ );+ }++ if (!country || !(country in COUNTRIES)) {+ throw new Error("Select a valid country.");+ }+ }+await updatedComplianceFieldsChecks({partner,input: parsedInput,@@ -285,6 +303,13 @@ export const updatePartnerProfileAction = authPartnerActionClient]),);+ if (countryChanged && country) {+ await updatePartnerCountry({+ partnerId: partner.id,+ country,+ });+ }+return {needsEmailVerification,};diff --git a/apps/web/lib/ai/build-system-prompt.ts b/apps/web/lib/ai/build-system-prompt.tsindex e5a9d47efb..154d9f4c43 100644--- a/apps/web/lib/ai/build-system-prompt.ts+++ b/apps/web/lib/ai/build-system-prompt.ts@@ -1,4 +1,5 @@import { SupportChatContext } from "@/ui/support/types";+import { COUNTRIES } from "@dub/utils";import { Program, Project } from "@prisma/client";export type GlobalChatContext = {@@ -6,6 +7,7 @@ export type GlobalChatContext = {accountType?: "workspace" | "partner";selectedWorkspace?: Pick<Project, "id" | "name" | "slug">;selectedProgram?: Pick<Program, "id" | "name" | "slug">;+ partnerCountry?: string | null;};const CONTEXT_SYSTEM_PROMPTS: Record<SupportChatContext, string> = {@@ -54,13 +56,23 @@ const PARTNERS_PAYOUT_PROMPT = `- Offer to create a Dub support ticket (call requestSupportTicket, then createSupportTicket once the user confirms) so Dub can investigate further.`.trim();-const PARTNER_PROFILE_COUNTRY_PROMPT = `+function buildPartnerProfileCountryPrompt(partnerCountry?: string | null) {+ return `Partner profile country:- The partner's profile country is based on their current location at signup and cannot be changed in the dashboard.- Never tell the partner to edit Country under partner profile or settings.- If they need to update their country, tell them they cannot change it themselves and must contact support. Call requestSupportTicket (then createSupportTicket after they confirm).+ The partner's profile country is based on their current location at signup.+ Current profile country: ${+ partnerCountry+ ? `${COUNTRIES[partnerCountry] ?? partnerCountry} (${partnerCountry})`+ : "unknown"+ }.+ ${+ partnerCountry === "US"+ ? "They can update it themselves in partner profile settings at https://partners.dub.co/profile. Tell them to change it there. Do not create a support ticket."+ : "They cannot change it themselves. Tell them their current country and that support has to update it. In that same response, call requestSupportTicket so the upload form appears. Do not only ask whether they want a ticket. After they confirm, call createSupportTicket."+ }Do not confuse this with which countries support payouts — that is a different question and can still use docs.`.trim();+}const NONPROFIT_DISCOUNT_PROMPT = `Non-profit discounts:@@ -108,7 +120,7 @@ export function buildSystemPrompt(globalContext?: GlobalChatContext): string {NONPROFIT_DISCOUNT_PROMPT,globalContext?.accountType === "partner" ? PARTNERS_PAYOUT_PROMPT : null,globalContext?.accountType === "partner"- ? PARTNER_PROFILE_COUNTRY_PROMPT+ ? buildPartnerProfileCountryPrompt(globalContext.partnerCountry): null,...accountSpecificPrompts,].filter((section): section is string => Boolean(section));diff --git a/apps/web/lib/partners/update-partner-country.ts b/apps/web/lib/partners/update-partner-country.tsnew file mode 100644index 0000000000..ab23acc944--- /dev/null+++ b/apps/web/lib/partners/update-partner-country.ts@@ -0,0 +1,78 @@+import { queuePartnerSearchSync } from "@/lib/api/partners/queue-partner-search-sync";+import { qstash } from "@/lib/cron";+import { prisma } from "@/lib/prisma";+import { partnerProfileChangeHistoryLogSchema } from "@/lib/zod/schemas/partner-profile";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { waitUntil } from "@vercel/functions";++export async function updatePartnerCountry({+ partnerId,+ country,+}: {+ partnerId: string;+ country: string;+}) {+ const partner = await prisma.partner.findUnique({+ where: {+ id: partnerId,+ },+ select: {+ id: true,+ country: true,+ changeHistoryLog: true,+ identityVerifiedAt: true,+ },+ });++ if (!partner) {+ throw new Error("Partner not found.");+ }++ if (partner.country === country) {+ return;+ }++ const partnerChangeHistoryLog = partner.changeHistoryLog+ ? partnerProfileChangeHistoryLogSchema.parse(partner.changeHistoryLog)+ : [];++ partnerChangeHistoryLog.push({+ field: "country",+ from: partner.country,+ to: country,+ changedAt: new Date(),+ });++ await prisma.partner.update({+ where: {+ id: partner.id,+ },+ data: {+ country,+ changeHistoryLog: partnerChangeHistoryLog,+ // reset all payout fields+ defaultPayoutMethod: null,+ payoutsEnabledAt: null,+ paypalEmail: null,+ stripeConnectId: null,+ stripeRecipientId: null,+ payoutMethodHash: null,+ cryptoWalletAddress: null,+ },+ });++ // Queue an index update because the partner country moved (filterable field)+ waitUntil(queuePartnerSearchSync({ partnerIds: [partner.id] }));++ // if there was an existing veriff session, trigger a country change verification+ if (partner.identityVerifiedAt) {+ waitUntil(+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/partners/verify-country-change`,+ body: {+ partnerId: partner.id,+ },+ }),+ );+ }+}diff --git a/apps/web/ui/partners/use-country-change-warning-modal.tsx b/apps/web/ui/partners/use-country-change-warning-modal.tsxindex 1da7d2a8ac..76f28380be 100644--- a/apps/web/ui/partners/use-country-change-warning-modal.tsx+++ b/apps/web/ui/partners/use-country-change-warning-modal.tsx@@ -5,19 +5,23 @@ import { useCallback, useRef, useState } from "react";export function useCountryChangeWarningModal() {const [showModalState, setShowModalState] = useState(false);- const [isAcknowledged, setIsAcknowledged] = useState(false);const onAcknowledgeRef = useRef<(() => void) | null>(null);+ const onCancelRef = useRef<(() => void) | null>(null);const handleCancel = useCallback(() => {+ const onCancel = onCancelRef.current;onAcknowledgeRef.current = null;+ onCancelRef.current = null;setShowModalState(false);+ onCancel?.();}, []);const handleAcknowledge = useCallback(() => {- setIsAcknowledged(true);- setShowModalState(false);- onAcknowledgeRef.current?.();+ const onAcknowledge = onAcknowledgeRef.current;onAcknowledgeRef.current = null;+ onCancelRef.current = null;+ setShowModalState(false);+ onAcknowledge?.();}, []);const modal = (@@ -61,20 +65,17 @@ export function useCountryChangeWarningModal() {</Modal>);- const showModal = useCallback(() => {- onAcknowledgeRef.current = null;- setShowModalState(true);- }, []);-- const acknowledgeAndContinue = useCallback((callback?: () => void) => {- onAcknowledgeRef.current = callback ?? null;- setShowModalState(true);- }, []);+ const acknowledgeAndContinue = useCallback(+ (callback?: () => void, onCancel?: () => void) => {+ onAcknowledgeRef.current = callback ?? null;+ onCancelRef.current = onCancel ?? null;+ setShowModalState(true);+ },+ [],+ );return {modal,- showModal,- isAcknowledged,acknowledgeAndContinue,};}