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.

Copy discounts from staging to live program groups

Kiran Ke3f1068ddc32
diff --git a/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts b/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts
index 97dc74dfdd..50a7cb5c16 100644
--- a/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts
+++ b/apps/web/app/(ee)/api/cron/discount-codes/create/queue-batches/route.ts
@@ -33,6 +33,7 @@ export const POST = withCron(async ({ rawBody }) => {
id: true,
stripeConnectId: true,
shopifyStoreId: true,
+ environment: true,
},
},
},
diff --git a/apps/web/app/(ee)/api/cron/discount-codes/create/route.ts b/apps/web/app/(ee)/api/cron/discount-codes/create/route.ts
index 1686474716..0e574f4005 100644
--- a/apps/web/app/(ee)/api/cron/discount-codes/create/route.ts
+++ b/apps/web/app/(ee)/api/cron/discount-codes/create/route.ts
@@ -46,6 +46,7 @@ export const POST = withCron(async ({ rawBody }) => {
id: true,
stripeConnectId: true,
shopifyStoreId: true,
+ environment: true,
},
},
},
diff --git a/apps/web/app/(ee)/api/cron/discount-codes/delete/route.ts b/apps/web/app/(ee)/api/cron/discount-codes/delete/route.ts
index 07f10e73bb..41e30331f9 100644
--- a/apps/web/app/(ee)/api/cron/discount-codes/delete/route.ts
+++ b/apps/web/app/(ee)/api/cron/discount-codes/delete/route.ts
@@ -26,6 +26,7 @@ export const POST = withCron(async ({ rawBody }) => {
id: true,
stripeConnectId: true,
shopifyStoreId: true,
+ environment: true,
},
});
diff --git a/apps/web/app/(ee)/api/cron/groups/remap-discount-codes/route.ts b/apps/web/app/(ee)/api/cron/groups/remap-discount-codes/route.ts
index 66c9dfecca..4e31077abe 100644
--- a/apps/web/app/(ee)/api/cron/groups/remap-discount-codes/route.ts
+++ b/apps/web/app/(ee)/api/cron/groups/remap-discount-codes/route.ts
@@ -151,6 +151,7 @@ export const POST = withCron(async ({ rawBody }) => {
id: true,
stripeConnectId: true,
shopifyStoreId: true,
+ environment: true,
},
});
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.tsx
index 99c182516f..0ee774206d 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,10 +1,13 @@
"use client";
+import { useCopyDiscountToLiveModal } from "@/lib/sandbox/copy-discount-to-live-modal";
import useGroup from "@/lib/swr/use-group";
+import useWorkspace from "@/lib/swr/use-workspace";
import type { DiscountProps, GroupProps } from "@/lib/types";
import { DEFAULT_PARTNER_GROUP } from "@/lib/zod/schemas/groups";
import { useDiscountSheet } from "@/ui/partners/discounts/add-edit-discount-sheet";
import { ProgramRewardDescription } from "@/ui/partners/program-reward-description";
+import { WorkspaceEnvironment } from "@dub/prisma/client";
import { Button, useRouterStuff } from "@dub/ui";
import { cn, isClickOnInteractiveChild } from "@dub/utils";
import { BadgePercent } from "lucide-react";
@@ -68,70 +71,93 @@ const DiscountItem = ({
group: GroupProps;
}) => {
const { slug } = useParams();
+ const { environment } = useWorkspace();
const { queryParams } = useRouterStuff();
+ const { openCopyDiscountToLiveModal, CopyDiscountToLiveModal } =
+ useCopyDiscountToLiveModal();
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",
+ <>
+ {discount && environment === WorkspaceEnvironment.staging && (
+ <CopyDiscountToLiveModal />
)}
- onClick={(e) => {
- if (isClickOnInteractiveChild(e)) return;
- queryParams({
- set: {
- discountId: discount?.id ?? "new",
- },
- scroll: false,
- });
- }}
- >
- <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>
+ <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) => {
+ e.preventDefault();
+ if (isClickOnInteractiveChild(e)) return;
+ queryParams({
+ set: {
+ discountId: discount?.id ?? "new",
+ },
+ scroll: false,
+ });
+ }}
+ >
+ <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 />
+ )}
+
+ {discount && environment === WorkspaceEnvironment.staging && (
+ <Button
+ text="Copy to live"
+ variant="secondary"
+ className="h-9 w-full rounded-lg md:w-fit"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ openCopyDiscountToLiveModal(discount);
+ }}
+ />
+ )}
- <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",
- },
- scroll: false,
- });
- }}
- />
+ <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",
+ },
+ scroll: false,
+ });
+ }}
+ />
+ </div>
</div>
- </div>
- </As>
+ </As>
+ </>
);
};
diff --git a/apps/web/lib/discounts/create-discount-code.ts b/apps/web/lib/discounts/create-discount-code.ts
index fbc5559027..e46645f8bd 100644
--- a/apps/web/lib/discounts/create-discount-code.ts
+++ b/apps/web/lib/discounts/create-discount-code.ts
@@ -5,7 +5,10 @@ import { constructDiscountCode } from "./construct-discount-code";
import { getDiscountProvider } from "./discount-provider";
interface CreateDiscountCodeArgs {
- workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
+ workspace: Pick<
+ Project,
+ "id" | "environment" | "stripeConnectId" | "shopifyStoreId"
+ >;
partner: Pick<Partner, "id" | "name">;
link: Pick<Link, "id">;
discount: Discount;
diff --git a/apps/web/lib/discounts/discount-provider-shopify.ts b/apps/web/lib/discounts/discount-provider-shopify.ts
index 0ba990a7c5..ae095067e2 100644
--- a/apps/web/lib/discounts/discount-provider-shopify.ts
+++ b/apps/web/lib/discounts/discount-provider-shopify.ts
@@ -32,15 +32,14 @@ interface ShopifyDiscountCodeDelete {
}[];
}
+type Workspace = Pick<Project, "id" | "environment" | "shopifyStoreId">;
+
const MAX_ATTEMPTS = 3;
-async function requireInstalledIntegration(
- workspace: Pick<Project, "id" | "shopifyStoreId">,
-) {
+async function requireInstalledIntegration(workspace: Workspace) {
if (!workspace.shopifyStoreId) {
throw new DiscountIntegrationNotAvailableError({
- message:
- "SHOPIFY_CONNECTION_REQUIRED: Your workspace isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.",
+ message: `SHOPIFY_CONNECTION_REQUIRED: Your workspace (${workspace.environment}) isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.`,
});
}
@@ -53,8 +52,7 @@ async function requireInstalledIntegration(
if (!installation) {
throw new DiscountIntegrationNotAvailableError({
- message:
- "SHOPIFY_CONNECTION_REQUIRED: Your workspace isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.",
+ message: `SHOPIFY_CONNECTION_REQUIRED: Your workspace (${workspace.environment}) isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create a discount.`,
});
}
@@ -64,8 +62,7 @@ async function requireInstalledIntegration(
if (!credentials?.scope?.includes("write_discounts")) {
throw new DiscountIntegrationNotAvailableError({
- message:
- "SHOPIFY_APP_UPGRADE_REQUIRED: Your connected Shopify store doesn't have permission to create discount codes. Please reinstall or upgrade the Dub Shopify app.",
+ message: `SHOPIFY_APP_UPGRADE_REQUIRED: Your connected Shopify store in the workspace (${workspace.environment}) doesn't have permission to create discount codes. Please reinstall or upgrade the Dub Shopify app.`,
});
}
@@ -95,7 +92,7 @@ function createShopifyDiscountProvider() {
code,
shouldRetry = true,
}: {
- workspace: Pick<Project, "id" | "shopifyStoreId">;
+ workspace: Pick<Project, "id" | "environment" | "shopifyStoreId">;
discount: Pick<Discount, "id" | "amount" | "type" | "maxDuration">;
code: string;
shouldRetry?: boolean;
@@ -226,7 +223,7 @@ function createShopifyDiscountProvider() {
workspace,
code,
}: {
- workspace: Pick<Project, "id" | "shopifyStoreId">;
+ workspace: Workspace;
code: string;
}) => {
const { credentials } = await requireInstalledIntegration(workspace);
@@ -295,7 +292,7 @@ function createShopifyDiscountProvider() {
const assertDiscountIntegrationAvailable = async ({
workspace,
}: {
- workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
+ workspace: Workspace;
}) => {
await requireInstalledIntegration(workspace);
};
diff --git a/apps/web/lib/discounts/discount-provider-stripe.ts b/apps/web/lib/discounts/discount-provider-stripe.ts
index f96449dfc3..83981b9279 100644
--- a/apps/web/lib/discounts/discount-provider-stripe.ts
+++ b/apps/web/lib/discounts/discount-provider-stripe.ts
@@ -16,13 +16,12 @@ import { DiscountIntegrationNotAvailableError } from "./discount-error";
const MAX_ATTEMPTS = 3;
-async function requireInstalledIntegration(
- workspace: Pick<Project, "id" | "stripeConnectId">,
-) {
+type Workspace = Pick<Project, "id" | "environment" | "stripeConnectId">;
+
+async function requireInstalledIntegration(workspace: Workspace) {
if (!workspace.stripeConnectId) {
throw new DiscountIntegrationNotAvailableError({
- message:
- "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create a discount.",
+ message: `STRIPE_CONNECTION_REQUIRED: Your workspace (${workspace.environment}) isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create a discount.`,
});
}
@@ -35,8 +34,7 @@ async function requireInstalledIntegration(
if (!installation) {
throw new DiscountIntegrationNotAvailableError({
- message:
- "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create a discount.",
+ message: `STRIPE_CONNECTION_REQUIRED: Your workspace (${workspace.environment}) isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create a discount.`,
});
}
@@ -96,9 +94,12 @@ function createStripeDiscountProvider() {
group,
data,
}: {
- workspace: Project;
- group: PartnerGroup;
- data: z.infer<typeof createDiscountSchema>;
+ workspace: Workspace;
+ group: Pick<PartnerGroup, "name">;
+ data: Pick<
+ z.infer<typeof createDiscountSchema>,
+ "amount" | "type" | "maxDuration"
+ >;
}) => {
const { settings } = await requireInstalledIntegration(workspace);
@@ -136,7 +137,7 @@ function createStripeDiscountProvider() {
code,
shouldRetry = true,
}: {
- workspace: Pick<Project, "id" | "stripeConnectId">;
+ workspace: Workspace;
discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;
code: string;
shouldRetry?: boolean; // we don't retry if the code is provided by the user
@@ -203,7 +204,7 @@ function createStripeDiscountProvider() {
workspace,
code,
}: {
- workspace: Pick<Project, "id" | "stripeConnectId">;
+ workspace: Workspace;
code: string;
}) => {
const { settings } = await requireInstalledIntegration(workspace);
@@ -251,7 +252,7 @@ function createStripeDiscountProvider() {
const assertDiscountIntegrationAvailable = async ({
workspace,
}: {
- workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;
+ workspace: Workspace;
}) => {
await requireInstalledIntegration(workspace);
};
diff --git a/apps/web/lib/discounts/generate-discount-code-for-partner.ts b/apps/web/lib/discounts/generate-discount-code-for-partner.ts
index e415687518..0b037feadb 100644
--- a/apps/web/lib/discounts/generate-discount-code-for-partner.ts
+++ b/apps/web/lib/discounts/generate-discount-code-for-partner.ts
@@ -40,6 +40,7 @@ export async function generateDiscountCodeForPartner({
id: true,
stripeConnectId: true,
shopifyStoreId: true,
+ environment: true,
},
});
diff --git a/apps/web/lib/sandbox/copy-discount-to-live-modal.tsx b/apps/web/lib/sandbox/copy-discount-to-live-modal.tsx
new file mode 100644
index 0000000000..0d360c6f5f
--- /dev/null
+++ b/apps/web/lib/sandbox/copy-discount-to-live-modal.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import useWorkspaces from "@/lib/swr/use-workspaces";
+import type { DiscountProps, GroupProps } from "@/lib/types";
+import { ERROR_MAP } from "@/ui/partners/constants";
+import { GroupColorCircle } from "@/ui/partners/groups/group-color-circle";
+import { UpgradeRequiredToast } from "@/ui/shared/upgrade-required-toast";
+import { Button, Combobox, type ComboboxOption, Modal } from "@dub/ui";
+import { fetcher } from "@dub/utils";
+import { useAction } from "next-safe-action/hooks";
+import { useCallback, useMemo, useState } from "react";
+import { toast } from "sonner";
+import useSWR from "swr";
+import { copyDiscountToLiveAction } from "./copy-discount-to-live";
+
+function CopyDiscountToLiveModal({
+ showModal,
+ setShowModal,
+ discount,
+}: {
+ showModal: boolean;
+ setShowModal: (show: boolean) => void;
+ discount: DiscountProps;
+}) {
+ const [selectedGroup, setSelectedGroup] = useState<ComboboxOption | null>(
+ null,
+ );
+
+ const { id: workspaceId } = useWorkspace();
+ const { workspaces } = useWorkspaces();
+
+ const liveWorkspace = workspaces?.find(
+ (w) => w.stagingWorkspaceId === workspaceId,
+ );
+
+ const { data: liveGroups, isLoading: liveGroupsLoading } = useSWR<
+ GroupProps[]
+ >(
+ showModal && liveWorkspace?.id
+ ? `/api/groups?workspaceId=${liveWorkspace.id}&sortBy=totalSaleAmount`
+ : null,
+ fetcher,
+ );
+
+ const groupOptions = (liveGroups ?? []).map((group) => ({
+ value: group.id,
+ label: group.name,
+ icon: <GroupColorCircle group={group} />,
+ }));
+
+ const { executeAsync, isPending } = useAction(copyDiscountToLiveAction, {
+ onSuccess: () => {
+ setShowModal(false);
+ setSelectedGroup(null);
+ toast.success("Discount copied to live program!");
+ },
+ onError({ error }) {
+ if (error.serverError) {
+ const code = Object.keys(ERROR_MAP).find((key) =>
+ error.serverError!.startsWith(key),
+ );
+
+ if (code) {
+ const { title, ctaLabel, ctaUrl } = ERROR_MAP[code];
+ const message = error.serverError!.replace(`${code}: `, "");
+
+ toast.custom(() => (
+ <UpgradeRequiredToast
+ title={title}
+ message={message}
+ ctaLabel={ctaLabel}
+ ctaUrl={ctaUrl}
+ />
+ ));
+ return;
+ }
+ }
+
+ toast.error(error.serverError);
+ },
+ });
+
+ const onSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!selectedGroup || !workspaceId) return;
+
+ await executeAsync({
+ workspaceId,
+ discountId: discount.id,
+ targetGroupId: selectedGroup.value,
+ });
+ };
+
+ return (
+ <Modal showModal={showModal} setShowModal={setShowModal}>
+ <div className="border-b border-neutral-200 px-4 py-4 sm:px-6">
+ <h3 className="text-lg font-medium">Copy discount to live group</h3>
+ </div>
+
+ <div className="bg-neutral-50">
+ <form onSubmit={onSubmit}>
+ <div className="flex flex-col gap-2 px-4 py-6 text-left sm:px-6">
+ <label className="text-sm font-medium text-neutral-700">
+ Group
+ </label>
+
+ <Combobox
+ options={groupOptions}
+ selected={selectedGroup}
+ setSelected={setSelectedGroup}
+ placeholder={
+ liveGroupsLoading ? "Loading groups..." : "Select a group"
+ }
+ searchPlaceholder="Search groups..."
+ caret
+ matchTriggerWidth
+ buttonProps={{
+ className:
+ "w-full justify-start border-neutral-300 px-3 data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500 focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
+ }}
+ >
+ {selectedGroup ? (
+ <span>{selectedGroup.label}</span>
+ ) : liveGroupsLoading ? (
+ "Loading groups..."
+ ) : (
+ "Select a group"
+ )}
+ </Combobox>
+
+ <p className="text-xs font-normal text-neutral-500">
+ Select a group with no discount set up
+ </p>
+ </div>
+
+ <div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-8 w-fit rounded-lg"
+ onClick={() => setShowModal(false)}
+ disabled={isPending}
+ />
+ <Button
+ type="submit"
+ text="Confirm"
+ className="h-8 w-fit rounded-lg"
+ loading={isPending}
+ disabled={!selectedGroup}
+ />
+ </div>
+ </div>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useCopyDiscountToLiveModal() {
+ const [discount, setDiscount] = useState<DiscountProps | null>(null);
+
+ const openCopyDiscountToLiveModal = useCallback((discount: DiscountProps) => {
+ setDiscount(discount);
+ }, []);
+
+ const closeCopyDiscountToLiveModal = useCallback(() => {
+ setDiscount(null);
+ }, []);
+
+ const CopyDiscountToLiveModalCallback = useCallback(() => {
+ if (!discount) return null;
+
+ return (
+ <CopyDiscountToLiveModal
+ discount={discount}
+ showModal
+ setShowModal={(show) => {
+ if (!show) closeCopyDiscountToLiveModal();
+ }}
+ />
+ );
+ }, [discount, closeCopyDiscountToLiveModal]);
+
+ return useMemo(
+ () => ({
+ openCopyDiscountToLiveModal,
+ CopyDiscountToLiveModal: CopyDiscountToLiveModalCallback,
+ }),
+ [openCopyDiscountToLiveModal, CopyDiscountToLiveModalCallback],
+ );
+}
diff --git a/apps/web/lib/sandbox/copy-discount-to-live.ts b/apps/web/lib/sandbox/copy-discount-to-live.ts
new file mode 100644
index 0000000000..1ac39f2824
--- /dev/null
+++ b/apps/web/lib/sandbox/copy-discount-to-live.ts
@@ -0,0 +1,178 @@
+"use server";
+
+import { prisma } from "@dub/prisma";
+import { WorkspaceEnvironment } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+import { authActionClient } from "../actions/safe-action";
+import { throwIfNoPermission } from "../actions/throw-if-no-permission";
+import { recordAuditLog } from "../api/audit-logs/record-audit-log";
+import { createId } from "../api/create-id";
+import { getDiscountOrThrow } from "../api/partners/get-discount-or-throw";
+import { getDefaultProgramIdOrThrow } from "../api/programs/get-default-program-id-or-throw";
+import { qstash } from "../cron";
+import { getDiscountProvider } from "../discounts/discount-provider";
+import { DubDiscountAttributes } from "../stripe/coupon-discount-converter";
+import { copyDiscountToLiveSchema } from "./schemas";
+
+export const copyDiscountToLiveAction = authActionClient
+ .inputSchema(copyDiscountToLiveSchema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace, user } = ctx;
+ const { discountId, targetGroupId } = parsedInput;
+
+ const programId = getDefaultProgramIdOrThrow(workspace);
+
+ throwIfNoPermission({
+ role: workspace.role,
+ requiredRoles: ["owner", "member"],
+ });
+
+ if (workspace.environment !== WorkspaceEnvironment.staging) {
+ throw new Error("This action is only available in staging workspaces.");
+ }
+
+ const { program: targetProgram, ...targetGroup } =
+ await prisma.partnerGroup.findUniqueOrThrow({
+ where: {
+ id: targetGroupId,
+ },
+ include: {
+ program: {
+ select: {
+ id: true,
+ workspace: {
+ select: {
+ id: true,
+ environment: true,
+ stripeConnectId: true,
+ shopifyStoreId: true,
+ users: {
+ where: {
+ userId: user.id,
+ },
+ select: {
+ userId: true,
+ role: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ });
+
+ const { workspace: targetWorkspace } = targetProgram;
+
+ // Check user has access in the target program
+ if (targetWorkspace.users.length === 0) {
+ throw new Error("You are not allowed to copy a reward to this program.");
+ }
+
+ throwIfNoPermission({
+ role: targetWorkspace.users[0].role,
+ requiredRoles: ["owner", "member"],
+ });
+
+ if (targetWorkspace.environment !== WorkspaceEnvironment.live) {
+ throw new Error("Reward can only be copied to a live program.");
+ }
+
+ const discount = await getDiscountOrThrow({
+ discountId,
+ programId,
+ });
+
+ if (targetGroup.discountId) {
+ throw new Error("The target group already has a discount.");
+ }
+
+ const discountProvider = getDiscountProvider(discount.provider);
+
+ await discountProvider.assertDiscountIntegrationAvailable({
+ workspace: targetWorkspace,
+ });
+
+ let newCoupon: (DubDiscountAttributes & { id: string }) | null = null;
+
+ if (discount.provider === "stripe") {
+ newCoupon = await discountProvider.createCoupon({
+ workspace: targetWorkspace,
+ group: targetGroup,
+ data: {
+ amount: discount.amount,
+ type: discount.type,
+ maxDuration: discount.maxDuration,
+ },
+ });
+ }
+
+ const newDiscount = await prisma.$transaction(async (tx) => {
+ const newDiscount = await tx.discount.create({
+ data: {
+ id: createId({ prefix: "disc_" }),
+ programId: targetGroup.programId,
+ amount: discount.amount,
+ type: discount.type,
+ maxDuration: discount.maxDuration,
+ description: discount.description,
+ couponId: newCoupon?.id,
+ autoProvisionEnabledAt: discount.autoProvisionEnabledAt
+ ? new Date()
+ : null,
+ provider: discount.provider,
+ },
+ });
+
+ await tx.partnerGroup.update({
+ where: {
+ id: targetGroupId,
+ },
+ data: {
+ discountId: newDiscount.id,
+ },
+ });
+
+ await tx.programEnrollment.updateMany({
+ where: {
+ groupId: targetGroupId,
+ },
+ data: {
+ discountId: newDiscount.id,
+ },
+ });
+
+ return newDiscount;
+ });
+
+ waitUntil(
+ Promise.allSettled([
+ recordAuditLog({
+ workspaceId: targetWorkspace.id,
+ programId: targetProgram.id,
+ action: "discount.created",
+ description: `Discount ${newDiscount.id} copied from staging.`,
+ actor: user,
+ targets: [
+ {
+ type: "discount",
+ id: newDiscount.id,
+ metadata: newDiscount,
+ },
+ ],
+ }),
+
+ ...(newDiscount.autoProvisionEnabledAt
+ ? [
+ qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/create/queue-batches`,
+ body: {
+ discountId: newDiscount.id,
+ },
+ }),
+ ]
+ : []),
+ ]),
+ );
+ });
diff --git a/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx b/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx
index 3ac3fde08a..e432247f78 100644
--- a/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx
+++ b/apps/web/lib/sandbox/copy-reward-to-live-modal.tsx
@@ -22,13 +22,13 @@ function CopyRewardToLiveModal({
setShowModal: (show: boolean) => void;
reward: RewardProps;
}) {
- const { id: workspaceId } = useWorkspace();
- const { workspaces } = useWorkspaces();
-
const [selectedGroup, setSelectedGroup] = useState<ComboboxOption | null>(
null,
);
+ const { id: workspaceId } = useWorkspace();
+ const { workspaces } = useWorkspaces();
+
const liveWorkspace = workspaces?.find(
(w) => w.stagingWorkspaceId === workspaceId,
);
@@ -52,7 +52,7 @@ function CopyRewardToLiveModal({
onSuccess: () => {
setShowModal(false);
setSelectedGroup(null);
- toast.success("Reward copied to live program group!");
+ toast.success("Reward copied to live program!");
},
onError({ error }) {
toast.error(parseActionError(error, "Failed to copy reward to live"));
@@ -78,40 +78,38 @@ function CopyRewardToLiveModal({
<div className="bg-neutral-50">
<form onSubmit={onSubmit}>
- <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">
- <div>
- <label className="text-sm font-medium text-neutral-700">
- Group
- </label>
- <div className="mt-2">
- <Combobox
- options={groupOptions}
- selected={selectedGroup}
- setSelected={setSelectedGroup}
- placeholder={
- liveGroupsLoading ? "Loading groups..." : "Select a group"
- }
- searchPlaceholder="Search groups..."
- caret
- matchTriggerWidth
- buttonProps={{
- className:
- "w-full justify-start border-neutral-300 px-3 data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500 focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
- }}
- >
- {selectedGroup ? (
- <span>{selectedGroup.label}</span>
- ) : liveGroupsLoading ? (
- "Loading groups..."
- ) : (
- "Select a group"
- )}
- </Combobox>
- </div>
- <p className="mt-2 text-xs font-normal text-neutral-500">
- Select a group with no {reward.event} reward set up
- </p>
- </div>
+ <div className="flex flex-col gap-2 px-4 py-6 text-left sm:px-6">
+ <label className="text-sm font-medium text-neutral-700">
+ Group
+ </label>
+
+ <Combobox
+ options={groupOptions}
+ selected={selectedGroup}
+ setSelected={setSelectedGroup}
+ placeholder={
+ liveGroupsLoading ? "Loading groups..." : "Select a group"
+ }
+ searchPlaceholder="Search groups..."
+ caret
+ matchTriggerWidth
+ buttonProps={{
+ className:
+ "w-full justify-start border-neutral-300 px-3 data-[state=open]:ring-1 data-[state=open]:ring-neutral-500 data-[state=open]:border-neutral-500 focus:ring-1 focus:ring-neutral-500 focus:border-neutral-500 transition-none",
+ }}
+ >
+ {selectedGroup ? (
+ <span>{selectedGroup.label}</span>
+ ) : liveGroupsLoading ? (
+ "Loading groups..."
+ ) : (
+ "Select a group"
+ )}
+ </Combobox>
+
+ <p className="text-xs font-normal text-neutral-500">
+ Select a group with no {reward.event} reward set up
+ </p>
</div>
<div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">
diff --git a/apps/web/lib/sandbox/copy-reward-to-live.ts b/apps/web/lib/sandbox/copy-reward-to-live.ts
index 1a34494cf2..c4db40187d 100644
--- a/apps/web/lib/sandbox/copy-reward-to-live.ts
+++ b/apps/web/lib/sandbox/copy-reward-to-live.ts
@@ -90,15 +90,15 @@ export const copyRewardToLiveAction = authActionClient
data: {
id: createId({ prefix: "rw_" }),
programId: targetGroup.programId,
+ description: reward.description,
+ tooltipDescription: reward.tooltipDescription,
event: reward.event,
type: reward.type,
+ amountInCents: reward.amountInCents,
+ amountInPercentage: reward.amountInPercentage,
maxDuration: reward.maxDuration,
- description: reward.description,
- tooltipDescription: reward.tooltipDescription,
modifiers: reward.modifiers ?? undefined,
config: reward.config ?? undefined,
- amountInCents: reward.amountInCents,
- amountInPercentage: reward.amountInPercentage,
},
});