Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add custom duration input for group discount codes (#3897)

Pedro Ladeira6186efe49495
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx
index e9352e271f..bbcff3e561 100644
--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx
+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx
@@ -11,13 +11,25 @@ export function RenewDomain() {
<form
action={async (data) => {
try {
+ const domain = data.get("domain")?.toString().trim();
+
+ if (!domain) {
+ toast.error("Please enter a domain.");
+ return;
+ }
+
+ const confirmed = window.confirm(
+ `Are you sure you want to renew ${domain}?`,
+ );
+ if (!confirmed) return;
+
const res = await fetch("/api/admin/renew-domain", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
- domain: data.get("domain"),
+ domain,
}),
});
diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.ts
index 36d331f5df..6dabb7a47a 100644
--- a/apps/web/lib/zod/schemas/misc.ts
+++ b/apps/web/lib/zod/schemas/misc.ts
@@ -2,7 +2,14 @@ import { plans } from "@/lib/types";
import { WorkspaceRole } from "@dub/prisma/client";
import * as z from "zod/v4";
-export const RECURRING_MAX_DURATIONS = [0, 1, 3, 6, 12, 18, 24, 36, 48];
+export const RECURRING_MAX_DURATIONS = [0, 1, 3, 6, 12, 24];
+
+export const maxDurationSchema = z.coerce
+ .number()
+ .int({ message: "Max duration must be an integer." })
+ .nonnegative({ message: "Max duration must be 0 or greater." })
+ .max(600, { message: "Max duration must be 600 months (50 years) or less." })
+ .nullish();
export const planSchema = z.enum(plans).describe("The plan of the workspace.");
@@ -79,10 +86,3 @@ export const getCursorPaginationQuerySchema = ({
example,
}),
});
-
-export const maxDurationSchema = z.coerce
- .number()
- .refine((val) => RECURRING_MAX_DURATIONS.includes(val), {
- message: `Max duration must be ${RECURRING_MAX_DURATIONS.join(", ")}`,
- })
- .nullish();
diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
index 2a6d82829a..1521686a58 100644
--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx
@@ -12,6 +12,7 @@ import { DiscountProps } from "@/lib/types";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
import { RECURRING_MAX_DURATIONS } from "@/lib/zod/schemas/misc";
import { Shopify } from "@/ui/guides/icons/shopify";
+import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";
import { X } from "@/ui/shared/icons";
import {
InlineBadgePopover,
@@ -302,7 +303,7 @@ function DiscountSheetContent({
</div>
{!discount && provider === DiscountProvider.stripe && (
- <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
+ <div className="grid grid-cols-1 gap-3 p-px lg:grid-cols-2">
{COUPON_CREATION_OPTIONS.map(
({ label, description, useExisting }) => {
const isSelected = useExistingCoupon === useExisting;
@@ -480,29 +481,12 @@ function DiscountSheetContent({
}
disabled={!!discount}
>
- <InlineBadgePopoverMenu
- selectedValue={maxDuration?.toString()}
- onSelect={(value) =>
- setValue("maxDuration", Number(value), {
- shouldDirty: true,
- })
+ <DurationPopoverContent
+ value={Number(maxDuration)}
+ onChange={(value) =>
+ setValue("maxDuration", value, { shouldDirty: true })
}
- items={[
- {
- text: "one time",
- value: "0",
- },
- ...RECURRING_MAX_DURATIONS.filter((v) => v !== 0).map(
- (v) => ({
- text: `for ${v} ${pluralize("month", Number(v))}`,
- value: v.toString(),
- }),
- ),
- {
- text: "for the customer's lifetime",
- value: "Infinity",
- },
- ]}
+ presetDurations={RECURRING_MAX_DURATIONS}
/>
</InlineBadgePopover>
</span>
diff --git a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
index 91d48bce45..37d1f7eae4 100644
--- a/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
+++ b/apps/web/ui/partners/rewards/add-edit-reward-sheet.tsx
@@ -22,6 +22,7 @@ import {
rewardConditionSchema,
rewardConditionsSchema,
} from "@/lib/zod/schemas/rewards";
+import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";
import { X } from "@/ui/shared/icons";
import { EventType, RewardStructure } from "@dub/prisma/client";
import {
@@ -485,29 +486,16 @@ function RewardSheetContent({
: `for ${maxDuration} ${pluralize("month", Number(maxDuration))}`
}
>
- <InlineBadgePopoverMenu
- selectedValue={maxDuration?.toString()}
- onSelect={(value) =>
- setValue("maxDuration", Number(value), {
+ <DurationPopoverContent
+ value={Number(maxDuration)}
+ onChange={(value) =>
+ setValue("maxDuration", value, {
shouldDirty: true,
})
}
- items={[
- {
- text: "one time",
- value: "0",
- },
- ...RECURRING_MAX_DURATIONS.filter(
- (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
- ).map((v) => ({
- text: `for ${v} ${pluralize("month", Number(v))}`,
- value: v.toString(),
- })),
- {
- text: "for the customer's lifetime",
- value: "Infinity",
- },
- ]}
+ presetDurations={RECURRING_MAX_DURATIONS.filter(
+ (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
+ )}
/>
</InlineBadgePopover>
</>
diff --git a/apps/web/ui/partners/rewards/rewards-logic.tsx b/apps/web/ui/partners/rewards/rewards-logic.tsx
index d09f277b1e..5fdd6d0d09 100644
--- a/apps/web/ui/partners/rewards/rewards-logic.tsx
+++ b/apps/web/ui/partners/rewards/rewards-logic.tsx
@@ -17,6 +17,7 @@ import {
STRING_CONDITION_OPERATORS,
} from "@/lib/zod/schemas/rewards";
import { CountryFlag } from "@/ui/shared/country-flag";
+import { DurationPopoverContent } from "@/ui/shared/duration-popover-content";
import { X } from "@/ui/shared/icons";
import { RewardStructure } from "@dub/prisma/client";
import {
@@ -849,37 +850,16 @@ function ResultTerms({ modifierIndex }: { modifierIndex: number }) {
: `for ${displayMaxDuration} ${pluralize("month", Number(displayMaxDuration))}`
}
>
- <InlineBadgePopoverMenu
- selectedValue={
- displayMaxDuration === Infinity
- ? "Infinity"
- : displayMaxDuration?.toString()
- }
- onSelect={(value) =>
- setValue(
- `${modifierKey}.maxDuration`,
- value === "Infinity" ? Infinity : Number(value),
- {
- shouldDirty: true,
- },
- )
+ <DurationPopoverContent
+ value={displayMaxDuration ?? undefined}
+ onChange={(value) =>
+ setValue(`${modifierKey}.maxDuration`, value, {
+ shouldDirty: true,
+ })
}
- items={[
- {
- text: "one time",
- value: "0",
- },
- ...RECURRING_MAX_DURATIONS.filter(
- (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
- ).map((v) => ({
- text: `for ${v} ${pluralize("month", Number(v))}`,
- value: v.toString(),
- })),
- {
- text: "for the customer's lifetime",
- value: "Infinity",
- },
- ]}
+ presetDurations={RECURRING_MAX_DURATIONS.filter(
+ (v) => v !== 0 && v !== 1, // filter out one-time and 1-month intervals (we only use 1-month for discounts)
+ )}
/>
</InlineBadgePopover>
</>
diff --git a/apps/web/ui/shared/duration-popover-content.tsx b/apps/web/ui/shared/duration-popover-content.tsx
new file mode 100644
index 0000000000..11d1fbe047
--- /dev/null
+++ b/apps/web/ui/shared/duration-popover-content.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import { pluralize } from "@dub/utils";
+import { ChangeEvent, useContext, useEffect, useState } from "react";
+import {
+ InlineBadgePopoverContext,
+ InlineBadgePopoverMenu,
+} from "./inline-badge-popover";
+
+export function DurationPopoverContent({
+ value,
+ onChange,
+ presetDurations,
+}: DurationPopoverContentProps) {
+ const { setIsOpen } = useContext(InlineBadgePopoverContext);
+ const customInputMax = 600;
+ const [customDurationInput, setCustomDurationInput] = useState<string>(() => {
+ if (
+ value !== null &&
+ value !== undefined &&
+ value !== Infinity &&
+ value !== 0 &&
+ !presetDurations.includes(Number(value))
+ ) {
+ return value.toString();
+ }
+ return "";
+ });
+ const [showCustomInput, setShowCustomInput] = useState(false);
+
+ useEffect(() => {
+ if (
+ value === null ||
+ value === undefined ||
+ value === Infinity ||
+ value === 0 ||
+ presetDurations.includes(Number(value))
+ ) {
+ setCustomDurationInput("");
+ setShowCustomInput(false);
+ return;
+ }
+
+ setCustomDurationInput(value.toString());
+ }, [value, presetDurations]);
+
+ const isPresetValue =
+ value === Infinity ||
+ value === 0 ||
+ presetDurations.includes(Number(value));
+
+ if (showCustomInput) {
+ return (
+ <div className="flex flex-col gap-1.5 p-1">
+ <button
+ type="button"
+ onClick={() => setShowCustomInput(false)}
+ className="flex items-center gap-1 rounded px-0.5 text-xs text-neutral-500 transition-colors hover:text-neutral-700"
+ >
+ ← Presets
+ </button>
+ <label className="flex w-full rounded-md border border-neutral-300 shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500 sm:w-32">
+ <input
+ type="number"
+ min="0"
+ max={customInputMax.toString()}
+ step="1"
+ autoFocus
+ placeholder="e.g. 24"
+ value={customDurationInput}
+ className="block min-w-0 grow rounded-md border-none py-1 pl-1.5 pr-0 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ onChange={(e: ChangeEvent<HTMLInputElement>) => {
+ const raw = e.target.value;
+ const parsed = parseInt(raw, 10);
+ const clamped = Math.min(parsed, customInputMax);
+ const display = isNaN(parsed) ? raw : clamped.toString();
+ setCustomDurationInput(display);
+ if (!isNaN(parsed) && parsed >= 0) {
+ onChange(clamped);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.nativeEvent.stopImmediatePropagation();
+ e.preventDefault();
+ setShowCustomInput(false);
+ return;
+ }
+ if (e.key === "Backspace" && customDurationInput === "") {
+ setShowCustomInput(false);
+ return;
+ }
+ if (e.key === "Enter") {
+ e.preventDefault();
+ if (customDurationInput === "0") {
+ onChange(0);
+ setCustomDurationInput("");
+ setShowCustomInput(false);
+ return;
+ }
+ setIsOpen(false);
+ }
+ }}
+ />
+ <span className="flex shrink-0 items-center pr-1.5 text-sm text-neutral-400">
+ months
+ </span>
+ </label>
+ </div>
+ );
+ }
+
+ return (
+ <InlineBadgePopoverMenu
+ selectedValue={isPresetValue ? value?.toString() : undefined}
+ onSelect={(selectedValue) => {
+ if (selectedValue === "custom") {
+ setShowCustomInput(true);
+ return;
+ }
+
+ onChange(
+ selectedValue === "Infinity" ? Infinity : Number(selectedValue),
+ );
+ setCustomDurationInput("");
+ }}
+ items={[
+ { text: "one time", value: "0" },
+ ...presetDurations
+ .filter((duration) => duration !== 0)
+ .map((duration) => ({
+ text: `for ${duration} ${pluralize("month", Number(duration))}`,
+ value: duration.toString(),
+ })),
+ { text: "for the customer's lifetime", value: "Infinity" },
+ { text: "custom", value: "custom", preventClose: true },
+ ]}
+ />
+ );
+}
+
+type DurationPopoverContentProps = {
+ value: number | undefined;
+ onChange: (value: number) => void;
+ presetDurations: number[];
+};
diff --git a/apps/web/ui/shared/inline-badge-popover.tsx b/apps/web/ui/shared/inline-badge-popover.tsx
index 61932f8462..cff9e83cb2 100644
--- a/apps/web/ui/shared/inline-badge-popover.tsx
+++ b/apps/web/ui/shared/inline-badge-popover.tsx
@@ -62,9 +62,11 @@ export function InlineBadgePopover({
align="start"
content={
<InlineBadgePopoverContext.Provider value={{ isOpen, setIsOpen }}>
- <ScrollContainer className="max-h-[50dvh] min-h-0 w-full min-w-32 overscroll-contain p-1 text-sm sm:w-auto">
- {children}
- </ScrollContainer>
+ <AnimatedSizeContainer height width>
+ <ScrollContainer className="max-h-[50dvh] min-h-0 w-full min-w-32 overscroll-contain p-1 text-sm sm:w-auto">
+ {children}
+ </ScrollContainer>
+ </AnimatedSizeContainer>
</InlineBadgePopoverContext.Provider>
}
onWheel={(e) => {
@@ -96,6 +98,7 @@ type MenuItem<T> = {
text: string;
value: T;
onSelect?: () => void;
+ preventClose?: boolean;
};
export function InlineBadgePopoverMenu<T extends any>({
@@ -113,9 +116,14 @@ export function InlineBadgePopoverMenu<T extends any>({
const isMultiSelect = Array.isArray(selectedValue);
+ const commandRef = useRef<HTMLDivElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const { scrollProgress, updateScrollProgress } = useScrollProgress(scrollRef);
+ useEffect(() => {
+ if (!search) commandRef.current?.focus();
+ }, []);
+
const sortedItems = useMemo(
() =>
items.toSorted((a, b) => {
@@ -144,7 +152,7 @@ export function InlineBadgePopoverMenu<T extends any>({
}, [isOpen, sortedItems]);
return (
- <Command loop className="focus:outline-none">
+ <Command ref={commandRef} loop tabIndex={-1} className="focus:outline-none">
{search && (
<div className="-mx-1 -mt-1 mb-1 flex items-center overflow-hidden rounded-t-lg border-b border-neutral-200">
<Command.Input
@@ -161,14 +169,14 @@ export function InlineBadgePopoverMenu<T extends any>({
onScroll={updateScrollProgress}
>
{displayedItems.map(
- ({ icon, text, value, onSelect: itemOnSelect }) => (
+ ({ icon, text, value, onSelect: itemOnSelect, preventClose }) => (
<Command.Item
key={text}
value={`${text} ${value}`}
onSelect={() => {
itemOnSelect?.();
onSelect?.(value);
- !isMultiSelect && setIsOpen(false);
+ !isMultiSelect && !preventClose && setIsOpen(false);
}}
className="flex cursor-pointer items-center justify-between rounded-md px-1.5 py-1 transition-colors duration-150 data-[selected=true]:bg-neutral-100"
>