The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
List additional group rewards and discounts and skip emails when none apply.
Kiran Kdcad3d89ce7b
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsxindex 60b64e5633..173be9b9b4 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/discounts/group-discounts.tsx@@ -1,5 +1,6 @@"use client";+import { useDiscounts } from "@/lib/swr/use-discounts";import useGroup from "@/lib/swr/use-group";import type { DiscountProps, GroupProps } from "@/lib/types";import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";@@ -7,6 +8,7 @@ import {DiscountSheet,useDiscountSheet,} from "@/ui/partners/discounts/add-edit-discount-sheet";+import { CustomItemsAccordion } from "@/ui/partners/groups/custom-rewards-accordion";import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";import { Button, useRouterStuff } from "@dub/ui";import { cn, isClickOnInteractiveChild } from "@dub/utils";@@ -17,6 +19,7 @@ import { useEffect, useState } from "react";export const GroupDiscounts = () => {const { group, loading } = useGroup();+ const { discounts } = useDiscounts({ groupId: group?.id });const { searchParams } = useRouterStuff();const [discountSheetState, setDiscountSheetState] = useState<@@ -34,11 +37,12 @@ export const GroupDiscounts = () => {}}, [searchParams]);- const currentDiscount =- discountSheetState.discountId &&- group?.discount?.id === discountSheetState.discountId- ? group.discount- : undefined;+ const currentDiscount = getCurrentDiscount({+ discountId: discountSheetState.discountId,+ groupDiscount: group?.discount,+ discounts,+ });+const isNewDiscount = discountSheetState.discountId === "new";return (@@ -56,7 +60,7 @@ export const GroupDiscounts = () => {{loading || !group ? (<DiscountSkeleton />) : (- <DiscountItem discount={group?.discount} group={group} />+ <DiscountItem discount={group.discount} group={group} />)}</div>);@@ -74,64 +78,67 @@ const DiscountItem = ({const As = discount ? Link : "div";return (- <As- href={- discount- ? `/${slug}/program/groups/${group.slug}/discounts?discountId=${discount.id}`- : ""- }- scroll={false}- className={cn(- "flex cursor-pointer flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",- discount && "border border-neutral-200 hover:border-neutral-300",- !discount && "bg-neutral-50 hover:bg-neutral-100",- )}- onClick={(e) => {- if (isClickOnInteractiveChild(e)) return;- queryParams({- set: {- discountId: discount?.id ?? "new",- },- });- }}- >- <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-white">- <BadgePercent className="size-4 text-neutral-600" />- </div>- <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">- <div className="flex items-center gap-2">- <span className="text-sm font-normal">- {discount ? (- <ProgramRewardDescription discount={discount} />- ) : (- <span className="text-sm font-normal text-neutral-600">- No referral discount created- </span>- )}- </span>+ <div>+ <As+ href={+ discount+ ? `/${slug}/program/groups/${group.slug}/discounts?discountId=${discount.id}`+ : ""+ }+ {...(discount ? { scroll: false } : {})}+ className={cn(+ "flex cursor-pointer flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",+ discount && "border border-neutral-200 hover:border-neutral-300",+ !discount && "bg-neutral-50 hover:bg-neutral-100",+ )}+ onClick={(e) => {+ if (isClickOnInteractiveChild(e)) return;+ queryParams({+ set: {+ discountId: discount?.id ?? "new",+ },+ });+ }}+ >+ <div className="flex size-10 items-center justify-center rounded-full border border-neutral-200 bg-white">+ <BadgePercent className="size-4 text-neutral-600" /></div>+ <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">+ <div className="flex items-center gap-2">+ <span className="text-sm font-normal">+ {discount ? (+ <ProgramRewardDescription discount={discount} />+ ) : (+ <span className="text-sm font-normal text-neutral-600">+ No referral discount created+ </span>+ )}+ </span>+ </div>- <div className="flex flex-col-reverse items-center gap-2 md:flex-row">- {!discount && group.slug !== DEFAULT_PARTNER_GROUP.slug && (- <CopyDefaultDiscountButton />- )}- <Button- text={discount ? "Edit" : "Create"}- variant={discount ? "secondary" : "primary"}- className="h-9 w-full rounded-lg md:w-fit"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- queryParams({- set: {- discountId: discount?.id ?? "new",- },- });- }}- />+ <div className="flex flex-col-reverse items-center gap-2 md:flex-row">+ {!discount && group.slug !== DEFAULT_PARTNER_GROUP.slug && (+ <CopyDefaultDiscountButton />+ )}+ <Button+ text={discount ? "Edit" : "Create"}+ variant={discount ? "secondary" : "primary"}+ className="h-9 w-full rounded-lg md:w-fit"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ queryParams({+ set: {+ discountId: discount?.id ?? "new",+ },+ });+ }}+ />+ </div></div>- </div>- </As>+ </As>+ <CustomItemsAccordion group={group} />+ </div>);};@@ -172,3 +179,23 @@ const DiscountSkeleton = () => {</div>);};++function getCurrentDiscount({+ discountId,+ groupDiscount,+ discounts,+}: {+ discountId: string | null;+ groupDiscount: GroupProps["discount"];+ discounts: DiscountProps[] | undefined;+}): DiscountProps | undefined {+ if (!discountId) {+ return undefined;+ }++ if (groupDiscount?.id === discountId) {+ return groupDiscount;+ }++ return discounts?.find((discount) => discount.id === discountId);+}diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/page.tsxindex cfbcaead3e..e455418399 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/groups/[groupSlug]/rewards/page.tsx@@ -2,11 +2,13 @@import { getPlanCapabilities } from "@/lib/plan-capabilities";import useGroup from "@/lib/swr/use-group";+import { useRewards } from "@/lib/swr/use-rewards";import useWorkspace from "@/lib/swr/use-workspace";import type { GroupProps, RewardProps } from "@/lib/types";import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";import { useRewardHistorySheet } from "@/ui/activity-logs/reward-history-sheet";import { useAdvancedUpsellModal } from "@/ui/partners/advanced-upsell-modal";+import { CustomItemsAccordion } from "@/ui/partners/groups/custom-rewards-accordion";import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";import {RewardSheet,@@ -28,6 +30,7 @@ import { useEffect, useState } from "react";export default function GroupRewardsPage() {const { group, loading } = useGroup();+ const { rewards: groupRewards } = useRewards({ groupId: group?.id });const { searchParams } = useRouterStuff();const [rewardSheetState, setRewardSheetState] = useState<@@ -53,9 +56,12 @@ export default function GroupRewardsPage() {group?.customReward,].filter(Boolean) ?? [];- const currentReward = rewardSheetState.rewardId- ? rewards.find((r) => r?.id === rewardSheetState.rewardId)- : undefined;+ const currentReward = getCurrentReward({+ rewardId: rewardSheetState.rewardId,+ defaultRewards: rewards,+ rewards: groupRewards,+ });+const isNewReward = rewardSheetState.rewardId?.startsWith("new-");const newRewardEvent = isNewReward? (rewardSheetState.rewardId?.replace("new-", "") as EventType)@@ -178,140 +184,143 @@ const RewardItem = ({{advancedUpsellModal}{RewardSheet}{rewardHistorySheet}- <As- href={- reward- ? `/${slug}/program/groups/${group.slug}/rewards?rewardId=${reward.id}`- : "#"- }- scroll={false}- className={cn(- "flex flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",- reward &&- "cursor-pointer border border-neutral-200 hover:border-neutral-300",- !reward && "bg-neutral-50 hover:bg-neutral-100",- )}- >- <div className="flex size-10 shrink-0 items-center justify-center rounded-full border border-neutral-200 bg-white">- <Icon className="size-4 text-neutral-600" />- </div>- <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">- <div className="flex w-full items-center gap-2">- {reward ? (- <div className="flex min-w-0 flex-1 flex-col gap-1">- <div className="text-sm font-normal">- <ProgramRewardDescription- reward={reward}- amountClassName="text-blue-600"- />- </div>+ <div>+ <As+ href={+ reward+ ? `/${slug}/program/groups/${group.slug}/rewards?rewardId=${reward.id}`+ : "#"+ }+ {...(reward ? { scroll: false } : {})}+ className={cn(+ "flex flex-col gap-4 rounded-lg p-6 transition-all md:flex-row md:items-center",+ reward &&+ "cursor-pointer border border-neutral-200 hover:border-neutral-300",+ !reward && "bg-neutral-50 hover:bg-neutral-100",+ )}+ >+ <div className="flex size-10 shrink-0 items-center justify-center rounded-full border border-neutral-200 bg-white">+ <Icon className="size-4 text-neutral-600" />+ </div>+ <div className="flex flex-1 flex-col justify-between gap-y-4 md:flex-row md:items-center">+ <div className="flex w-full items-center gap-2">+ {reward ? (+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="text-sm font-normal">+ <ProgramRewardDescription+ reward={reward}+ amountClassName="text-blue-600"+ />+ </div>- <div className="flex items-center gap-1 text-xs font-medium text-neutral-500">- <span>Last updated </span>- {!lastUpdatedDate ? (- <div className="h-3 w-16 animate-pulse rounded bg-neutral-100" />- ) : (- <TimestampTooltip- timestamp={lastUpdatedDate}- side="left"- rows={["local", "utc", "unix"]}- >- <span>- {formatDate(lastUpdatedDate, {- month: "short",- day: "numeric",- year: "numeric",- })}- </span>- </TimestampTooltip>- )}+ <div className="flex items-center gap-1 text-xs font-medium text-neutral-500">+ <span>Last updated </span>+ {!lastUpdatedDate ? (+ <div className="h-3 w-16 animate-pulse rounded bg-neutral-100" />+ ) : (+ <TimestampTooltip+ timestamp={lastUpdatedDate}+ side="left"+ rows={["local", "utc", "unix"]}+ >+ <span>+ {formatDate(lastUpdatedDate, {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </span>+ </TimestampTooltip>+ )}- {activityLogsLoading ? (- <div className="ml-1 h-3 w-20 animate-pulse rounded bg-neutral-100" />- ) : hasActivityLogs ? (- <>- <span- className="ml-1 size-1 shrink-0 rounded-full bg-neutral-400"- aria-hidden- />- <Button- variant="outline"- text="View history"- className="h-4 w-fit px-1 py-0.5 text-xs font-medium text-neutral-500"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- setHistoryOpen(true);- }}- />- </>- ) : null}+ {activityLogsLoading ? (+ <div className="ml-1 h-3 w-20 animate-pulse rounded bg-neutral-100" />+ ) : hasActivityLogs ? (+ <>+ <span+ className="ml-1 size-1 shrink-0 rounded-full bg-neutral-400"+ aria-hidden+ />+ <Button+ variant="outline"+ text="View history"+ className="h-4 w-fit px-1 py-0.5 text-xs font-medium text-neutral-500"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setHistoryOpen(true);+ }}+ />+ </>+ ) : null}+ </div></div>- </div>- ) : (- <div className="flex flex-col">- <span className="text-sm font-medium text-neutral-900">- {REWARD_EVENT_DESCRIPTIONS[event].title}- </span>- <span className="text-sm font-normal text-neutral-500">- {REWARD_EVENT_DESCRIPTIONS[event].description}.{" "}- <Link- href={REWARD_EVENT_DESCRIPTIONS[event].learnMoreHref}- target="_blank"- rel="noopener noreferrer"- className="underline decoration-neutral-400 decoration-dotted underline-offset-2 hover:text-neutral-600"- >- Learn more ↗- </Link>- </span>- </div>- )}- </div>+ ) : (+ <div className="flex flex-col">+ <span className="text-sm font-medium text-neutral-900">+ {REWARD_EVENT_DESCRIPTIONS[event].title}+ </span>+ <span className="text-sm font-normal text-neutral-500">+ {REWARD_EVENT_DESCRIPTIONS[event].description}.{" "}+ <Link+ href={REWARD_EVENT_DESCRIPTIONS[event].learnMoreHref}+ target="_blank"+ rel="noopener noreferrer"+ className="underline decoration-neutral-400 decoration-dotted underline-offset-2 hover:text-neutral-600"+ >+ Learn more ↗+ </Link>+ </span>+ </div>+ )}+ </div>- {reward ? (- <Button- text="Edit"- variant="secondary"- className="h-9 w-fit rounded-lg"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- queryParams({- set: {- rewardId: reward.id,- },- });- }}- />- ) : (- <div className="flex flex-col-reverse items-center gap-2 md:flex-row">- {group.slug !== DEFAULT_PARTNER_GROUP.slug &&- (event !== "referral" || canCreateReferralReward) && (- <CopyDefaultRewardButton event={event} />- )}+ {reward ? (<Button- text="Create"- variant="primary"- className="h-9 w-full rounded-lg md:w-fit"- disabledTooltip={- event === "referral" && !canCreateReferralReward ? (- <TooltipContent- title="Referral rewards are only available on the Advanced plan and above."- cta="Upgrade to Advanced"- onClick={() => setShowAdvancedUpsellModal(true)}- />- ) : undefined- }+ text="Edit"+ variant="secondary"+ className="h-9 w-fit rounded-lg"onClick={(e) => {e.preventDefault();e.stopPropagation();- setIsOpen(true);+ queryParams({+ set: {+ rewardId: reward.id,+ },+ });}}/>- </div>- )}- </div>- </As>+ ) : (+ <div className="flex flex-col-reverse items-center gap-2 md:flex-row">+ {group.slug !== DEFAULT_PARTNER_GROUP.slug &&+ (event !== "referral" || canCreateReferralReward) && (+ <CopyDefaultRewardButton event={event} />+ )}+ <Button+ text="Create"+ variant="primary"+ className="h-9 w-full rounded-lg md:w-fit"+ disabledTooltip={+ event === "referral" && !canCreateReferralReward ? (+ <TooltipContent+ title="Referral rewards are only available on the Advanced plan and above."+ cta="Upgrade to Advanced"+ onClick={() => setShowAdvancedUpsellModal(true)}+ />+ ) : undefined+ }+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ setIsOpen(true);+ }}+ />+ </div>+ )}+ </div>+ </As>+ <CustomItemsAccordion group={group} event={event} />+ </div></>);};@@ -356,3 +365,22 @@ const RewardSkeleton = () => {</div>);};++function getCurrentReward({+ rewardId,+ defaultRewards,+ rewards,+}: {+ rewardId: string | null;+ defaultRewards: (RewardProps | null | undefined)[];+ rewards: RewardProps[] | undefined;+}): RewardProps | undefined {+ if (!rewardId) {+ return undefined;+ }++ return (+ defaultRewards.find((reward) => reward?.id === rewardId) ??+ rewards?.find((reward) => reward.id === rewardId)+ );+}diff --git a/apps/web/ui/modals/confirm-reward-change-modal.tsx b/apps/web/ui/modals/confirm-reward-change-modal.tsxindex 6cf35011eb..59b00c79c3 100644--- a/apps/web/ui/modals/confirm-reward-change-modal.tsx+++ b/apps/web/ui/modals/confirm-reward-change-modal.tsx@@ -6,13 +6,36 @@ import { ProgramRewardDescription } from "@/ui/partners/program-reward-descriptiimport { REWARD_EVENT_DESCRIPTIONS } from "@/ui/partners/rewards/reward-event-descriptions";import { MaxCharactersCounter } from "@/ui/shared/max-characters-counter";import { Button, Modal } from "@dub/ui";-import { cn, pluralize } from "@dub/utils";-import { EventType } from "@prisma/client";-import { useEffect, useState } from "react";+import { cn, nFormatter, pluralize } from "@dub/utils";+import { useCallback, useEffect, useState } from "react";import { useForm } from "react-hook-form";import { PartnerEmailNotificationTooltipHelper } from "../shared/partner-email-notification-tooltip-helper";export type RewardChangeAction = "created" | "updated" | "deleted";+type RewardNotificationTarget = "group" | "partner";++function shouldNotifyRewardChange({+ action,+ target,+ isDefault = false,+ partnerCount,+}: {+ action: RewardChangeAction;+ target: RewardNotificationTarget;+ isDefault?: boolean;+ partnerCount?: number;+}): boolean {+ if (target === "partner") {+ return true;+ }++ // Creating a non-default reward never assigns partners automatically.+ if (action === "created" && !isDefault) {+ return false;+ }++ return partnerCount === undefined || partnerCount > 0;+}const TITLES: Record<RewardChangeAction, string> = {created: "Create reward",@@ -26,46 +49,95 @@ const CONFIRM_TEXT: Record<RewardChangeAction, string> = {deleted: "Delete reward",};+const GROUP_CHANGE_COPY: Record<RewardChangeAction, string> = {+ created: "added to",+ updated: "updated for",+ deleted: "removed from",+};+type ConfirmRewardChangeFormData = {activityDescription: string;};-type ConfirmRewardChangeModalProps = {- showModal: boolean;- setShowModal: (show: boolean) => void;+type RewardSnapshot = Pick<+ RewardProps,+ | "description"+ | "event"+ | "maxDuration"+ | "modifiers"+ | "tooltipDescription"+ | "type"+ | "amountInCents"+ | "amountInPercentage"+ | "config"+ | "spendLimitAmount"+ | "spendLimitInterval"+>;++type ConfirmRewardChangeOptions = {action: RewardChangeAction;- event: EventType;- reward: Pick<- RewardProps,- | "description"- | "event"- | "maxDuration"- | "modifiers"- | "tooltipDescription"- | "type"- | "amountInCents"- | "amountInPercentage"- | "config"- | "spendLimitAmount"- | "spendLimitInterval"- >;+ target: RewardNotificationTarget;+ isDefault?: boolean;+ reward: RewardSnapshot;partnerCount?: number;onConfirm: (activityDescription?: string) => Promise<void>;isPending?: boolean;};+type ConfirmRewardChangeModalProps = ConfirmRewardChangeOptions & {+ showModal: boolean;+ setShowModal: (show: boolean) => void;+};++function getDescription({+ action,+ target,+ partnerCount,+}: {+ action: RewardChangeAction;+ target: RewardNotificationTarget;+ partnerCount?: number;+}) {+ if (target === "partner") {+ return (+ <>+ The reward below will be updated for this partner, and they will be{" "}+ <PartnerEmailNotificationTooltipHelper />.+ </>+ );+ }++ return (+ <>+ The reward below will be {GROUP_CHANGE_COPY[action]} the group+ {partnerCount && partnerCount > 0 ? (+ <>+ , and {nFormatter(partnerCount, { full: true })}{" "}+ {pluralize("partner", partnerCount)} will be{" "}+ <PartnerEmailNotificationTooltipHelper />+ </>+ ) : (+ ""+ )}+ .+ </>+ );+}+export function ConfirmRewardChangeModal({showModal,setShowModal,action,- event,reward,partnerCount,+ target,onConfirm,isPending = false,}: ConfirmRewardChangeModalProps) {const [isLoading, setIsLoading] = useState(false);- const { icon: Icon, title } = REWARD_EVENT_DESCRIPTIONS[event];+ const { icon: Icon, title } = REWARD_EVENT_DESCRIPTIONS[reward.event];+ const messageLabel =+ target === "group" ? "Message to partners" : "Message to partner";const {register,@@ -85,12 +157,6 @@ export function ConfirmRewardChangeModal({}}, [showModal, reset]);- const change = {- created: "added to",- updated: "updated for",- deleted: "removed from",- }[action];-const onSubmit = handleSubmit(async ({ activityDescription }) => {setIsLoading(true);try {@@ -114,16 +180,7 @@ export function ConfirmRewardChangeModal({{TITLES[action]}</h3><p className="text-content-subtle mt-1 text-sm">- The reward below will be {change} the group- {partnerCount && partnerCount > 0 ? (- <>- , and {partnerCount} {pluralize("partner", partnerCount)} will- be <PartnerEmailNotificationTooltipHelper />- </>- ) : (- ""- )}- .+ {getDescription({ action, target, partnerCount })}</p><div className="mt-4 rounded-lg border border-neutral-200 bg-neutral-100 p-3">@@ -146,7 +203,7 @@ export function ConfirmRewardChangeModal({htmlFor="activityDescription"className="text-content-emphasis text-sm font-medium">- Message to partners+ {messageLabel}<span className="ml-1 font-normal text-neutral-500">(optional)</span>@@ -204,37 +261,42 @@ export function ConfirmRewardChangeModal({}export function useConfirmRewardChangeModal() {- const [state, setState] = useState<{- action: RewardChangeAction;- event: EventType;- reward: ConfirmRewardChangeModalProps["reward"];- onConfirm: (activityDescription?: string) => Promise<void>;- isPending?: boolean;- partnerCount?: number;- } | null>(null);+ const [state, setState] = useState<ConfirmRewardChangeOptions | null>(null);++ const confirmRewardChange = useCallback(+ async (options: ConfirmRewardChangeOptions) => {+ const shouldNotify = shouldNotifyRewardChange({+ action: options.action,+ target: options.target,+ isDefault: options.isDefault,+ partnerCount: options.partnerCount,+ });++ if (!shouldNotify) {+ if (options.action === "deleted") {+ if (!window.confirm("Are you sure you want to delete this reward?")) {+ return;+ }+ }++ await options.onConfirm();+ return;+ }++ setState(options);+ },+ [],+ );return {- openConfirmRewardChangeModal: (options: {- action: RewardChangeAction;- event: EventType;- reward: ConfirmRewardChangeModalProps["reward"];- partnerCount?: number;- onConfirm: (activityDescription?: string) => Promise<void>;- isPending?: boolean;- }) => setState(options),- closeConfirmRewardChangeModal: () => setState(null),+ confirmRewardChange,ConfirmRewardChangeModal: state ? (<ConfirmRewardChangeModalshowModalsetShowModal={(show) => {if (!show) setState(null);}}- action={state.action}- event={state.event}- reward={state.reward}- partnerCount={state.partnerCount}- onConfirm={state.onConfirm}- isPending={state.isPending}+ {...state}/>) : null,};diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsxindex 18ff1d54af..299556dbdf 100644--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx@@ -5,6 +5,8 @@ import { deleteDiscountAction } from "@/lib/actions/partners/delete-discount";import { updateDiscountAction } from "@/lib/actions/partners/update-discount";import { constructDiscountAmount } from "@/lib/api/sales/construct-discount-amount";import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";+import { getPlanCapabilities } from "@/lib/plan-capabilities";+import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";import useGroup from "@/lib/swr/use-group";import useProgram from "@/lib/swr/use-program";import useWorkspace from "@/lib/swr/use-workspace";@@ -25,6 +27,7 @@ import {Sheet,Switch,Tooltip,+ TooltipContent,useRouterStuff,} from "@dub/ui";import { CircleCheck, StripeIcon, Tag } from "@dub/ui/icons";@@ -51,6 +54,9 @@ interface DiscountSheetProps {setIsOpen: Dispatch<SetStateAction<boolean>>;discount?: DiscountProps;defaultDiscountValues?: DiscountProps;+ groupIdOrSlug?: string | null;+ isDefault?: boolean;+ onCreated?: (id: string) => void;}type FormData = z.infer<typeof createDiscountSchema>;@@ -76,12 +82,25 @@ function DiscountSheetContent({setIsOpen,discount,defaultDiscountValues,+ groupIdOrSlug,+ isDefault = true,+ onCreated,}: DiscountSheetProps) {const formRef = useRef<HTMLFormElement>(null);- const { group, mutateGroup } = useGroup();+ const { group, mutateGroup } = useGroup({+ groupIdOrSlug: groupIdOrSlug ?? undefined,+ });const { mutate: mutateProgram } = useProgram();- const { id: workspaceId, defaultProgramId } = useWorkspace();+ const {+ id: workspaceId,+ defaultProgramId,+ slug: workspaceSlug,+ plan,+ } = useWorkspace();+ const { canUseAdvancedRewardLogic } = getPlanCapabilities(plan);+ const showPartnerAndLinkUpsell =+ !discount && !isDefault && !canUseAdvancedRewardLogic;const isEdit = Boolean(discount?.id);@@ -123,6 +142,7 @@ function DiscountSheetContent({couponTestId: defaultValuesSource.couponTestId,autoProvision: Boolean(defaultValuesSource.autoProvisionEnabledAt),provider: discountProvider,+ isDefault,},});@@ -144,11 +164,17 @@ function DiscountSheetContent({const { executeAsync: createDiscount, isPending: isCreating } = useAction(createDiscountAction,{- onSuccess: async () => {+ onSuccess: async ({ data }) => {+ if (data?.id) {+ onCreated?.(data.id);+ }setIsOpen(false);toast.success("Discount created!");await mutateProgram();await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/discounts"),+ );},onError({ error }) {if (error.serverError) {@@ -185,6 +211,9 @@ function DiscountSheetContent({toast.success("Discount updated!");await mutateProgram();await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/discounts"),+ );},onError({ error }) {toast.error(error.serverError);@@ -200,6 +229,9 @@ function DiscountSheetContent({toast.success("Discount deleted!");await mutate(`/api/programs/${defaultProgramId}`);await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/discounts"),+ );},onError({ error }) {toast.error(error.serverError);@@ -208,7 +240,12 @@ function DiscountSheetContent({);const onSubmit = async (data: FormData) => {- if (!workspaceId || !defaultProgramId || !group) {+ if (+ !workspaceId ||+ !defaultProgramId ||+ !group ||+ showPartnerAndLinkUpsell+ ) {return;}@@ -229,6 +266,7 @@ function DiscountSheetContent({amount: data.type === "flat" ? data.amount * 100 : data.amount || 0,maxDuration:Number(data.maxDuration) === Infinity ? null : data.maxDuration,+ isDefault,});};@@ -558,9 +596,12 @@ function DiscountSheetContent({</div></div>- <VerticalLine />-- {group && <RewardDiscountPartnersCard groupId={group.id} />}+ {isDefault && group && (+ <>+ <VerticalLine />+ <RewardDiscountPartnersCard groupId={group.id} />+ </>+ )}</div><div className="flex items-center justify-between border-t border-neutral-200 p-5">@@ -593,6 +634,16 @@ function DiscountSheetContent({className="w-fit"loading={isCreating || isUpdating}disabled={(!discount && amount == null) || isDeleting}+ disabledTooltip={+ showPartnerAndLinkUpsell ? (+ <TooltipContent+ title={PARTNER_LEVEL_REWARDS_PLAN_ERROR}+ cta="Upgrade to Advanced"+ href={`/${workspaceSlug}/upgrade?plan=advanced&showAdvancedUpsellModal=true`}+ target="_blank"+ />+ ) : undefined+ }/></div></div>@@ -675,7 +726,7 @@ export function DiscountSheet({const setIsOpen: DiscountSheetProps["setIsOpen"] = (value) => {const nextOpen = typeof value === "function" ? value(isOpen) : value;rest.setIsOpen(value);- if (!nextOpen) {+ if (!nextOpen && !nested) {queryParams({ del: "discountId", scroll: false });}};diff --git a/apps/web/ui/partners/groups/custom-rewards-accordion.tsx b/apps/web/ui/partners/groups/custom-rewards-accordion.tsxnew file mode 100644index 0000000000..4b135dcba2--- /dev/null+++ b/apps/web/ui/partners/groups/custom-rewards-accordion.tsx@@ -0,0 +1,167 @@+"use client";++import { useDiscounts } from "@/lib/swr/use-discounts";+import { useRewards } from "@/lib/swr/use-rewards";+import type { DiscountProps, GroupProps, RewardProps } from "@/lib/types";+import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ AnimatedSizeContainer,+ Users,+ useRouterStuff,+} from "@dub/ui";+import { cn, pluralize } from "@dub/utils";+import { motion } from "motion/react";+import { ReactNode } from "react";++const DEFAULT_REWARD_FIELD = {+ sale: "saleReward",+ lead: "leadReward",+ click: "clickReward",+} as const satisfies Record<string, keyof GroupProps>;++type CustomRewardEvent = keyof typeof DEFAULT_REWARD_FIELD;++type CustomItemsAccordionProps = {+ group: GroupProps;+ event?: RewardProps["event"];+};++export function CustomItemsAccordion({+ group,+ event,+}: CustomItemsAccordionProps) {+ if (!event) {+ return <CustomDiscountsAccordion group={group} />;+ }++ if (event !== "sale" && event !== "lead" && event !== "click") {+ return null;+ }++ return <CustomRewardsAccordion group={group} event={event} />;+}++function CustomRewardsAccordion({+ group,+ event,+}: {+ group: GroupProps;+ event: CustomRewardEvent;+}) {+ const { queryParams } = useRouterStuff();+ const { rewards } = useRewards({ groupId: group.id });+ const defaultReward = group[DEFAULT_REWARD_FIELD[event]];++ const items = (rewards ?? []).filter(+ (reward) => reward.event === event && reward.id !== defaultReward?.id,+ );++ return (+ <ItemsAccordion+ label={`${items.length} custom ${event} ${pluralize("reward", items.length)}`}+ items={items}+ renderItem={(reward) => <ProgramRewardDescription reward={reward} />}+ onSelect={(reward) => {+ queryParams({+ set: { rewardId: reward.id },+ scroll: false,+ });+ }}+ />+ );+}++function CustomDiscountsAccordion({ group }: { group: GroupProps }) {+ const { queryParams } = useRouterStuff();+ const { discounts } = useDiscounts({ groupId: group.id });++ const items = (discounts ?? []).filter(+ (discount) => discount.id !== group.discount?.id,+ );++ return (+ <ItemsAccordion+ label={`${items.length} custom ${pluralize("discount", items.length)}`}+ items={items}+ renderItem={(discount) => (+ <ProgramRewardDescription discount={discount} />+ )}+ onSelect={(discount) => {+ queryParams({+ set: { discountId: discount.id },+ scroll: false,+ });+ }}+ />+ );+}++type AccordionRow = Pick<RewardProps | DiscountProps, "id">;++function ItemsAccordion<T extends AccordionRow>({+ label,+ items,+ renderItem,+ onSelect,+}: {+ label: string;+ items: T[];+ renderItem: (item: T) => ReactNode;+ onSelect: (item: T) => void;+}) {+ return (+ <AnimatedSizeContainer+ height+ className={cn(items.length > 0 && "relative z-10 -mt-px")}+ >+ {items.length > 0 ? (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ transition={{ duration: 0.2, ease: "easeOut" }}+ className="px-2"+ >+ <Accordion+ type="single"+ collapsible+ className="rounded-b-lg border border-neutral-200 bg-white p-1"+ >+ <AccordionItem value="items" className="border-none py-0">+ <AccordionTrigger+ onClick={(e) => e.stopPropagation()}+ className="h-7 py-0 pl-1.5 pr-2 text-xs font-medium tracking-tight text-neutral-600 hover:no-underline sm:text-xs [&>svg]:size-2.5 [&>svg]:text-neutral-600"+ >+ <span className="flex items-center gap-2">+ <Users className="size-3.5" />+ {label}+ </span>+ </AccordionTrigger>+ <AccordionContent className="pb-0 pt-0 text-xs text-neutral-600 sm:text-xs">+ <div className="flex flex-col">+ {items.map((item) => (+ <button+ key={item.id}+ type="button"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onSelect(item);+ }}+ className="w-full rounded-md px-1.5 py-1.5 text-left text-xs text-neutral-600 hover:bg-neutral-50"+ >+ {renderItem(item)}+ </button>+ ))}+ </div>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ </motion.div>+ ) : null}+ </AnimatedSizeContainer>+ );+}diff --git a/apps/web/ui/partners/program-reward-list.tsx b/apps/web/ui/partners/program-reward-list.tsxindex 8ad22d2f73..b1f295b373 100644--- a/apps/web/ui/partners/program-reward-list.tsx+++ b/apps/web/ui/partners/program-reward-list.tsx@@ -2,15 +2,25 @@import { getRewardAmount } from "@/lib/partners/get-reward-amount";import { DiscountProps, RewardProps } from "@/lib/types";-import { Button, Gift, Icon } from "@dub/ui";+import { Button, Gift, Icon, Tooltip } from "@dub/ui";import { cn } from "@dub/utils";import Link from "next/link";import { useParams } from "next/navigation";-import { PropsWithChildren } from "react";+import { PropsWithChildren, ReactNode } from "react";import { formatDiscountDescription } from "./format-discount-description";import { ProgramRewardDescription } from "./program-reward-description";import { REWARD_EVENT_ICON } from "./rewards/reward-event-icon";+const EDITABLE_REWARD_EVENTS = new Set(["sale", "lead", "click"]);++type RewardListItem = RewardProps & {+ isOverride?: boolean;+};++type DiscountListItem = DiscountProps & {+ isOverride?: boolean;+};+export function ProgramRewardList({rewards,discount,@@ -18,13 +28,19 @@ export function ProgramRewardList({className,iconClassName,showModifiersTooltip = true,+ onEditReward,+ onEditDiscount,+ editDisabledTooltip,}: {- rewards: RewardProps[];- discount?: DiscountProps | null;+ rewards: RewardListItem[];+ discount?: DiscountListItem | null;variant?: "default" | "plain";className?: string;iconClassName?: string;showModifiersTooltip?: boolean;+ onEditReward?: (reward: RewardProps) => void;+ onEditDiscount?: (discount: DiscountProps) => void;+ editDisabledTooltip?: ReactNode;}) {const { programSlug } = useParams();const sortedFilteredRewards = rewards.filter((r) => getRewardAmount(r) >= 0);@@ -58,21 +74,47 @@ export function ProgramRewardList({className,)}>- {sortedFilteredRewards.map((reward) => (+ {sortedFilteredRewards.map((reward) => {+ const canEdit =+ onEditReward && EDITABLE_REWARD_EVENTS.has(reward.event);++ return (+ <Item+ key={reward.id}+ icon={REWARD_EVENT_ICON[reward.event]}+ iconClassName={iconClassName}+ isOverride={reward.isOverride}+ action={+ canEdit ? (+ <EditAction+ disabledTooltip={editDisabledTooltip}+ onClick={() => onEditReward(reward)}+ />+ ) : undefined+ }+ >+ <ProgramRewardDescription+ reward={reward}+ showModifiersTooltip={showModifiersTooltip}+ />+ </Item>+ );+ })}++ {discount && (<Item- key={reward.id}- icon={REWARD_EVENT_ICON[reward.event]}+ icon={Gift}iconClassName={iconClassName}+ isOverride={discount.isOverride}+ action={+ onEditDiscount ? (+ <EditAction+ disabledTooltip={editDisabledTooltip}+ onClick={() => onEditDiscount(discount)}+ />+ ) : undefined+ }>- <ProgramRewardDescription- reward={reward}- showModifiersTooltip={showModifiersTooltip}- />- </Item>- ))}-- {discount && (- <Item icon={Gift} iconClassName={iconClassName}>{formatDiscountDescription(discount)}</Item>)}@@ -80,15 +122,79 @@ export function ProgramRewardList({);}+function EditAction({+ onClick,+ disabledTooltip,+}: {+ onClick: () => void;+ disabledTooltip?: ReactNode;+}) {+ const button = (+ <button+ type="button"+ className={cn(+ "text-content-subtle shrink-0 text-xs font-medium",+ disabledTooltip+ ? "cursor-not-allowed opacity-50"+ : "hover:text-content-default",+ )}+ aria-disabled={Boolean(disabledTooltip) || undefined}+ onClick={disabledTooltip ? undefined : onClick}+ >+ Edit+ </button>+ );++ if (!disabledTooltip) {+ return button;+ }++ return <Tooltip content={disabledTooltip}>{button}</Tooltip>;+}++function RewardOverrideIcon() {+ return (+ <span aria-hidden className="absolute right-0 top-0 size-1">+ <svg+ width="8"+ height="8"+ viewBox="0 0 8 8"+ fill="none"+ className="absolute inset-[-50%] overflow-visible"+ >+ <circle+ cx="4"+ cy="4"+ r="3"+ fill="#155DFC"+ stroke="white"+ strokeWidth="2"+ />+ </svg>+ </span>+ );+}+const Item = ({icon: Icon,children,iconClassName,-}: PropsWithChildren<{ icon: Icon; iconClassName?: string }>) => {+ isOverride,+ action,+}: PropsWithChildren<{+ icon: Icon;+ iconClassName?: string;+ isOverride?: boolean;+ action?: ReactNode;+}>) => {return (<li className="flex items-start gap-2">- <Icon className={cn("size-4 shrink-0 translate-y-px", iconClassName)} />- <div>{children}</div>+ <div className="relative shrink-0 py-px">+ <Icon className={cn("block size-4", iconClassName)} />+ {isOverride && <RewardOverrideIcon />}+ </div>+ <div className="min-w-0 flex-1">{children}</div>+ {action}</li>);};diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsxindex 9660b71216..2e5d665c16 100644--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx@@ -8,9 +8,10 @@ import { constructRewardAmount } from "@/lib/api/sales/construct-reward-amount";import { handleMoneyInputChange, handleMoneyKeyDown } from "@/lib/form-utils";import { ReferralRewardConfig } from "@/lib/partner-referrals/types";import { getPlanCapabilities } from "@/lib/plan-capabilities";+import { PARTNER_LEVEL_REWARDS_PLAN_ERROR } from "@/lib/rewards/constants";import useGroup from "@/lib/swr/use-group";-import usePartnersCount from "@/lib/swr/use-partners-count";import useProgram from "@/lib/swr/use-program";+import { useRewards } from "@/lib/swr/use-rewards";import useWorkspace from "@/lib/swr/use-workspace";import { RewardConditionsArray, RewardProps } from "@/lib/types";import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";@@ -81,6 +82,9 @@ interface RewardSheetProps {event: EventType;reward?: RewardProps;defaultRewardValues?: RewardProps;+ groupIdOrSlug?: string | null;+ isDefault?: boolean;+ onCreated?: (id: string) => void;}// Special form schema to allow for empty condition fields when adding a new condition@@ -212,20 +216,27 @@ function RewardSheetContent({event,reward,defaultRewardValues,+ groupIdOrSlug,+ isDefault = true,+ onCreated,hasPendingChangesRef,}: RewardSheetProps & {hasPendingChangesRef: MutableRefObject<boolean>;}) {- const { group, mutateGroup } = useGroup();- const { partnersCount, loading, isValidating } = usePartnersCount<- number | undefined- >({+ const { group, mutateGroup } = useGroup({+ groupIdOrSlug: groupIdOrSlug ?? undefined,+ });+ const { rewards } = useRewards({groupId: group?.id,- status: "approved",});- const partnerCountForConfirm =- group?.id && !loading && !isValidating ? partnersCount : undefined;- const { openConfirmRewardChangeModal, ConfirmRewardChangeModal } =++ const partnerCountForConfirm = reward+ ? rewards?.find((item) => item.id === reward.id)?.partnersCount+ : isDefault+ ? undefined+ : 0;++ const { confirmRewardChange, ConfirmRewardChangeModal } =useConfirmRewardChangeModal();const {@@ -243,7 +254,6 @@ function RewardSheetContent({const formRef = useRef<HTMLFormElement>(null);const { mutate: mutateProgram } = useProgram();- const { queryParams } = useRouterStuff();const defaultValuesSource = reward || defaultRewardValues;@@ -374,12 +384,18 @@ function RewardSheetContent({const { executeAsync: createReward, isPending: isCreating } = useAction(createRewardAction,{- onSuccess: async () => {+ onSuccess: async ({ data }) => {hasPendingChangesRef.current = false;+ if (data?.id) {+ onCreated?.(data.id);+ }setIsOpen(false);toast.success("Reward created!");await mutateProgram();await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/rewards"),+ );},onError({ error }) {toast.error(parseActionError(error, "Failed to create reward"));@@ -392,10 +408,13 @@ function RewardSheetContent({{onSuccess: async () => {hasPendingChangesRef.current = false;- queryParams({ del: "rewardId" });+ setIsOpen(false);toast.success("Reward updated!");await mutateProgram();await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/rewards"),+ );},onError({ error }) {toast.error(parseActionError(error, "Failed to update reward"));@@ -412,6 +431,9 @@ function RewardSheetContent({toast.success("Reward deleted!");await mutate(`/api/programs/${defaultProgramId}`);await mutateGroup();+ await mutate(+ (key) => typeof key === "string" && key.startsWith("/api/rewards"),+ );},onError({ error }) {toast.error(error.serverError);@@ -421,6 +443,8 @@ function RewardSheetContent({const [showAdvancedUpsell, setShowAdvancedUpsell] = useState(false);const showReferralUpsell = event === "referral" && !canCreateReferralReward;+ const showPartnerAndLinkUpsell =+ !reward && !isDefault && !canUseAdvancedRewardLogic;useEffect(() => {if (modifiers?.length && !canUseAdvancedRewardLogic) {@@ -436,12 +460,13 @@ function RewardSheetContent({!defaultProgramId ||showAdvancedUpsell ||showReferralUpsell ||+ showPartnerAndLinkUpsell ||!group) {return;}- let payload: ReturnType<typeof getRewardPayload> | null = null;+ let payload: ReturnType<typeof getRewardPayload>;try {payload = {@@ -460,22 +485,24 @@ function RewardSheetContent({return;}- openConfirmRewardChangeModal({+ await confirmRewardChange({action: reward ? "updated" : "created",- event,- reward: payload!,+ target: "group",+ isDefault,+ reward: payload,partnerCount: partnerCountForConfirm,isPending: isCreating || isUpdating,onConfirm: async (activityDescription) => {if (!reward) {await createReward({- ...payload!,+ ...payload,groupId: group.id,activityDescription,+ isDefault,});} else {await updateReward({- ...payload!,+ ...payload,rewardId: reward.id,activityDescription,});@@ -484,14 +511,15 @@ function RewardSheetContent({});};- const onDelete = () => {+ const onDelete = async () => {if (!workspaceId || !defaultProgramId || !reward) {return;}- openConfirmRewardChangeModal({+ await confirmRewardChange({action: "deleted",- event: reward.event,+ target: "group",+ isDefault,reward,partnerCount: partnerCountForConfirm,isPending: isDeleting,@@ -931,7 +959,7 @@ function RewardSheetContent({<VerticalLine /><RewardPreviewCard />- {group && (+ {isDefault && group && (<><VerticalLine /><RewardDiscountPartnersCard groupId={group.id} />@@ -986,6 +1014,13 @@ function RewardSheetContent({href={`/${workspaceSlug}/upgrade?plan=advanced&showAdvancedUpsellModal=true`}target="_blank"/>+ ) : showPartnerAndLinkUpsell ? (+ <TooltipContent+ title={PARTNER_LEVEL_REWARDS_PLAN_ERROR}+ cta="Upgrade to Advanced"+ href={`/${workspaceSlug}/upgrade?plan=advanced&showAdvancedUpsellModal=true`}+ target="_blank"+ />) : showAdvancedUpsell ? (<TooltipContenttitle="[Advanced reward structures](https://dub.co/help/article/partner-rewards#adding-reward-conditions) are only available on the Advanced plan and above."@@ -1141,7 +1176,7 @@ export function RewardSheet({rest.setIsOpen(value);- if (!nextOpen) {+ if (!nextOpen && !nested) {queryParams({ del: "rewardId" });}};diff --git a/apps/web/ui/partners/rewards/additional-reward-option-list.tsx b/apps/web/ui/partners/rewards/additional-reward-option-list.tsxnew file mode 100644index 0000000000..28b74447c0--- /dev/null+++ b/apps/web/ui/partners/rewards/additional-reward-option-list.tsx@@ -0,0 +1,288 @@+"use client";++import { GroupBadge } from "@/ui/partners/rewards/group-badge";+import { ThreeDots } from "@/ui/shared/icons";+import {+ AnimatedSizeContainer,+ Button,+ MenuItem,+ Popover,+ Users,+ useMediaQuery,+ useScrollProgress,+} from "@dub/ui";+import { Pen2, Plus2, Trash } from "@dub/ui/icons";+import { cn, nFormatter } from "@dub/utils";+import { Command } from "cmdk";+import { ReactNode, useEffect, useMemo, useRef, useState } from "react";++export type AdditionalRewardOption = {+ id: string;+ label: ReactNode;+ searchValue: string;+ isGroup?: boolean;+ partnersCount?: number | null;+};++const createItemClassName =+ "group/button flex h-10 cursor-pointer items-center justify-start gap-2 rounded-lg px-2.5 data-[selected=true]:bg-black/[0.03]";++export function AdditionalRewardOptionList({+ options,+ selectedId,+ onSelect,+ onEdit,+ onDelete,+ searchPlaceholder,+ emptyLabel,+ onCreate,+ createLabel,+ showModal,+}: {+ options: AdditionalRewardOption[];+ selectedId: string | null | undefined;+ onSelect: (id: string) => void;+ onEdit?: (id: string) => void;+ onDelete?: (id: string) => void;+ searchPlaceholder: string;+ emptyLabel: string;+ onCreate?: () => void;+ createLabel?: string;+ showModal?: boolean;+}) {+ const [search, setSearch] = useState("");+ const { isMobile } = useMediaQuery();+ const inputRef = useRef<HTMLInputElement>(null);+ const scrollRef = useRef<HTMLDivElement>(null);+ const { scrollProgress, updateScrollProgress } = useScrollProgress(scrollRef);+ const wasModalOpenRef = useRef(false);++ useEffect(() => {+ if (showModal === undefined) {+ return;+ }++ if (showModal) {+ if (!wasModalOpenRef.current) {+ setSearch("");+ }+ wasModalOpenRef.current = true;+ } else {+ wasModalOpenRef.current = false;+ setSearch("");+ }+ }, [showModal]);++ useEffect(() => {+ if (showModal === false) {+ return;+ }++ inputRef.current &&+ !isMobile &&+ setTimeout(() => inputRef.current?.focus(), 10);+ }, [isMobile, showModal]);++ const normalizedSearch = search.trim().toLowerCase();++ const filteredOptions = useMemo(() => {+ if (!normalizedSearch) {+ return options;+ }++ return options.filter((option) =>+ option.searchValue.toLowerCase().includes(normalizedSearch),+ );+ }, [options, normalizedSearch]);++ const showCreate =+ Boolean(normalizedSearch) &&+ filteredOptions.length === 0 &&+ Boolean(onCreate) &&+ Boolean(createLabel);++ return (+ <AnimatedSizeContainer+ height+ transition={{ ease: "easeOut", duration: 0.1 }}+ className="pointer-events-auto -m-1 overflow-clip"+ >+ <Command loop shouldFilter={false} className="p-1 pb-2">+ <Command.Input+ ref={inputRef}+ placeholder={searchPlaceholder}+ value={search}+ onValueChange={setSearch}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ }+ }}+ className="border-border-default placeholder:text-content-muted w-full rounded-lg border px-2.5 py-2 focus:border-neutral-500 focus:outline-none focus:ring-1 focus:ring-neutral-500 sm:text-sm"+ />+ <div className="relative">+ <div+ ref={scrollRef}+ onScroll={updateScrollProgress}+ className="scrollbar-hide max-h-[calc(100dvh-250px)] overflow-y-auto"+ >+ <Command.List className="mt-4">+ {filteredOptions.map((option) => (+ <Command.Item+ key={option.id}+ value={`${option.searchValue} ${option.id}`}+ onSelect={() => onSelect(option.id)}+ onMouseDown={(e) => {+ // Keep the search input focused when selecting with mouse+ e.preventDefault();+ }}+ className="cursor-pointer outline-none"+ >+ <AdditionalRewardOptionRow+ option={option}+ selected={option.id === selectedId}+ onEdit={onEdit}+ onDelete={onDelete}+ />+ </Command.Item>+ ))}++ {showCreate && (+ <Command.Item+ className={createItemClassName}+ value={`create::${search}`}+ forceMount+ onMouseDown={(e) => {+ e.preventDefault();+ }}+ onSelect={() => {+ onCreate?.();+ }}+ >+ <Plus2 className="size-3.5 shrink-0" />+ <span className="min-w-0 truncate text-sm font-medium">+ {createLabel}+ </span>+ </Command.Item>+ )}++ {filteredOptions.length === 0 && (+ <div className="text-content-default flex select-none flex-col items-center justify-center gap-2 py-12">+ <span className="text-sm font-medium">{emptyLabel}</span>+ </div>+ )}+ </Command.List>+ </div>++ <div+ className="pointer-events-none absolute bottom-0 left-0 hidden h-16 w-full bg-gradient-to-t from-white sm:block"+ style={{ opacity: 1 - Math.pow(scrollProgress, 2) }}+ />+ </div>+ </Command>+ </AnimatedSizeContainer>+ );+}++function AdditionalRewardOptionRow({+ option,+ selected,+ onEdit,+ onDelete,+}: {+ option: AdditionalRewardOption;+ selected: boolean;+ onEdit?: (id: string) => void;+ onDelete?: (id: string) => void;+}) {+ const [openPopover, setOpenPopover] = useState(false);+ const showActions = Boolean(onEdit || onDelete);++ return (+ <div+ className={cn(+ "group flex items-center gap-3 rounded-lg py-2 pl-2.5 pr-1.5 transition-colors hover:bg-neutral-100",+ selected && "bg-transparent",+ )}+ >+ <div className="flex min-w-0 flex-1 items-center gap-3">+ <span+ aria-hidden+ className="border-primary text-primary flex size-3.5 shrink-0 items-center justify-center rounded-full border"+ >+ {selected && <span className="size-2.5 rounded-full bg-current" />}+ </span>+ <div className="text-content-default min-w-0 flex-1 text-sm leading-5">+ {option.label}+ </div>+ </div>++ <div+ className="flex w-[92px] shrink-0 items-center justify-between"+ onPointerDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="flex items-center gap-1">+ <Users className="size-3.5 shrink-0 text-neutral-500" />+ {option.isGroup ? (+ <GroupBadge />+ ) : (+ <span className="text-content-default text-sm font-medium tabular-nums">+ {nFormatter(option.partnersCount ?? 0, { full: true })}+ </span>+ )}+ </div>++ {showActions ? (+ <Popover+ align="end"+ openPopover={openPopover}+ setOpenPopover={setOpenPopover}+ content={+ <div className="flex min-w-32 flex-col gap-1 p-1">+ {onEdit && (+ <MenuItem+ onClick={(e) => {+ e.stopPropagation();+ setOpenPopover(false);+ onEdit(option.id);+ }}+ icon={<Pen2 className="size-4" />}+ >+ Edit+ </MenuItem>+ )}+ {onDelete && (+ <MenuItem+ variant="danger"+ onClick={(e) => {+ e.stopPropagation();+ setOpenPopover(false);+ onDelete(option.id);+ }}+ icon={<Trash className="size-4" />}+ >+ Delete+ </MenuItem>+ )}+ </div>+ }+ >+ <Button+ type="button"+ variant="outline"+ icon={<ThreeDots className="size-3.5" />}+ className="size-6 rounded-lg border-transparent p-0 hover:bg-black/5"+ onClick={(e) => {+ e.stopPropagation();+ setOpenPopover(!openPopover);+ }}+ />+ </Popover>+ ) : (+ <div className="size-6" />+ )}+ </div>+ </div>+ );+}