The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Shopify discount (#3804)
Kiran Kb2fd378c82b6
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 0abc5ccae0..f09accde36 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -192,4 +192,4 @@ E2E_PARTNER_PASSWORD=# Veriff (Identity Verification)VERIFF_API_KEY=-VERIFF_SHARED_SECRET=+VERIFF_SHARED_SECRET=\ No newline at end of filediff --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.tsindex 1f6c848853..97dc74dfdd 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@@ -1,6 +1,8 @@import { CRON_BATCH_SIZE, qstash } from "@/lib/cron";import { enqueueBatchJobs } from "@/lib/cron/enqueue-batch-jobs";import { withCron } from "@/lib/cron/with-cron";+import { isDiscountIntegrationNotAvailableError } from "@/lib/discounts/discount-error";+import { getDiscountProvider } from "@/lib/discounts/discount-provider";import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";@@ -30,6 +32,7 @@ export const POST = withCron(async ({ rawBody }) => {select: {id: true,stripeConnectId: true,+ shopifyStoreId: true,},},},@@ -48,12 +51,21 @@ export const POST = withCron(async ({ rawBody }) => {}const { program } = discount;- const { workspace } = program;- if (!workspace.stripeConnectId) {- return logAndRespond(- `Workspace ${workspace.id} does not have stripeConnectId set. Skipping...`,- );+ const discountProvider = getDiscountProvider(discount.provider);++ try {+ await discountProvider.assertDiscountIntegrationAvailable({+ workspace: program.workspace,+ });+ } catch (error) {+ if (isDiscountIntegrationNotAvailableError(error)) {+ return logAndRespond(+ `Workspace has not installed the ${discount.provider} integration. Skipping...`,+ );+ }++ throw error;}const programEnrollments = await prisma.programEnrollment.findMany({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.tsindex 13d79f2880..1686474716 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@@ -1,8 +1,7 @@-import { createDiscountCode } from "@/lib/api/discounts/create-discount-code";import { withCron } from "@/lib/cron/with-cron";-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";+import { createDiscountCode } from "@/lib/discounts/create-discount-code";+import { isDiscountIntegrationNotAvailableError } from "@/lib/discounts/discount-error";import { prisma } from "@dub/prisma";-import { STRIPE_INTEGRATION_ID } from "@dub/utils";import * as z from "zod/v4";import { logAndRespond } from "../../utils";@@ -46,11 +45,7 @@ export const POST = withCron(async ({ rawBody }) => {select: {id: true,stripeConnectId: true,- installedIntegrations: {- where: {- integrationId: STRIPE_INTEGRATION_ID,- },- },+ shopifyStoreId: true,},},},@@ -76,20 +71,10 @@ export const POST = withCron(async ({ rawBody }) => {);}- const { project: workspace, programEnrollment } = link;- const { partner, discount, program } = programEnrollment;-- if (!workspace.stripeConnectId) {- return logAndRespond(- `Workspace ${workspace.id} does not have stripeConnectId set. Skipping...`,- );- }-- if (!workspace.installedIntegrations.length) {- return logAndRespond(- `Workspace ${workspace.id} does not have the Stripe integration installed. Skipping...`,- );- }+ const {+ project: workspace,+ programEnrollment: { program, partner, discount },+ } = link;if (!discount) {return logAndRespond(@@ -97,17 +82,22 @@ export const POST = withCron(async ({ rawBody }) => {);}- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- workspace.installedIntegrations[0].settings || {},- );+ try {+ await createDiscountCode({+ workspace,+ partner,+ link,+ discount,+ });+ } catch (error) {+ if (isDiscountIntegrationNotAvailableError(error)) {+ return logAndRespond(+ `Workspace has not installed the ${discount.provider} integration. Skipping...`,+ );+ }- await createDiscountCode({- stripeConnectId: workspace.stripeConnectId,- stripeMode: stripeIntegrationSettings.stripeMode,- partner,- link,- discount,- });+ throw error;+ }return logAndRespond(`Discount code created for link ${linkId}.`);});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.tsindex fd4cac6c65..07f10e73bb 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@@ -1,8 +1,8 @@import { withCron } from "@/lib/cron/with-cron";-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";-import { disableStripeDiscountCode } from "@/lib/stripe/disable-stripe-discount-code";+import { isDiscountIntegrationNotAvailableError } from "@/lib/discounts/discount-error";+import { getDiscountProvider } from "@/lib/discounts/discount-provider";import { prisma } from "@dub/prisma";-import { STRIPE_INTEGRATION_ID } from "@dub/utils";+import { DiscountProvider } from "@dub/prisma/client";import * as z from "zod/v4";import { logAndRespond } from "../../utils";@@ -11,11 +11,12 @@ export const dynamic = "force-dynamic";const inputSchema = z.object({code: z.string(),programId: z.string(),+ provider: z.enum(DiscountProvider),});// POST /api/cron/discount-codes/deleteexport const POST = withCron(async ({ rawBody }) => {- const { code, programId } = inputSchema.parse(JSON.parse(rawBody));+ const { provider, code, programId } = inputSchema.parse(JSON.parse(rawBody));const workspace = await prisma.project.findUniqueOrThrow({where: {@@ -24,37 +25,24 @@ export const POST = withCron(async ({ rawBody }) => {select: {id: true,stripeConnectId: true,- installedIntegrations: {- where: {- integrationId: STRIPE_INTEGRATION_ID,- },- },+ shopifyStoreId: true,},});- if (!workspace.stripeConnectId || !workspace.installedIntegrations.length) {- return logAndRespond(- `Workspace ${workspace.id} does not have the Stripe integration installed. Skipping...`,- );- }-- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- workspace.installedIntegrations[0].settings || {},- );+ const discountProvider = getDiscountProvider(provider);- const disabledDiscountCode = await disableStripeDiscountCode({- code,- stripeConnectId: workspace.stripeConnectId,- stripeMode: stripeIntegrationSettings.stripeMode,- });+ try {+ await discountProvider.disableDiscountCode({+ workspace,+ code,+ });+ } catch (error) {+ if (isDiscountIntegrationNotAvailableError(error)) {+ return logAndRespond(`Skipping ${code}: ${error.message}`);+ }- if (!disabledDiscountCode) {- return logAndRespond(- `Failed to disable discount code ${code} in Stripe for ${workspace.stripeConnectId}.`,- );+ throw error;}- return logAndRespond(- `Discount code ${code} disabled from Stripe for ${workspace.stripeConnectId}.`,- );+ return logAndRespond(`Discount code ${code} disabled from ${provider}.`);});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.tsindex 12e8243518..66c9dfecca 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@@ -1,11 +1,10 @@-import { createDiscountCode } from "@/lib/api/discounts/create-discount-code";-import { deleteDiscountCodes } from "@/lib/api/discounts/delete-discount-code";-import { isDiscountEquivalent } from "@/lib/api/discounts/is-discount-equivalent";import { withCron } from "@/lib/cron/with-cron";-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";+import { createDiscountCode } from "@/lib/discounts/create-discount-code";+import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";+import { isDiscountIntegrationNotAvailableError } from "@/lib/discounts/discount-error";+import { isDiscountEquivalent } from "@/lib/discounts/is-discount-equivalent";import { prisma } from "@dub/prisma";-import { DiscountCode } from "@dub/prisma/client";-import { STRIPE_INTEGRATION_ID } from "@dub/utils";+import { Discount, DiscountCode } from "@dub/prisma/client";import * as z from "zod/v4";import { logAndRespond } from "../../utils";@@ -69,7 +68,9 @@ export const POST = withCron(async ({ rawBody }) => {// Find the discount codes to update and removeconst discountCodesToUpdate: DiscountCode[] = [];- const discountCodesToRemove: DiscountCode[] = [];+ const discountCodesToRemove: (DiscountCode & {+ discount: Pick<Discount, "provider"> | null;+ })[] = [];for (const discountCode of discountCodes) {const keepDiscountCode = isDiscountEquivalent(@@ -147,29 +148,30 @@ export const POST = withCron(async ({ rawBody }) => {defaultProgramId: programId,},select: {+ id: true,stripeConnectId: true,- installedIntegrations: {- where: {- integrationId: STRIPE_INTEGRATION_ID,- },- },+ shopifyStoreId: true,},});// Create discount code for the partner default links- if (workspace.stripeConnectId && workspace.installedIntegrations.length) {- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- workspace.installedIntegrations[0].settings || {},- );-- for (const link of links) {+ for (const link of links) {+ try {await createDiscountCode({- stripeConnectId: workspace.stripeConnectId,- stripeMode: stripeIntegrationSettings.stripeMode,+ workspace,partner: link.programEnrollment!.partner,link,discount: group.discount,});+ } catch (error) {+ if (isDiscountIntegrationNotAvailableError(error)) {+ console.warn(+ `Workspace has not installed the ${group.discount.provider} integration. Skipping remaining discount code creation for remap.`,+ );+ break;+ }++ throw error;}}}diff --git a/apps/web/app/(ee)/api/cron/partners/ban/route.ts b/apps/web/app/(ee)/api/cron/partners/ban/route.tsindex b550c15894..3a51388c68 100644--- a/apps/web/app/(ee)/api/cron/partners/ban/route.ts+++ b/apps/web/app/(ee)/api/cron/partners/ban/route.ts@@ -1,9 +1,9 @@-import { deleteDiscountCodes } from "@/lib/api/discounts/delete-discount-code";import { linkCache } from "@/lib/api/links/cache";import { includeTags } from "@/lib/api/links/include-tags";import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { withCron } from "@/lib/cron/with-cron";+import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";import { recordLink } from "@/lib/tinybird";import { BAN_PARTNER_REASONS } from "@/lib/zod/schemas/partners";import { sendEmail } from "@dub/email";@@ -24,23 +24,29 @@ export const POST = withCron(async ({ rawBody }) => {console.info(`Banning partner ${partnerId} from program ${programId}...`);- const { partner, links, program, ...programEnrollment } =+ const { partner, links, program, discountCodes, ...programEnrollment } =await getProgramEnrollmentOrThrow({partnerId,programId,include: {partner: true,links: {- include: {- ...includeTags,- discountCode: true,- },+ include: includeTags,},program: {select: {workspaceId: true,},},+ discountCodes: {+ include: {+ discount: {+ select: {+ provider: true,+ },+ },+ },+ },},});@@ -55,7 +61,7 @@ export const POST = withCron(async ({ rawBody }) => {partnerId,};- const [linksUpdated, bountySubmissions, discountCodes, payouts] =+ const [linksUpdated, bountySubmissions, discountCodesDeleted, payouts] =await prisma.$transaction([// Disable linksprisma.link.updateMany({@@ -108,7 +114,7 @@ export const POST = withCron(async ({ rawBody }) => {console.info(`Disabled ${linksUpdated.count} links.`);console.info(`Rejected ${bountySubmissions.count} bounty submissions.`);- console.info(`Removed ${discountCodes.count} discount codes.`);+ console.info(`Removed ${discountCodesDeleted.count} discount codes.`);console.info(`Canceled ${payouts.count} payouts.`);// Mark the commissions as canceled@@ -132,7 +138,7 @@ export const POST = withCron(async ({ rawBody }) => {recordLink(links, { deleted: true }),// Queue discount code deletions- deleteDiscountCodes(links.map((link) => link.discountCode)),+ deleteDiscountCodes(discountCodes),]);// Send emaildiff --git a/apps/web/app/(ee)/api/cron/partners/deactivate/route.ts b/apps/web/app/(ee)/api/cron/partners/deactivate/route.tsindex db7d99989f..db06b5de35 100644--- a/apps/web/app/(ee)/api/cron/partners/deactivate/route.ts+++ b/apps/web/app/(ee)/api/cron/partners/deactivate/route.ts@@ -1,6 +1,6 @@-import { deleteDiscountCodes } from "@/lib/api/discounts/delete-discount-code";import { linkCache } from "@/lib/api/links/cache";import { withCron } from "@/lib/cron/with-cron";+import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";import { sendBatchEmail } from "@dub/email";import PartnerDeactivated from "@dub/email/templates/partner-deactivated";import { prisma } from "@dub/prisma";@@ -37,7 +37,15 @@ export const POST = withCron(async ({ rawBody }) => {},},links: true,- discountCodes: true,+ discountCodes: {+ include: {+ discount: {+ select: {+ provider: true,+ },+ },+ },+ },},});diff --git a/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts b/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.tsindex be833968ef..d5a0a98ac3 100644--- a/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts+++ b/apps/web/app/(ee)/api/discount-codes/[discountCodeId]/route.ts@@ -1,8 +1,8 @@import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";-import { deleteDiscountCodes } from "@/lib/api/discounts/delete-discount-code";import { DubApiError } from "@/lib/api/errors";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { withWorkspace } from "@/lib/auth";+import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";import { prisma } from "@dub/prisma";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -17,9 +17,16 @@ export const DELETE = withWorkspace(where: {id: discountCodeId,},+ include: {+ discount: {+ select: {+ provider: true,+ },+ },+ },});- if (!discountCode || !discountCode.discountId) {+ if (!discountCode || !discountCode.discount) {throw new DubApiError({message: `Discount code (${discountCodeId}) not found.`,code: "bad_request",@@ -59,7 +66,7 @@ export const DELETE = withWorkspace(],}),- deleteDiscountCodes(discountCode),+ deleteDiscountCodes([discountCode]),]),);diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.tsindex fda236505b..921e93f24d 100644--- a/apps/web/app/(ee)/api/discount-codes/route.ts+++ b/apps/web/app/(ee)/api/discount-codes/route.ts@@ -1,18 +1,16 @@import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";-import { createDiscountCode } from "@/lib/api/discounts/create-discount-code";import { DubApiError } from "@/lib/api/errors";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";+import { createDiscountCode } from "@/lib/discounts/create-discount-code";import {createDiscountCodeSchema,DiscountCodeSchema,getDiscountCodesQuerySchema,} from "@/lib/zod/schemas/discount";import { prisma } from "@dub/prisma";-import { STRIPE_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";@@ -58,37 +56,6 @@ export const POST = withWorkspace(await parseRequestBody(req),);- if (!workspace.stripeConnectId) {- throw new DubApiError({- code: "bad_request",- message:- "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",- });- }-- const installedStripeIntegration =- await prisma.installedIntegration.findFirst({- where: {- projectId: workspace.id,- integrationId: STRIPE_INTEGRATION_ID,- },- select: {- settings: true,- },- });-- if (!installedStripeIntegration) {- throw new DubApiError({- code: "bad_request",- message:- "The Stripe integration is not installed on your workspace. Please install the Stripe integration under /settings/integrations/stripe to proceed.",- });- }-- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- installedStripeIntegration.settings || {},- );-const programEnrollment = await getProgramEnrollmentOrThrow({partnerId,programId,@@ -155,43 +122,32 @@ export const POST = withWorkspace(});}- try {- const discountCode = await createDiscountCode({- stripeConnectId: workspace.stripeConnectId,- stripeMode: stripeIntegrationSettings.stripeMode,- partner: programEnrollment.partner,- link,- discount,- code,- });+ const discountCode = await createDiscountCode({+ workspace,+ partner: programEnrollment.partner,+ link,+ discount,+ code,+ });- waitUntil(- recordAuditLog({- workspaceId: workspace.id,- programId,- action: "discount_code.created",- description: `Discount code (${discountCode.code}) created`,- actor: session.user,- targets: [- {- type: "discount_code",- id: discountCode.id,- metadata: discountCode,- },- ],- }),- );-- return NextResponse.json(DiscountCodeSchema.parse(discountCode));- } catch (error) {- throw new DubApiError({- code: "bad_request",- message:- error.code === "more_permissions_required_for_application"- ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."- : error.message,- });- }+ waitUntil(+ recordAuditLog({+ workspaceId: workspace.id,+ programId,+ action: "discount_code.created",+ description: `Discount code (${discountCode.code}) created`,+ actor: session.user,+ targets: [+ {+ type: "discount_code",+ id: discountCode.id,+ metadata: discountCode,+ },+ ],+ }),+ );++ return NextResponse.json(DiscountCodeSchema.parse(discountCode));},{requiredPlan: [diff --git a/apps/web/app/(ee)/api/partners/[partnerId]/route.ts b/apps/web/app/(ee)/api/partners/[partnerId]/route.tsindex c72baaa699..f98b525916 100644--- a/apps/web/app/(ee)/api/partners/[partnerId]/route.ts+++ b/apps/web/app/(ee)/api/partners/[partnerId]/route.ts@@ -16,11 +16,12 @@ export const GET = withWorkspace(partnerId,});- if (!partner)+ if (!partner) {throw new DubApiError({code: "not_found",message: "Partner not found.",});+ }return NextResponse.json(EnrolledPartnerSchemaExtended.parse(partner));},diff --git a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts b/apps/web/app/(ee)/api/shopify/integration/callback/route.tsindex e507999d90..7cba9c4fe5 100644--- a/apps/web/app/(ee)/api/shopify/integration/callback/route.ts+++ b/apps/web/app/(ee)/api/shopify/integration/callback/route.ts@@ -4,19 +4,27 @@ import { withWorkspace } from "@/lib/auth";import { installIntegration } from "@/lib/integrations/install";import { prisma } from "@dub/prisma";import { SHOPIFY_INTEGRATION_ID } from "@dub/utils";-import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";import * as z from "zod/v4";+const requestSchema = z.discriminatedUnion("action", [+ z.object({+ action: z.literal("connect"),+ shopifyStoreId: z.string().min(1),+ accessToken: z.string().min(1),+ scope: z.string().min(1),+ }),++ z.object({+ action: z.literal("disconnect"),+ shopifyStoreId: z.literal(null),+ }),+]);+// PATCH /api/shopify/integration/callback – update a shopify store idexport const PATCH = withWorkspace(async ({ req, workspace, session }) => {- const body = await parseRequestBody(req);- const { shopifyStoreId } = z- .object({- shopifyStoreId: z.string().nullable(),- })- .parse(body);+ const body = requestSchema.parse(await parseRequestBody(req));try {const response = await prisma.project.update({@@ -24,57 +32,47 @@ export const PATCH = withWorkspace(id: workspace.id,},data: {- shopifyStoreId,+ shopifyStoreId: body.shopifyStoreId,},select: {shopifyStoreId: true,},});- waitUntil(- (async () => {- const installation = await prisma.installedIntegration.findUnique({+ // Install the integration+ if (body.action === "connect") {+ await installIntegration({+ userId: session.user.id,+ workspaceId: workspace.id,+ integrationId: SHOPIFY_INTEGRATION_ID,+ credentials: {+ accessToken: body.accessToken,+ scope: body.scope,+ },+ });+ }++ // Uninstall the integration+ if (body.action === "disconnect") {+ try {+ await prisma.installedIntegration.delete({where: {userId_integrationId_projectId: {userId: session.user.id,- projectId: workspace.id,integrationId: SHOPIFY_INTEGRATION_ID,+ projectId: workspace.id,},},- select: {- id: true,- },});-- // Install the integration if it doesn't exist- if (!installation) {- await installIntegration({- userId: session.user.id,- workspaceId: workspace.id,- integrationId: SHOPIFY_INTEGRATION_ID,- credentials: {- shopifyStoreId,- },- });- }-- // Uninstall the integration if the shopify store id is null- if (installation && shopifyStoreId === null) {- await prisma.installedIntegration.delete({- where: {- id: installation.id,- },- });- }- })(),- );+ } catch {}+ }return NextResponse.json(response);} catch (error) {if (error.code === "P2002") {throw new DubApiError({code: "conflict",- message: `The shopify store "${shopifyStoreId}" is already in use.`,+ message: `The shopify store "${body.shopifyStoreId}" is already in use.`,});}diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.tsindex b208d75135..e0b6f99d2c 100644--- a/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/orders-paid.ts@@ -1,19 +1,27 @@import { qstash } from "@/lib/cron";-import { processOrder } from "@/lib/integrations/shopify/process-order";+import { createShopifySale } from "@/lib/integrations/shopify/create-sale";+import {+ attributeViaDiscountCode,+ processOrder,+} from "@/lib/integrations/shopify/process-order";import { orderSchema } from "@/lib/integrations/shopify/schema";+import { WorkspaceProps } from "@/lib/types";import { redis } from "@/lib/upstash";import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";export async function ordersPaid({event,- workspaceId,+ workspace,}: {event: any;- workspaceId: string;+ workspace: Pick<WorkspaceProps, "id" | "defaultProgramId" | "webhookEnabled">;}) {- const { customer: orderCustomer, checkout_token: checkoutToken } =- orderSchema.parse(event);+ const {+ customer: orderCustomer,+ checkout_token: checkoutToken,+ discount_codes: discountCodes,+ } = orderSchema.parse(event);if (orderCustomer) {const { id: externalId } = orderCustomer;@@ -21,7 +29,7 @@ export async function ordersPaid({const customer = await prisma.customer.findUnique({where: {projectId_externalId: {- projectId: workspaceId,+ projectId: workspace.id,externalId: externalId.toString(),},},@@ -31,7 +39,7 @@ export async function ordersPaid({if (customer) {await processOrder({event,- workspaceId,+ workspaceId: workspace.id,customerId: customer.id,});@@ -39,6 +47,41 @@ export async function ordersPaid({}}+ // Check if the order has created using a program discount code+ if (discountCodes && discountCodes.length > 0 && workspace.defaultProgramId) {+ const programDiscountCodes = await prisma.discountCode.findMany({+ where: {+ programId: workspace.defaultProgramId,+ code: {+ in: discountCodes.map(({ code }) => code),+ },+ },+ include: {+ link: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ if (programDiscountCodes.length > 0) {+ const { customer, leadEvent: leadData } = await attributeViaDiscountCode({+ event,+ workspace,+ link: programDiscountCodes[0].link,+ });++ await createShopifySale({+ leadData,+ event,+ workspaceId: workspace.id,+ customerId: customer.id,+ });++ return "[Shopify] Order event processed successfully with discount codes.";+ }+ }+// Check the cache to see the pixel event for this checkout token exist before publishing the event to the queueconst clickId = await redis.hget<string>(`shopify:checkout:${checkoutToken}`,@@ -56,7 +99,7 @@ export async function ordersPaid({else if (clickId) {await processOrder({event,- workspaceId,+ workspaceId: workspace.id,clickId,});@@ -73,7 +116,7 @@ export async function ordersPaid({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/shopify/order-paid`,body: {checkoutToken,- workspaceId,+ workspaceId: workspace.id,},retries: 5,delay: 3,diff --git a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts b/apps/web/app/(ee)/api/shopify/integration/webhook/route.tsindex ae468ed5cc..fddd2c4a9b 100644--- a/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/shopify/integration/webhook/route.ts@@ -1,4 +1,5 @@import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";+import { isLocalDev } from "@/lib/api/environment";import { prisma } from "@dub/prisma";import { log } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -27,16 +28,18 @@ export const POST = async (req: Request) => {const topic = headers.get("x-shopify-topic") || "";const signature = headers.get("x-shopify-hmac-sha256") || "";- // Verify signature- const generatedSignature = crypto- .createHmac("sha256", `${process.env.SHOPIFY_WEBHOOK_SECRET}`)- .update(data, "utf8")- .digest("base64");-- if (generatedSignature !== signature) {- return new Response(`[Shopify] Invalid webhook signature. Skipping...`, {- status: 401,- });+ if (!isLocalDev) {+ // Verify signature+ const generatedSignature = crypto+ .createHmac("sha256", `${process.env.SHOPIFY_WEBHOOK_SECRET}`)+ .update(data, "utf8")+ .digest("base64");++ if (generatedSignature !== signature) {+ return new Response(`[Shopify] Invalid webhook signature. Skipping...`, {+ status: 401,+ });+ }}// Check if topic is relevant@@ -54,6 +57,8 @@ export const POST = async (req: Request) => {},select: {id: true,+ defaultProgramId: true,+ webhookEnabled: true,},});@@ -78,7 +83,7 @@ export const POST = async (req: Request) => {case "orders/paid":response = await ordersPaid({event,- workspaceId: workspace.id,+ workspace,});break;case "customers/data_request":diff --git a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts b/apps/web/app/(ee)/api/workflows/partner-approved/route.tsindex 4598012fd2..d0e227d58c 100644--- a/apps/web/app/(ee)/api/workflows/partner-approved/route.ts+++ b/apps/web/app/(ee)/api/workflows/partner-approved/route.ts@@ -1,10 +1,10 @@-import { generateDiscountCodeForPartner } from "@/lib/api/discounts/generate-discount-code-for-partner";import { createPartnerDefaultLinks } from "@/lib/api/partners/create-partner-default-links";import { getGroupRewardsAndBounties } from "@/lib/api/partners/get-group-rewards-and-bounties";import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";import { createWorkflowLogger } from "@/lib/cron/qstash-workflow-logger";+import { generateDiscountCodeForPartner } from "@/lib/discounts/generate-discount-code-for-partner";import { polyfillSocialMediaFields } from "@/lib/social-utils";import { PlanProps } from "@/lib/types";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsxindex b9ecfb2184..78da748cb3 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/[partnerId]/links/page.tsx@@ -5,11 +5,16 @@ import useDiscountCodes from "@/lib/swr/use-discount-codes";import useGroup from "@/lib/swr/use-group";import usePartner from "@/lib/swr/use-partner";import useWorkspace from "@/lib/swr/use-workspace";-import { DiscountCodeProps, EnrolledPartnerProps } from "@/lib/types";+import {+ DiscountCodeProps,+ EnrolledPartnerExtendedProps,+ EnrolledPartnerProps,+} from "@/lib/types";import { useAddDiscountCodeModal } from "@/ui/modals/add-discount-code-modal";import { useAddPartnerLinkModal } from "@/ui/modals/add-partner-link-modal";import { DeleteDiscountCodeModal } from "@/ui/modals/delete-discount-code-modal";import { DiscountCodeBadge } from "@/ui/partners/discounts/discount-code-badge";+import { DiscountProvider } from "@dub/prisma/client";import {Button,CopyButton,@@ -177,9 +182,9 @@ const PartnerLinks = ({ partner }: { partner: EnrolledPartnerProps }) => {const PartnerDiscountCodes = ({partner,}: {- partner: EnrolledPartnerProps;+ partner: EnrolledPartnerExtendedProps;}) => {- const { slug, stripeConnectId } = useWorkspace();+ const { slug, stripeConnectId, shopifyStoreId } = useWorkspace();const [selectedDiscountCode, setSelectedDiscountCode] =useState<DiscountCodeProps | null>(null);@@ -252,7 +257,14 @@ const PartnerDiscountCodes = ({} as any);const disabledReason = useMemo(() => {- if (!stripeConnectId) {+ if (!partner.discount) {+ return "No discount assigned to this partner group. Please add a discount before you can create a discount code.";+ }++ if (+ partner.discount.provider === DiscountProvider.stripe &&+ !stripeConnectId+ ) {return (<TooltipContenttitle="Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount codes."@@ -263,8 +275,18 @@ const PartnerDiscountCodes = ({);}- if (!partner.discountId) {- return "No discount assigned to this partner group. Please add a discount before you can create a discount code.";+ if (+ partner.discount.provider === DiscountProvider.shopify &&+ !shopifyStoreId+ ) {+ return (+ <TooltipContent+ title="Your workspace isn't connected to Shopify yet. Please install the Dub Shopify app in settings to create discount codes."+ cta="Install Shopify app"+ href={`/${slug}/settings/integrations/shopify`}+ target="_blank"+ />+ );}if (partner.links?.length === 0) {@@ -276,7 +298,13 @@ const PartnerDiscountCodes = ({}return undefined;- }, [partner.discountId, partner.links, discountCodes, stripeConnectId]);+ }, [+ partner.discount,+ partner.links,+ discountCodes,+ stripeConnectId,+ shopifyStoreId,+ ]);return (<>diff --git a/apps/web/lib/actions/partners/accept-program-invite.ts b/apps/web/lib/actions/partners/accept-program-invite.tsindex f19bba6246..1d189a2f95 100644--- a/apps/web/lib/actions/partners/accept-program-invite.ts+++ b/apps/web/lib/actions/partners/accept-program-invite.ts@@ -1,8 +1,8 @@"use server";-import { generateDiscountCodeForPartner } from "@/lib/api/discounts/generate-discount-code-for-partner";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { triggerDraftBountySubmissionCreation } from "@/lib/bounty/api/trigger-draft-bounty-submissions";+import { generateDiscountCodeForPartner } from "@/lib/discounts/generate-discount-code-for-partner";import { polyfillSocialMediaFields } from "@/lib/social-utils";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { EnrolledPartnerSchema } from "@/lib/zod/schemas/partners";diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex a957d6ae90..61e3000cd8 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -5,22 +5,13 @@ import { createId } from "@/lib/api/create-id";import { getGroupOrThrow } from "@/lib/api/groups/get-group-or-throw";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { qstash } from "@/lib/cron";-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";-import { stripeAppClient } from "@/lib/stripe";-import {- dubDiscountToStripeCoupon,- stripeCouponToDubDiscount,- validateStripeCouponForDubDiscount,-} from "@/lib/stripe/coupon-discount-converter";+import { getDiscountProvider } from "@/lib/discounts/discount-provider";+import { DubDiscountAttributes } from "@/lib/stripe/coupon-discount-converter";import { createDiscountSchema } from "@/lib/zod/schemas/discount";import { prisma } from "@dub/prisma";-import {- APP_DOMAIN_WITH_NGROK,- STRIPE_INTEGRATION_ID,- truncate,-} from "@dub/utils";+import { DiscountProvider } from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { waitUntil } from "@vercel/functions";-import { Stripe } from "stripe";import { authActionClient } from "../safe-action";import { throwIfNoPermission } from "../throw-if-no-permission";@@ -28,7 +19,8 @@ export const createDiscountAction = authActionClient.inputSchema(createDiscountSchema).action(async ({ parsedInput, ctx }) => {const { workspace, user } = ctx;- let {+ const {+ provider,amount,type,maxDuration,@@ -56,79 +48,28 @@ export const createDiscountAction = authActionClient);}- if (!workspace.stripeConnectId) {- throw new Error(- "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount.",- );- }-- const installedStripeIntegration =- await prisma.installedIntegration.findFirst({- where: {- projectId: workspace.id,- integrationId: STRIPE_INTEGRATION_ID,- },- select: {- settings: true,- },- });+ const discountProvider = getDiscountProvider(provider);- if (!installedStripeIntegration) {- throw new Error(- "STRIPE_CONNECTION_REQUIRED: Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount.",- );- }+ let coupon: (DubDiscountAttributes & { id: string }) | null = null;- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- installedStripeIntegration.settings || {},- );-- const stripe = stripeAppClient({- mode: stripeIntegrationSettings.stripeMode,- });-- let stripeCoupon: Stripe.Coupon | undefined;- try {+ // Fetch existing coupon if couponId is provided otherwise create a new coupon on the discount provider+ if (provider === DiscountProvider.stripe) {if (couponId) {- stripeCoupon = await stripe.coupons.retrieve(couponId, {- stripeAccount: workspace.stripeConnectId,+ coupon = await discountProvider.getCoupon({+ couponId,+ workspace,});-- // Validate the Stripe coupon can be converted to a Dub discount- const validation = validateStripeCouponForDubDiscount(stripeCoupon);- if (!validation.isValid) {- throw new Error(- `Invalid Stripe coupon: ${validation.errors.join(", ")}`,- );- }-- // Convert Stripe coupon to Dub discount attributes- const dubDiscountAttrs = stripeCouponToDubDiscount(stripeCoupon);- amount = dubDiscountAttrs.amount;- type = dubDiscountAttrs.type;- maxDuration = dubDiscountAttrs.maxDuration;-- // if there is no couponId provided, we need to create a new coupon on Stripe} else {- const stripeCouponData = dubDiscountToStripeCoupon({- name: `Dub Discount (${truncate(group.name, 25)})`,- amount,- type,- maxDuration: maxDuration ?? null,- });-- stripeCoupon = await stripe.coupons.create(stripeCouponData, {- stripeAccount: workspace.stripeConnectId,+ coupon = await discountProvider.createCoupon({+ workspace,+ group,+ data: parsedInput,});}- } catch (error) {- throw new Error(- error.code === "more_permissions_required_for_application"- ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."- : error.code === "resource_missing"- ? `The coupon ID you provided (${couponId}) was not found in your Stripe account. Please check the coupon ID and try again.`- : error.message,- );+ } else if (provider === DiscountProvider.shopify) {+ await discountProvider.assertDiscountIntegrationAvailable({+ workspace,+ });}// Create the discount and update the group and program enrollment@@ -140,7 +81,8 @@ export const createDiscountAction = authActionClientamount,type,maxDuration,- couponId: stripeCoupon?.id || couponId,+ provider,+ couponId: coupon?.id || couponId || null,...(couponTestId && { couponTestId }),...(autoProvision && { autoProvisionEnabledAt: new Date() }),},diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.tsindex 2b8babfe3c..b10864b38d 100644--- a/apps/web/lib/actions/partners/delete-discount.ts+++ b/apps/web/lib/actions/partners/delete-discount.ts@@ -1,10 +1,10 @@"use server";import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";-import { deleteDiscountCodes } from "@/lib/api/discounts/delete-discount-code";import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { qstash } from "@/lib/cron";+import { deleteDiscountCodes } from "@/lib/discounts/delete-discount-code";import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -40,6 +40,16 @@ export const deleteDiscountAction = authActionClientwhere: {discountId: discount.id,},+ select: {+ id: true,+ code: true,+ programId: true,+ discount: {+ select: {+ provider: true,+ },+ },+ },});const group = await prisma.$transaction(async (tx) => {diff --git a/apps/web/lib/api/discounts/delete-discount-code.ts b/apps/web/lib/api/discounts/delete-discount-code.tsdeleted file mode 100644index 17cb791912..0000000000--- a/apps/web/lib/api/discounts/delete-discount-code.ts+++ /dev/null@@ -1,62 +0,0 @@-import { qstash } from "@/lib/cron";-import { prisma } from "@dub/prisma";-import { DiscountCode } from "@dub/prisma/client";-import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";--const queue = qstash.queue({- queueName: "delete-discount-code",-});--type DiscountCodePayload = Pick<DiscountCode, "id" | "code" | "programId">;--type DeleteDiscountCodesParams =- | DiscountCodePayload- | (DiscountCodePayload | null | undefined)[];--// Triggered in the following cases:-// 1. When a discount is deleted-// 2. When a link is deleted that has a discount code associated with it-// 3. When partners are banned / deactivated-// 4. When a partner is moved to a different group-export async function deleteDiscountCodes(input: DeleteDiscountCodesParams) {- const raw = Array.isArray(input) ? input : [input];- const discountCodes = raw.filter(- (dc): dc is NonNullable<typeof dc> => dc != null,- );-- if (discountCodes.length === 0) {- return;- }-- // Delete the discount codes from the database- const deletedDiscountCodes = await prisma.discountCode.deleteMany({- where: {- id: {- in: discountCodes.map(({ id }) => id),- },- },- });-- console.log(- `Deleted ${deletedDiscountCodes.count} discount codes.`,- discountCodes.map(({ id, code }) => ({ id, code })),- );-- // Queue the job to remove the discount codes from Stripe- const chunks = chunk(discountCodes, 100);-- for (const chunkOfCodes of chunks) {- await Promise.allSettled(- chunkOfCodes.map((discountCode) =>- queue.enqueueJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/delete`,- method: "POST",- body: {- code: discountCode.code,- programId: discountCode.programId,- },- }),- ),- );- }-}diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.tsindex bc3c997cce..fa0405065f 100644--- a/apps/web/lib/api/links/delete-link.ts+++ b/apps/web/lib/api/links/delete-link.ts@@ -3,7 +3,7 @@ import { recordLink } from "@/lib/tinybird";import { prisma } from "@dub/prisma";import { R2_URL } from "@dub/utils";import { waitUntil } from "@vercel/functions";-import { deleteDiscountCodes } from "../discounts/delete-discount-code";+import { deleteDiscountCodes } from "../../discounts/delete-discount-code";import { linkCache } from "./cache";import { includeProgramEnrollment } from "./include-program-enrollment";import { includeTags } from "./include-tags";@@ -17,7 +17,15 @@ export async function deleteLink(linkId: string) {include: {...includeTags,...includeProgramEnrollment,- discountCode: true,+ discountCode: {+ include: {+ discount: {+ select: {+ provider: true,+ },+ },+ },+ },},});@@ -40,11 +48,13 @@ export async function deleteLink(linkId: string) {id: link.projectId,},data: {- totalLinks: { decrement: 1 },+ totalLinks: {+ decrement: 1,+ },},}),- link.discountCode && deleteDiscountCodes(link.discountCode),+ link.discountCode && deleteDiscountCodes([link.discountCode]),]),);diff --git a/apps/web/lib/api/partner-profile/get-partner-for-program.ts b/apps/web/lib/api/partner-profile/get-partner-for-program.tsindex 2fa69fe1a5..9a69ce6342 100644--- a/apps/web/lib/api/partner-profile/get-partner-for-program.ts+++ b/apps/web/lib/api/partner-profile/get-partner-for-program.ts@@ -25,6 +25,12 @@ export async function getPartnerForProgram({},},links: true,+ discount: {+ select: {+ id: true,+ provider: true,+ },+ },},});diff --git a/apps/web/lib/api/partners/bulk-delete-partners.ts b/apps/web/lib/api/partners/bulk-delete-partners.tsindex 3286b85334..7741478888 100644--- a/apps/web/lib/api/partners/bulk-delete-partners.ts+++ b/apps/web/lib/api/partners/bulk-delete-partners.ts@@ -1,7 +1,7 @@import { conn } from "@/lib/planetscale";import { prisma } from "@dub/prisma";import { ACME_PROGRAM_ID } from "@dub/utils";-import { deleteDiscountCodes } from "../discounts/delete-discount-code";+import { deleteDiscountCodes } from "../../discounts/delete-discount-code";import { bulkDeleteLinks } from "../links/bulk-delete-links";const BATCH_SIZE = 250;@@ -69,6 +69,11 @@ export async function bulkDeletePartners({id: true,code: true,programId: true,+ discount: {+ select: {+ provider: true,+ },+ },},});diff --git a/apps/web/lib/cron/enqueue-batch-jobs.ts b/apps/web/lib/cron/enqueue-batch-jobs.tsindex a8b4f8c56f..ca8016ff94 100644--- a/apps/web/lib/cron/enqueue-batch-jobs.ts+++ b/apps/web/lib/cron/enqueue-batch-jobs.ts@@ -8,7 +8,8 @@ type EnqueueBatchJobsProps = PublishBatchRequest<unknown> & {| "send-partner-summary"| "create-discount-code"| "sync-bounty-social-metrics"- | "process-hubspot-webhook";+ | "process-hubspot-webhook"+ | "delete-discount-code";};// Generic helper to enqueue a batch of QStash jobs.diff --git a/apps/web/lib/api/discounts/construct-discount-code.ts b/apps/web/lib/discounts/construct-discount-code.tssimilarity index 100%rename from apps/web/lib/api/discounts/construct-discount-code.tsrename to apps/web/lib/discounts/construct-discount-code.tsdiff --git a/apps/web/lib/api/discounts/create-discount-code.ts b/apps/web/lib/discounts/create-discount-code.tssimilarity index 53%rename from apps/web/lib/api/discounts/create-discount-code.tsrename to apps/web/lib/discounts/create-discount-code.tsindex 454a5dd5a5..fbc5559027 100644--- a/apps/web/lib/api/discounts/create-discount-code.ts+++ b/apps/web/lib/discounts/create-discount-code.ts@@ -1,25 +1,24 @@import { createId } from "@/lib/api/create-id";-import { createStripeDiscountCode } from "@/lib/stripe/create-stripe-discount-code";-import { StripeMode } from "@/lib/types";import { prisma } from "@dub/prisma";-import { Discount, Link, Partner } from "@dub/prisma/client";+import { Discount, Link, Partner, Project } from "@dub/prisma/client";import { constructDiscountCode } from "./construct-discount-code";+import { getDiscountProvider } from "./discount-provider";++interface CreateDiscountCodeArgs {+ workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;+ partner: Pick<Partner, "id" | "name">;+ link: Pick<Link, "id">;+ discount: Discount;+ code?: string;+}export async function createDiscountCode({- stripeConnectId,- stripeMode,+ workspace,partner,link,discount,code,-}: {- stripeConnectId: string;- stripeMode: StripeMode;- partner: Pick<Partner, "id" | "name">;- link: Pick<Link, "id">;- discount: Pick<Discount, "id" | "programId" | "couponId" | "amount" | "type">;- code?: string;-}) {+}: CreateDiscountCodeArgs) {let finalCode = code;// Construct the discount code if no code is provided@@ -30,28 +29,23 @@ export async function createDiscountCode({});}- const stripeDiscountCode = await createStripeDiscountCode({- stripeConnectId,- stripeMode,+ const discountProvider = getDiscountProvider(discount.provider);++ const discountCode = await discountProvider.createDiscountCode({+ workspace,discount,code: finalCode,shouldRetry: code ? false : true,});- const discountCode = await prisma.discountCode.create({+ return await prisma.discountCode.create({data: {id: createId({ prefix: "dcode_" }),- code: stripeDiscountCode.code,+ code: discountCode.code,programId: discount.programId,partnerId: partner.id,linkId: link.id,discountId: discount.id,},});-- console.log(- `Created discount code ${discountCode.code} for the link ${link.id}.`,- );-- return discountCode;}diff --git a/apps/web/lib/discounts/delete-discount-code.ts b/apps/web/lib/discounts/delete-discount-code.tsnew file mode 100644index 0000000000..1583e7f0ee--- /dev/null+++ b/apps/web/lib/discounts/delete-discount-code.ts@@ -0,0 +1,77 @@+import { prisma } from "@dub/prisma";+import { Discount, DiscountCode } from "@dub/prisma/client";+import { APP_DOMAIN_WITH_NGROK, chunk } from "@dub/utils";+import { enqueueBatchJobs } from "../cron/enqueue-batch-jobs";++type DeleteDiscountCodesParams = Pick<+ DiscountCode,+ "id" | "code" | "programId"+> & {+ discount: Pick<Discount, "provider"> | null;+};++// Triggered in the following cases:+// 1. When a discount is deleted+// 2. When a link is deleted that has a discount code associated with it+// 3. When partners are banned / deactivated+// 4. When a partner is moved to a different group+export async function deleteDiscountCodes(+ input: (DeleteDiscountCodesParams | null | undefined)[],+) {+ const discountCodes = input.filter(+ (dc): dc is NonNullable<typeof dc> => dc != null,+ );++ if (discountCodes.length === 0) {+ console.log(+ "[deleteDiscountCodes] No discount codes to delete. Skipping...",+ );+ return;+ }++ // Delete the discount codes from the database+ const deletedDiscountCodes = await prisma.discountCode.deleteMany({+ where: {+ id: {+ in: discountCodes.map(({ id }) => id),+ },+ },+ });++ console.log(+ `[deleteDiscountCodes] Deleted ${deletedDiscountCodes.count} discount codes.`,+ );++ // Only enqueue external-provider cleanup for codes whose provider is known.+ // Orphaned codes (discount relation is null) still get deleted locally above+ // but we can't tell which external provider to clean up, so we skip them.+ const codesWithProvider = discountCodes.filter(+ (dc): dc is typeof dc & { discount: Pick<Discount, "provider"> } =>+ dc.discount != null,+ );++ const orphanedCount = discountCodes.length - codesWithProvider.length;+ if (orphanedCount > 0) {+ console.warn(+ `[deleteDiscountCodes] Skipping external provider cleanup for ${orphanedCount} orphaned discount code(s) with no discount relation.`,+ );+ }++ // Queue the job to remove the discount codes from provider+ const chunks = chunk(codesWithProvider, 100);++ for (const chunkOfCodes of chunks) {+ await enqueueBatchJobs(+ chunkOfCodes.map((discountCode) => ({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/discount-codes/delete`,+ method: "POST",+ queueName: "delete-discount-code",+ body: {+ code: discountCode.code,+ programId: discountCode.programId,+ provider: discountCode.discount.provider,+ },+ })),+ );+ }+}diff --git a/apps/web/lib/discounts/discount-error.ts b/apps/web/lib/discounts/discount-error.tsnew file mode 100644index 0000000000..4b0a6b2ded--- /dev/null+++ b/apps/web/lib/discounts/discount-error.ts@@ -0,0 +1,15 @@+import { DubApiError } from "../api/errors";++export class DiscountIntegrationNotAvailableError extends DubApiError {+ constructor({ message }: { message: string }) {+ super({ code: "bad_request", message });+ this.name = "DiscountIntegrationNotAvailableError";+ Object.setPrototypeOf(this, new.target.prototype);+ }+}++export function isDiscountIntegrationNotAvailableError(+ error: unknown,+): error is DiscountIntegrationNotAvailableError {+ return error instanceof DiscountIntegrationNotAvailableError;+}diff --git a/apps/web/lib/discounts/discount-provider-shopify.ts b/apps/web/lib/discounts/discount-provider-shopify.tsnew file mode 100644index 0000000000..52c69d1e80--- /dev/null+++ b/apps/web/lib/discounts/discount-provider-shopify.ts@@ -0,0 +1,292 @@+import { prisma } from "@dub/prisma";+import { Discount, Project } from "@dub/prisma/client";+import { SHOPIFY_INTEGRATION_ID, nanoid } from "@dub/utils";+import {+ ShopifyAdminGraphqlError,+ shopifyAdminGraphql,+} from "../integrations/shopify/admin-graphql";+import { integrationCredentialsSchema } from "../integrations/shopify/schema";+import { DiscountIntegrationNotAvailableError } from "./discount-error";++interface ShopifyDiscountCodeBasicCreate {+ codeDiscountNode: {+ id: string;+ codeDiscount: {+ codes: { nodes: { code: string }[] };+ };+ } | null;+ userErrors: {+ field: string[] | null;+ message: string;+ code: string;+ }[];+}++interface ShopifyDiscountCodeDelete {+ deletedCodeDiscountId: string | null;+ userErrors: {+ field: string[] | null;+ message: string;+ code: string;+ }[];+}++const MAX_ATTEMPTS = 3;++async function requireInstalledIntegration(+ workspace: Pick<Project, "id" | "shopifyStoreId">,+) {+ 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.",+ });+ }++ const installation = await prisma.installedIntegration.findFirst({+ where: {+ projectId: workspace.id,+ integrationId: SHOPIFY_INTEGRATION_ID,+ },+ });++ 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.",+ });+ }++ let credentials = integrationCredentialsSchema.parse(+ installation.credentials || {},+ );++ 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.",+ });+ }++ return {+ ...installation,+ credentials,+ };+}++function createShopifyDiscountProvider() {+ const getCoupon = async () => {+ throw new Error("Shopify does not this method.");+ };++ const createCoupon = async () => {+ throw new Error("Shopify does not this method.");+ };++ const createDiscountCode = async ({+ workspace,+ discount,+ code,+ shouldRetry = true,+ }: {+ workspace: Pick<Project, "id" | "shopifyStoreId">;+ discount: Pick<Discount, "id" | "amount" | "type">;+ code: string;+ shouldRetry?: boolean;+ }) => {+ const { credentials } = await requireInstalledIntegration(workspace);++ let attempt = 0;+ let currentCode = code;++ while (attempt < MAX_ATTEMPTS) {+ try {+ const data = await shopifyAdminGraphql<{+ discountCodeBasicCreate: ShopifyDiscountCodeBasicCreate;+ }>({+ shopifyStoreId: workspace.shopifyStoreId!,+ accessToken: credentials.accessToken!,+ query: /* GraphQL */ `+ mutation DiscountCodeBasicCreate(+ $basicCodeDiscount: DiscountCodeBasicInput!+ ) {+ discountCodeBasicCreate(basicCodeDiscount: $basicCodeDiscount) {+ codeDiscountNode {+ id+ codeDiscount {+ ... on DiscountCodeBasic {+ codes(first: 1) {+ nodes {+ code+ }+ }+ }+ }+ }+ userErrors {+ field+ message+ code+ }+ }+ }+ `,+ variables: {+ basicCodeDiscount: {+ title: `Dub Discount (${currentCode})`,+ code: currentCode.toUpperCase(),+ startsAt: new Date().toISOString(),+ customerSelection: { all: true },+ appliesOncePerCustomer: true,+ customerGets: {+ items: { all: true },+ value:+ discount.type === "percentage"+ ? { percentage: discount.amount / 100 }+ : {+ discountAmount: {+ amount: (discount.amount / 100).toFixed(2),+ appliesOnEachItem: false,+ },+ },+ },+ },+ },+ });++ const { codeDiscountNode, userErrors } = data.discountCodeBasicCreate;++ if (userErrors.length > 0) {+ throw new ShopifyAdminGraphqlError(+ userErrors[0].code,+ userErrors[0].message,+ userErrors,+ );+ }++ if (!codeDiscountNode) {+ throw new ShopifyAdminGraphqlError(+ "no_node_returned",+ "Shopify did not return a discount code node.",+ );+ }++ return {+ code: codeDiscountNode.codeDiscount.codes.nodes[0].code,+ };+ } catch (error) {+ const isDuplicate =+ error instanceof ShopifyAdminGraphqlError &&+ (error.code === "TAKEN" || error.code === "DUPLICATE");++ if (!isDuplicate || !shouldRetry) {+ throw error;+ }++ attempt++;++ if (attempt >= MAX_ATTEMPTS) {+ throw error;+ }++ const newCode = `${currentCode}${nanoid(2)}`;++ console.warn(+ `Discount code "${currentCode}" already exists in Shopify. Retrying with "${newCode}" (attempt ${attempt}/${MAX_ATTEMPTS}).`,+ );++ currentCode = newCode;+ }+ }++ throw new Error("Failed to create Shopify discount code.");+ };++ const disableDiscountCode = async ({+ workspace,+ code,+ }: {+ workspace: Pick<Project, "id" | "shopifyStoreId">;+ code: string;+ }) => {+ const { credentials } = await requireInstalledIntegration(workspace);++ const lookup = await shopifyAdminGraphql<{+ codeDiscountNodeByCode: { id: string } | null;+ }>({+ shopifyStoreId: workspace.shopifyStoreId!,+ accessToken: credentials.accessToken!,+ query: /* GraphQL */ `+ query CodeDiscountNodeByCode($code: String!) {+ codeDiscountNodeByCode(code: $code) {+ id+ }+ }+ `,+ variables: { code },+ });++ const id = lookup.codeDiscountNodeByCode?.id;++ if (!id) {+ console.error(+ `Shopify discount code ${code} not found (shopifyStoreId=${workspace.shopifyStoreId!}).`,+ );+ return;+ }++ const data = await shopifyAdminGraphql<{+ discountCodeDelete: ShopifyDiscountCodeDelete;+ }>({+ shopifyStoreId: workspace.shopifyStoreId!,+ accessToken: credentials.accessToken!,+ query: /* GraphQL */ `+ mutation DiscountCodeDelete($id: ID!) {+ discountCodeDelete(id: $id) {+ deletedCodeDiscountId+ userErrors {+ field+ message+ code+ }+ }+ }+ `,+ variables: { id },+ });++ const { userErrors } = data.discountCodeDelete;++ if (userErrors.length > 0) {+ throw new ShopifyAdminGraphqlError(+ userErrors[0].code,+ userErrors[0].message,+ userErrors,+ );+ }++ console.info(+ `Deleted Shopify discount code ${code} (id=${id}, shopifyStoreId=${workspace.shopifyStoreId}).`,+ );++ return { id, code };+ };++ const assertDiscountIntegrationAvailable = async ({+ workspace,+ }: {+ workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;+ }) => {+ await requireInstalledIntegration(workspace);+ };++ return {+ getCoupon,+ createCoupon,+ createDiscountCode,+ disableDiscountCode,+ assertDiscountIntegrationAvailable,+ };+}++export const shopifyDiscountProvider = createShopifyDiscountProvider();diff --git a/apps/web/lib/discounts/discount-provider-stripe.ts b/apps/web/lib/discounts/discount-provider-stripe.tsnew file mode 100644index 0000000000..f96449dfc3--- /dev/null+++ b/apps/web/lib/discounts/discount-provider-stripe.ts@@ -0,0 +1,268 @@+import { prisma } from "@dub/prisma";+import { PartnerGroup, Project } from "@dub/prisma/client";+import { nanoid, STRIPE_INTEGRATION_ID, truncate } from "@dub/utils";+import * as z from "zod/v4";+import { DubApiError } from "../api/errors";+import { stripeIntegrationSettingsSchema } from "../integrations/stripe/schema";+import { stripeAppClient } from "../stripe";+import {+ dubDiscountToStripeCoupon,+ stripeCouponToDubDiscount,+ validateStripeCouponForDubDiscount,+} from "../stripe/coupon-discount-converter";+import { DiscountProps } from "../types";+import { createDiscountSchema } from "../zod/schemas/discount";+import { DiscountIntegrationNotAvailableError } from "./discount-error";++const MAX_ATTEMPTS = 3;++async function requireInstalledIntegration(+ workspace: Pick<Project, "id" | "stripeConnectId">,+) {+ 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.",+ });+ }++ const installation = await prisma.installedIntegration.findFirst({+ where: {+ projectId: workspace.id,+ integrationId: STRIPE_INTEGRATION_ID,+ },+ });++ 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.",+ });+ }++ const settings = stripeIntegrationSettingsSchema.parse(+ installation.settings || {},+ );++ return {+ ...installation,+ settings,+ };+}++function createStripeDiscountProvider() {+ const getCoupon = async ({+ couponId,+ workspace,+ }: {+ couponId: string;+ workspace: Project;+ }) => {+ const { settings } = await requireInstalledIntegration(workspace);++ const stripeApp = stripeAppClient({+ mode: settings.stripeMode,+ });++ try {+ const coupon = await stripeApp.coupons.retrieve(couponId, {+ stripeAccount: workspace.stripeConnectId!,+ });++ // Validate the Stripe coupon can be converted to a Dub discount+ const validation = validateStripeCouponForDubDiscount(coupon);+ if (!validation.isValid) {+ throw new Error(+ `Invalid Stripe coupon: ${validation.errors.join(", ")}`,+ );+ }++ return stripeCouponToDubDiscount(coupon);+ } catch (error) {+ throw new DubApiError({+ code: "bad_request",+ message:+ error.code === "more_permissions_required_for_application"+ ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."+ : error.code === "resource_missing"+ ? `The coupon ID you provided (${couponId}) was not found in your Stripe account. Please check the coupon ID and try again.`+ : error.message,+ });+ }+ };++ const createCoupon = async ({+ workspace,+ group,+ data,+ }: {+ workspace: Project;+ group: PartnerGroup;+ data: z.infer<typeof createDiscountSchema>;+ }) => {+ const { settings } = await requireInstalledIntegration(workspace);++ const stripeApp = stripeAppClient({+ mode: settings.stripeMode,+ });++ const stripeCouponData = dubDiscountToStripeCoupon({+ name: `Dub Discount (${truncate(group.name, 25)})`,+ amount: data.amount,+ type: data.type,+ maxDuration: data.maxDuration ?? null,+ });++ try {+ const coupon = await stripeApp.coupons.create(stripeCouponData, {+ stripeAccount: workspace.stripeConnectId!,+ });++ return stripeCouponToDubDiscount(coupon);+ } catch (error) {+ throw new DubApiError({+ code: "bad_request",+ message:+ error.code === "more_permissions_required_for_application"+ ? "STRIPE_APP_UPGRADE_REQUIRED: Your connected Stripe account doesn't have the permissions needed to create discount codes. Please upgrade your Stripe integration in settings or reach out to our support team for help."+ : error.message,+ });+ }+ };++ const createDiscountCode = async ({+ workspace,+ discount,+ code,+ shouldRetry = true,+ }: {+ workspace: Pick<Project, "id" | "stripeConnectId">;+ discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;+ code: string;+ shouldRetry?: boolean; // we don't retry if the code is provided by the user+ }) => {+ const { settings } = await requireInstalledIntegration(workspace);++ const stripeApp = stripeAppClient({+ mode: settings.stripeMode,+ });++ if (!discount.couponId) {+ throw new Error(`couponId not found for discount ${discount.id}.`);+ }++ let attempt = 0;+ let currentCode = code;++ while (attempt < MAX_ATTEMPTS) {+ try {+ return await stripeApp.promotionCodes.create(+ {+ coupon: discount.couponId,+ code: currentCode.toUpperCase(),+ restrictions: {+ first_time_transaction: true,+ },+ },+ {+ stripeAccount: workspace.stripeConnectId!,+ },+ );+ } catch (error: any) {+ const errorMessage = error.raw?.message || error.message;+ const isDuplicateError = errorMessage?.includes("already exists");++ if (!isDuplicateError) {+ throw error;+ }++ if (!shouldRetry) {+ throw error;+ }++ attempt++;++ if (attempt >= MAX_ATTEMPTS) {+ throw error;+ }++ const newCode = `${currentCode}${nanoid(2)}`;++ console.warn(+ `Discount code "${currentCode}" already exists. Retrying with "${newCode}" (attempt ${attempt}/${MAX_ATTEMPTS}).`,+ );++ currentCode = newCode;+ }+ }++ throw new Error("Failed to create Stripe discount code.");+ };++ const disableDiscountCode = async ({+ workspace,+ code,+ }: {+ workspace: Pick<Project, "id" | "stripeConnectId">;+ code: string;+ }) => {+ const { settings } = await requireInstalledIntegration(workspace);++ const stripeApp = stripeAppClient({+ mode: settings.stripeMode,+ });++ const promotionCodes = await stripeApp.promotionCodes.list(+ {+ code,+ limit: 1,+ },+ {+ stripeAccount: workspace.stripeConnectId!,+ },+ );++ if (promotionCodes.data.length === 0) {+ console.error(+ `Stripe promotion code ${code} not found (stripeConnectId=${workspace.stripeConnectId}).`,+ );+ return;+ }++ const promotionCode = promotionCodes.data[0];++ await stripeApp.promotionCodes.update(+ promotionCode.id,+ {+ active: false,+ },+ {+ stripeAccount: workspace.stripeConnectId!,+ },+ );++ console.info(+ `Disabled Stripe promotion code ${promotionCode.code} (id=${promotionCode.id}, stripeConnectId=${workspace.stripeConnectId}).`,+ );++ return promotionCode;+ };++ const assertDiscountIntegrationAvailable = async ({+ workspace,+ }: {+ workspace: Pick<Project, "id" | "stripeConnectId" | "shopifyStoreId">;+ }) => {+ await requireInstalledIntegration(workspace);+ };++ return {+ getCoupon,+ createCoupon,+ createDiscountCode,+ disableDiscountCode,+ assertDiscountIntegrationAvailable,+ };+}++export const stripeDiscountProvider = createStripeDiscountProvider();diff --git a/apps/web/lib/discounts/discount-provider.ts b/apps/web/lib/discounts/discount-provider.tsnew file mode 100644index 0000000000..8ad3755bbd--- /dev/null+++ b/apps/web/lib/discounts/discount-provider.ts@@ -0,0 +1,18 @@+import { DiscountProvider } from "@dub/prisma/client";+import { shopifyDiscountProvider } from "./discount-provider-shopify";+import { stripeDiscountProvider } from "./discount-provider-stripe";++const discountProviders = {+ stripe: stripeDiscountProvider,+ shopify: shopifyDiscountProvider,+} as const;++export function getDiscountProvider(name: DiscountProvider) {+ const provider = discountProviders[name];++ if (!provider) {+ throw new Error(`Unsupported provider: ${name}`);+ }++ return provider;+}diff --git a/apps/web/lib/api/discounts/generate-discount-code-for-partner.ts b/apps/web/lib/discounts/generate-discount-code-for-partner.tssimilarity index 69%rename from apps/web/lib/api/discounts/generate-discount-code-for-partner.tsrename to apps/web/lib/discounts/generate-discount-code-for-partner.tsindex 545c519216..e415687518 100644--- a/apps/web/lib/api/discounts/generate-discount-code-for-partner.ts+++ b/apps/web/lib/discounts/generate-discount-code-for-partner.ts@@ -1,7 +1,5 @@-import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";import { EnrolledPartnerProps } from "@/lib/types";import { prisma } from "@dub/prisma";-import { STRIPE_INTEGRATION_ID } from "@dub/utils";import { createDiscountCode } from "./create-discount-code";export async function generateDiscountCodeForPartner({@@ -39,29 +37,12 @@ export async function generateDiscountCodeForPartner({id: workspaceId,},select: {+ id: true,stripeConnectId: true,- installedIntegrations: {- where: {- integrationId: STRIPE_INTEGRATION_ID,- },- },+ shopifyStoreId: true,},});- if (!workspace.stripeConnectId) {- console.log("Workspace does not have stripeConnectId");- return;- }-- if (!workspace.installedIntegrations.length) {- console.log("Workspace does not have the Stripe integration installed");- return;- }-- const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- workspace.installedIntegrations[0].settings || {},- );-const partnerDefaultLink = await prisma.link.findFirst({where: {programId: group.programId,@@ -87,8 +68,7 @@ export async function generateDiscountCodeForPartner({try {await createDiscountCode({- stripeConnectId: workspace.stripeConnectId,- stripeMode: stripeIntegrationSettings.stripeMode,+ workspace,partner,link: partnerDefaultLink,discount: group.discount,diff --git a/apps/web/lib/api/discounts/is-discount-equivalent.ts b/apps/web/lib/discounts/is-discount-equivalent.tssimilarity index 100%rename from apps/web/lib/api/discounts/is-discount-equivalent.tsrename to apps/web/lib/discounts/is-discount-equivalent.tsdiff --git a/apps/web/lib/integrations/shopify/admin-graphql.ts b/apps/web/lib/integrations/shopify/admin-graphql.tsnew file mode 100644index 0000000000..c3bf1bbf88--- /dev/null+++ b/apps/web/lib/integrations/shopify/admin-graphql.ts@@ -0,0 +1,58 @@+const SHOPIFY_ADMIN_API_VERSION = "2025-04";++export class ShopifyAdminGraphqlError extends Error {+ constructor(+ public code: string,+ message: string,+ public userErrors?: unknown,+ ) {+ super(message);+ }+}++// TODO:+// Send the error to Axiom++export async function shopifyAdminGraphql<T>({+ shopifyStoreId,+ accessToken,+ query,+ variables,+}: {+ shopifyStoreId: string;+ accessToken: string;+ query: string;+ variables?: Record<string, unknown>;+}): Promise<T> {+ const response = await fetch(+ `https://${shopifyStoreId}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/graphql.json`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "X-Shopify-Access-Token": accessToken,+ },+ body: JSON.stringify({ query, variables }),+ signal: AbortSignal.timeout(15_000),+ },+ );++ if (!response.ok) {+ throw new ShopifyAdminGraphqlError(+ response.status === 401 ? "unauthorized" : "http_error",+ `Shopify Admin API error: ${response.status} ${response.statusText}`,+ );+ }++ const json = await response.json();++ if (json.errors?.length) {+ throw new ShopifyAdminGraphqlError(+ "graphql_error",+ json.errors[0].message,+ json.errors,+ );+ }++ return json.data as T;+}diff --git a/apps/web/lib/integrations/shopify/create-lead.ts b/apps/web/lib/integrations/shopify/create-lead.tsindex ef9a3da087..6baddb8eae 100644--- a/apps/web/lib/integrations/shopify/create-lead.ts+++ b/apps/web/lib/integrations/shopify/create-lead.ts@@ -48,6 +48,24 @@ export async function createShopifyLead({const { link_id: linkId, country, timestamp } = clickData;+ const partnerLink = await prisma.link.findUnique({+ where: {+ id: linkId,+ },+ select: {+ id: true,+ programId: true,+ partnerId: true,+ },+ });++ if (!partnerLink) {+ throw new DubApiError({+ code: "not_found",+ message: `Link not found for linkId: ${linkId}`,+ });+ }+// create customerconst customer = await prisma.customer.create({data: {@@ -56,6 +74,8 @@ export async function createShopifyLead({name,email,projectId: workspaceId,+ programId: partnerLink.programId,+ partnerId: partnerLink.partnerId,clickedAt: new Date(timestamp + "Z"),clickId,linkId,diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.tsindex c75fdf3d24..c7ed6f81d3 100644--- a/apps/web/lib/integrations/shopify/process-order.ts+++ b/apps/web/lib/integrations/shopify/process-order.ts@@ -1,7 +1,23 @@+import { createId } from "@/lib/api/create-id";import { handleAndReturnErrorResponse } from "@/lib/api/errors";-import { getLeadEvent } from "@/lib/tinybird";+import { includeTags } from "@/lib/api/links/include-tags";+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";+import { generateRandomName } from "@/lib/names";+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";+import { getLeadEvent, recordLead } from "@/lib/tinybird";+import { recordFakeClick } from "@/lib/tinybird/record-fake-click";+import { WorkspaceProps } from "@/lib/types";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";+import { transformLeadEventData } from "@/lib/webhook/transform";+import { prisma } from "@dub/prisma";+import { Link } from "@dub/prisma/client";+import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { createShopifyLead } from "./create-lead";import { createShopifySale } from "./create-sale";+import { orderSchema } from "./schema";// Process the order from Shopify webhookexport async function processOrder({@@ -59,3 +75,158 @@ export async function processOrder({return handleAndReturnErrorResponse(error);}}++export async function attributeViaDiscountCode({+ event,+ workspace,+ link,+}: {+ event: unknown;+ workspace: Pick<WorkspaceProps, "id" | "defaultProgramId" | "webhookEnabled">;+ link: Link;+}) {+ const { customer: orderCustomer, billing_address: billingAddress } =+ orderSchema.parse(event);++ // Record a fake click for this event+ const clickEvent = await recordFakeClick({+ link,+ customer: {+ continent: billingAddress?.country_code+ ? COUNTRIES_TO_CONTINENTS[billingAddress.country_code]+ : "Unknown",+ country: billingAddress?.country_code ?? "Unknown",+ region: billingAddress?.province ?? "Unknown",+ },+ });++ const customerId = createId({ prefix: "cus_" });++ const customer = await prisma.customer.create({+ data: {+ id: customerId,+ name: orderCustomer+ ? `${orderCustomer.first_name} ${orderCustomer.last_name}`.trim()+ : generateRandomName(),+ email: orderCustomer?.email,+ externalId: orderCustomer?.id?.toString() || customerId,+ linkId: clickEvent.link_id,+ clickId: clickEvent.click_id,+ clickedAt: new Date(clickEvent.timestamp + "Z"),+ country: billingAddress?.country_code,+ projectId: workspace.id,+ programId: link.programId,+ partnerId: link.partnerId,+ },+ });++ // Prepare the payload for the lead event+ const { timestamp, ...rest } = clickEvent;++ const leadEvent = {+ ...rest,+ workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id+ event_id: nanoid(16),+ event_name: "Checkout with discount code",+ customer_id: customer.id,+ metadata: "",+ };++ await recordLead(leadEvent);++ waitUntil(+ (async () => {+ const linkUpdated = await prisma.link.update({+ where: {+ id: link.id,+ },+ data: {+ leads: {+ increment: 1,+ },+ lastLeadAt: new Date(),+ },+ include: includeTags,+ });++ let createdCommission:+ | Awaited<ReturnType<typeof createPartnerCommission>>+ | undefined = undefined;++ if (link.programId && link.partnerId) {+ createdCommission = await createPartnerCommission({+ event: "lead",+ programId: link.programId,+ partnerId: link.partnerId,+ linkId: link.id,+ eventId: leadEvent.event_id,+ customerId: customer.id,+ quantity: 1,+ context: {+ customer: {+ country: customer.country,+ },+ },+ });++ await Promise.allSettled([+ executeWorkflows({+ trigger: "partnerMetricsUpdated",+ reason: "lead",+ identity: {+ workspaceId: workspace.id,+ programId: link.programId,+ partnerId: link.partnerId,+ },+ metrics: {+ current: {+ leads: 1,+ },+ },+ }),++ syncPartnerLinksStats({+ partnerId: link.partnerId,+ programId: link.programId,+ eventType: "lead",+ }),+ ]);+ }++ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...clickEvent,+ eventName: "Checkout with discount code",+ link: linkUpdated,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),+ }),++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...leadEvent,+ eventName: "Checkout with discount code",+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]);+ })(),+ );++ return {+ customer,+ leadEvent,+ };+}diff --git a/apps/web/lib/integrations/shopify/schema.ts b/apps/web/lib/integrations/shopify/schema.tsindex 37dc782010..cc7c985a5f 100644--- a/apps/web/lib/integrations/shopify/schema.ts+++ b/apps/web/lib/integrations/shopify/schema.ts@@ -19,4 +19,23 @@ export const orderSchema = z.object({}).describe("Amount in shop currency."),}),+ discount_codes: z.array(+ z.object({+ code: z.string().describe("The code of the discount."),+ }),+ ),+ billing_address: z+ .object({+ province: z.string().nullish(),+ country_code: z.string().nullish(),+ })+ .nullish(),+});++export const integrationCredentialsSchema = z.object({+ accessToken: z+ .string()+ .nullish()+ .describe("Encrypted access token for the Shopify store."),+ scope: z.string().nullish().describe("Scope of the Shopify store."),});diff --git a/apps/web/lib/stripe/coupon-discount-converter.ts b/apps/web/lib/stripe/coupon-discount-converter.tsindex 028078bbd7..5f03eb669d 100644--- a/apps/web/lib/stripe/coupon-discount-converter.ts+++ b/apps/web/lib/stripe/coupon-discount-converter.ts@@ -51,7 +51,7 @@ export function dubDiscountToStripeCoupon(*/export function stripeCouponToDubDiscount(stripeCoupon: Stripe.Coupon,-): DubDiscountAttributes {+): DubDiscountAttributes & { id: string } {// Determine discount type and amountconst type: RewardStructure = stripeCoupon.percent_off? "percentage"@@ -74,6 +74,7 @@ export function stripeCouponToDubDiscount(}return {+ id: stripeCoupon.id,amount,type,maxDuration,diff --git a/apps/web/lib/stripe/create-stripe-discount-code.ts b/apps/web/lib/stripe/create-stripe-discount-code.tsdeleted file mode 100644index e9562ce414..0000000000--- a/apps/web/lib/stripe/create-stripe-discount-code.ts+++ /dev/null@@ -1,80 +0,0 @@-import { nanoid } from "@dub/utils";-import { stripeAppClient } from ".";-import { DiscountProps, StripeMode } from "../types";--const MAX_ATTEMPTS = 3;--export async function createStripeDiscountCode({- stripeConnectId,- stripeMode,- discount,- code,- shouldRetry = true,-}: {- stripeConnectId: string;- stripeMode: StripeMode;- discount: Pick<DiscountProps, "id" | "couponId" | "amount" | "type">;- code: string;- shouldRetry?: boolean; // we don't retry if the code is provided by the user-}) {- if (!stripeConnectId) {- throw new Error(- `stripeConnectId is required to create a Stripe discount code.`,- );- }-- const stripe = stripeAppClient({- mode: stripeMode,- });-- if (!discount.couponId) {- throw new Error(`couponId not found for discount ${discount.id}.`);- }-- let attempt = 0;- let currentCode = code;-- while (attempt < MAX_ATTEMPTS) {- try {- return await stripe.promotionCodes.create(- {- coupon: discount.couponId,- code: currentCode.toUpperCase(),- restrictions: {- first_time_transaction: true,- },- },- {- stripeAccount: stripeConnectId,- },- );- } catch (error: any) {- const errorMessage = error.raw?.message || error.message;- const isDuplicateError = errorMessage?.includes("already exists");-- if (!isDuplicateError) {- throw error;- }-- if (!shouldRetry) {- throw error;- }-- attempt++;-- if (attempt >= MAX_ATTEMPTS) {- throw error;- }-- const newCode = `${currentCode}${nanoid(2)}`;-- console.warn(- `Discount code "${currentCode}" already exists. Retrying with "${newCode}" (attempt ${attempt}/${MAX_ATTEMPTS}).`,- );-- currentCode = newCode;- }- }-- throw new Error("Failed to create Stripe discount code.");-}diff --git a/apps/web/lib/stripe/disable-stripe-discount-code.ts b/apps/web/lib/stripe/disable-stripe-discount-code.tsdeleted file mode 100644index b75acee615..0000000000--- a/apps/web/lib/stripe/disable-stripe-discount-code.ts+++ /dev/null@@ -1,51 +0,0 @@-import { stripeAppClient } from ".";-import { StripeMode } from "../types";--export async function disableStripeDiscountCode({- stripeConnectId,- stripeMode,- code,-}: {- stripeConnectId: string;- stripeMode: StripeMode;- code: string;-}) {- const stripe = stripeAppClient({- mode: stripeMode,- });-- const promotionCodes = await stripe.promotionCodes.list(- {- code,- limit: 1,- },- {- stripeAccount: stripeConnectId,- },- );-- if (promotionCodes.data.length === 0) {- console.error(- `Stripe promotion code ${code} not found (stripeConnectId=${stripeConnectId}).`,- );- return;- }-- let promotionCode = promotionCodes.data[0];-- promotionCode = await stripe.promotionCodes.update(- promotionCode.id,- {- active: false,- },- {- stripeAccount: stripeConnectId,- },- );-- console.info(- `Disabled Stripe promotion code ${promotionCode.code} (id=${promotionCode.id}, stripeConnectId=${stripeConnectId}).`,- );-- return promotionCode;-}diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 36ac2b377a..3c859eb231 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -197,6 +197,7 @@ export const CustomerEnrichedSchema = CustomerSchema.extend({}).nullish(),discount: DiscountSchema.omit({autoProvisionEnabledAt: true,+ provider: true,}).nullish(),});diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.tsindex 779639dffa..34cb5f0322 100644--- a/apps/web/lib/zod/schemas/discount.ts+++ b/apps/web/lib/zod/schemas/discount.ts@@ -1,4 +1,4 @@-import { RewardStructure } from "@dub/prisma/client";+import { DiscountProvider, RewardStructure } from "@dub/prisma/client";import * as z from "zod/v4";import { getPaginationQuerySchema, maxDurationSchema } from "./misc";@@ -12,10 +12,12 @@ export const DiscountSchema = z.object({description: z.string().nullish(),partnersCount: z.number().nullish(),autoProvisionEnabledAt: z.coerce.date().nullish(),+ provider: z.enum(DiscountProvider),});export const DiscountSchemaWithDeprecatedFields = DiscountSchema.omit({autoProvisionEnabledAt: true,+ provider: true,}).extend({duration: z@@ -35,6 +37,7 @@ export const createDiscountSchema = z.object({couponTestId: z.string().nullish(),groupId: z.string(),autoProvision: z.boolean().optional(),+ provider: z.enum(DiscountProvider),});export const updateDiscountSchema = createDiscountSchemadiff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.tsindex 110e79e3d5..dae29c1a69 100644--- a/apps/web/lib/zod/schemas/partners.ts+++ b/apps/web/lib/zod/schemas/partners.ts@@ -17,6 +17,7 @@ import { COUNTRY_CODES } from "@dub/utils";import * as z from "zod/v4";import { analyticsQuerySchema } from "./analytics";import { analyticsResponse } from "./analytics-response";+import { DiscountSchema } from "./discount";import {base64ImageSchema,googleFaviconUrlSchema,@@ -573,6 +574,10 @@ export const EnrolledPartnerSchemaExtended = EnrolledPartnerSchema.extend({customerDataSharingEnabledAt: z.date().nullish(),groupMoveDisabledAt: z.date().nullish(),platforms: z.array(partnerPlatformSchema).nullable(),+ discount: DiscountSchema.pick({+ id: true,+ provider: true,+ }).nullish(),}).extend(PartnerSchema.pick({diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.tsindex 98a927fa7d..f1fbccb4c2 100644--- a/apps/web/lib/zod/schemas/workspaces.ts+++ b/apps/web/lib/zod/schemas/workspaces.ts@@ -226,6 +226,7 @@ export const WorkspaceSchemaExtended = WorkspaceSchema.extend({),publishableKey: z.string().nullable(),fastDirectDebitPayouts: z.boolean().default(false),+ shopifyStoreId: z.string().nullable(),});export const OnboardingUsageSchema = z.object({diff --git a/apps/web/scripts/dev/simulate-shopify-webhook.ts b/apps/web/scripts/dev/simulate-shopify-webhook.tsnew file mode 100644index 0000000000..85d233beb3--- /dev/null+++ b/apps/web/scripts/dev/simulate-shopify-webhook.ts@@ -0,0 +1,48 @@+import "dotenv-flow/config";++import { orderSchema } from "@/lib/integrations/shopify/schema";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";++async function main() {+ const event = orderSchema.parse({+ confirmation_number: "WDQ0YHYU32",+ checkout_token: "20585787a5a40274b6b34511d2f637e92",+ customer: {+ id: 97773681707702,+ first_name: "John",+ last_name: "Doe",+ email: "[email protected]",+ },+ current_subtotal_price_set: {+ shop_money: {+ amount: "22.50",+ currency_code: "USD",+ },+ },+ discount_codes: [+ {+ code: "D1",+ },+ ],+ billing_address: {+ province: "California",+ country_code: "US",+ },+ });++ const response = await fetch(+ `${APP_DOMAIN_WITH_NGROK}/api/shopify/integration/webhook`,+ {+ method: "POST",+ body: JSON.stringify(event),+ headers: {+ "x-shopify-topic": "orders/paid",+ "x-shopify-shop-domain": "dub-conversions.myshopify.com",+ },+ },+ );++ console.log(response.ok);+}++main();diff --git a/apps/web/ui/modals/add-discount-code-modal.tsx b/apps/web/ui/modals/add-discount-code-modal.tsxindex f8d753a0cc..5c361cd8c8 100644--- a/apps/web/ui/modals/add-discount-code-modal.tsx+++ b/apps/web/ui/modals/add-discount-code-modal.tsx@@ -17,7 +17,7 @@ import { useForm } from "react-hook-form";import { toast } from "sonner";import { useDebounce } from "use-debounce";import * as z from "zod/v4";-import { STRIPE_ERROR_MAP } from "../partners/constants";+import { ERROR_MAP } from "../partners/constants";import { X } from "../shared/icons";import { UpgradeRequiredToast } from "../shared/upgrade-required-toast";@@ -88,12 +88,12 @@ const AddDiscountCodeModal = ({},onError: (error) => {if (error) {- const code = Object.keys(STRIPE_ERROR_MAP).find((key) =>+ const code = Object.keys(ERROR_MAP).find((key) =>error.startsWith(key),);if (code) {- const { title, ctaLabel, ctaUrl } = STRIPE_ERROR_MAP[code];+ const { title, ctaLabel, ctaUrl } = ERROR_MAP[code];const message = error.replace(`${code}: `, "");toast.custom(() => (diff --git a/apps/web/ui/partners/constants.ts b/apps/web/ui/partners/constants.tsindex 495f4d916c..26959045ba 100644--- a/apps/web/ui/partners/constants.ts+++ b/apps/web/ui/partners/constants.ts@@ -24,7 +24,7 @@ export const REWARD_EVENTS = {},} as const;-export const STRIPE_ERROR_MAP: Record<+export const ERROR_MAP: Record<string,{ title: string; ctaLabel: string; ctaUrl: string }> = {@@ -38,4 +38,14 @@ export const STRIPE_ERROR_MAP: Record<ctaLabel: "Review permissions",ctaUrl: "https://marketplace.stripe.com/apps/dub-conversions",},+ SHOPIFY_CONNECTION_REQUIRED: {+ title: "Shopify connection required",+ ctaLabel: "Install Shopify app",+ ctaUrl: "https://apps.shopify.com/dub-conversion-tracking",+ },+ SHOPIFY_APP_UPGRADE_REQUIRED: {+ title: "Shopify app upgrade required",+ ctaLabel: "Review permissions",+ ctaUrl: "https://apps.shopify.com/dub-conversion-tracking",+ },};diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsxindex 50b72a6303..22b0d14c33 100644--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx@@ -17,11 +17,13 @@ import {InlineBadgePopoverMenu,} from "@/ui/shared/inline-badge-popover";import { UpgradeRequiredToast } from "@/ui/shared/upgrade-required-toast";+import { DiscountProvider } from "@dub/prisma/client";import { Button, InfoTooltip, Sheet, Switch } from "@dub/ui";import { CircleCheckFill, StripeIcon, Tag } from "@dub/ui/icons";import { capitalize, cn, pluralize } from "@dub/utils";import { useAction } from "next-safe-action/hooks";import {+ ChangeEvent,Dispatch,PropsWithChildren,ReactNode,@@ -33,7 +35,7 @@ import { FormProvider, useForm, useFormContext } from "react-hook-form";import { toast } from "sonner";import { mutate } from "swr";import * as z from "zod/v4";-import { STRIPE_ERROR_MAP } from "../constants";+import { ERROR_MAP } from "../constants";import { RewardDiscountPartnersCard } from "../groups/reward-discount-partners-card";interface DiscountSheetProps {@@ -59,6 +61,8 @@ const COUPON_CREATION_OPTIONS = [},] as const;+const DEFAULT_MAX_DURATION = 6;+function DiscountSheetContent({setIsOpen,discount,@@ -76,11 +80,16 @@ function DiscountSheetContent({Boolean(discount?.couponTestId),);+ const discountProvider =+ discount?.provider ??+ defaultDiscountValues?.provider ??+ DiscountProvider.stripe;+const defaultValuesSource = discount ||defaultDiscountValues || {amount: 10,type: "percentage",- maxDuration: 6,+ maxDuration: DEFAULT_MAX_DURATION,couponId: "",couponTestId: "",autoProvisionEnabledAt: null,@@ -94,21 +103,25 @@ function DiscountSheetContent({: defaultValuesSource.amount,type: defaultValuesSource.type,maxDuration:- defaultValuesSource.maxDuration === null- ? Infinity- : defaultValuesSource.maxDuration,+ discountProvider === DiscountProvider.shopify+ ? 0+ : defaultValuesSource.maxDuration === null+ ? Infinity+ : defaultValuesSource.maxDuration,couponId: defaultValuesSource.couponId || "",couponTestId: defaultValuesSource.couponTestId,autoProvision: Boolean(defaultValuesSource.autoProvisionEnabledAt),+ provider: discountProvider,},});const { handleSubmit, watch, setValue, register } = form;- const [type, amount, maxDuration, autoProvision] = watch([+ const [type, amount, maxDuration, autoProvision, provider] = watch(["type","amount","maxDuration","autoProvision",+ "provider",]);const { executeAsync: createDiscount, isPending: isCreating } = useAction(@@ -122,12 +135,12 @@ function DiscountSheetContent({},onError({ error }) {if (error.serverError) {- const code = Object.keys(STRIPE_ERROR_MAP).find((key) =>+ const code = Object.keys(ERROR_MAP).find((key) =>error.serverError!.startsWith(key),);if (code) {- const { title, ctaLabel, ctaUrl } = STRIPE_ERROR_MAP[code];+ const { title, ctaLabel, ctaUrl } = ERROR_MAP[code];const message = error.serverError!.replace(`${code}: `, "");toast.custom(() => (@@ -251,17 +264,55 @@ function DiscountSheetContent({<div className="border-border-subtle -mx-px rounded-xl border-x border-t bg-neutral-100 p-2.5"><div className="space-y-4"><div className="flex flex-col gap-2">- <label className="text-content-emphasis text-sm font-medium">- Payment provider+ <label+ htmlFor="provider"+ className="text-content-emphasis text-sm font-medium"+ >+ Discount provider</label><div className="">- <select className="block w-full rounded-md border-neutral-300 px-3 py-2 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500">- <option value="stripe">Stripe</option>+ <select+ className="block w-full rounded-md border-neutral-300 px-3 py-2 text-sm text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 disabled:cursor-not-allowed disabled:bg-neutral-50"+ {...(() => {+ const { onChange: onProviderChange, ...rest } =+ register("provider", {+ disabled: Boolean(discount),+ });++ return {+ ...rest,+ onChange: (e: ChangeEvent<HTMLSelectElement>) => {+ onProviderChange(e);+ if (e.target.value === DiscountProvider.shopify) {+ setUseExistingCoupon(false);+ setUseStripeTestCouponId(false);+ setValue("couponId", "");+ setValue("couponTestId", "");+ setValue("maxDuration", 0);+ } else {+ setUseExistingCoupon(false);+ setUseStripeTestCouponId(false);+ setValue(+ "maxDuration",+ defaultValuesSource.maxDuration === null+ ? Infinity+ : defaultValuesSource.maxDuration,+ );+ }+ },+ };+ })()}+ id="provider"+ >+ <option value={DiscountProvider.stripe}>Stripe</option>+ <option value={DiscountProvider.shopify}>+ Shopify+ </option></select></div></div>- {!discount && (+ {!discount && provider === DiscountProvider.stripe && (<div className="grid grid-cols-1 gap-3 lg:grid-cols-2">{COUPON_CREATION_OPTIONS.map(({ label, description, useExisting }) => {@@ -305,72 +356,73 @@ function DiscountSheetContent({</div>)}- {(useExistingCoupon || discount) && (- <>- <div>- <label- htmlFor="couponId"- className="flex items-center space-x-2"- >- <h2 className="text-sm font-medium text-neutral-900">- Stripe coupon ID- </h2>- </label>- <div className="mt-2">- <input- type="text"- id="couponId"- className="border-border-subtle block w-full rounded-lg bg-white px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"- {...register("couponId")}- placeholder="XZuejd0Q"- disabled={!!discount} // we don't allow updating the coupon ID for existing discounts- />- </div>- </div>-- <div className="flex items-center gap-3">- <Switch- fn={() => {- setUseStripeTestCouponId(!useStripeTestCouponId);- setValue("couponTestId", "");- }}- checked={useStripeTestCouponId}- trackDimensions="w-8 h-4"- thumbDimensions="w-3 h-3"- thumbTranslate="translate-x-4"- />- <div className="flex items-center gap-2">- <h3 className="text-sm font-medium text-neutral-800">- Use Stripe test coupon ID- </h3>-- <InfoTooltip content="Enabling this will allow you to test your coupon code before going live by entering your Stripe test coupon ID." />- </div>- </div>-- {useStripeTestCouponId && (+ {(useExistingCoupon || discount) &&+ provider === DiscountProvider.stripe && (+ <><div><label- htmlFor="couponTestId"+ htmlFor="couponId"className="flex items-center space-x-2"><h2 className="text-sm font-medium text-neutral-900">- Stripe test coupon ID+ Stripe coupon ID</h2></label><div className="mt-2"><inputtype="text"- id="couponTestId"- className="border-border-subtle block w-full rounded-lg px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"- {...register("couponTestId")}- placeholder="2NMXz81x"+ id="couponId"+ className="border-border-subtle block w-full rounded-lg bg-white px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ {...register("couponId")}+ placeholder="XZuejd0Q"+ disabled={!!discount} // we don't allow updating the coupon ID for existing discounts/></div></div>- )}- </>- )}++ <div className="flex items-center gap-3">+ <Switch+ fn={() => {+ setUseStripeTestCouponId(!useStripeTestCouponId);+ setValue("couponTestId", "");+ }}+ checked={useStripeTestCouponId}+ trackDimensions="w-8 h-4"+ thumbDimensions="w-3 h-3"+ thumbTranslate="translate-x-4"+ />+ <div className="flex items-center gap-2">+ <h3 className="text-sm font-medium text-neutral-800">+ Use Stripe test coupon ID+ </h3>++ <InfoTooltip content="Enabling this will allow you to test your coupon code before going live by entering your Stripe test coupon ID." />+ </div>+ </div>++ {useStripeTestCouponId && (+ <div>+ <label+ htmlFor="couponTestId"+ className="flex items-center space-x-2"+ >+ <h2 className="text-sm font-medium text-neutral-900">+ Stripe test coupon ID+ </h2>+ </label>+ <div className="mt-2">+ <input+ type="text"+ id="couponTestId"+ className="border-border-subtle block w-full rounded-lg px-3 py-2 text-neutral-800 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm"+ {...register("couponTestId")}+ placeholder="2NMXz81x"+ />+ </div>+ </div>+ )}+ </>+ )}</div></div>}@@ -447,16 +499,20 @@ function DiscountSheetContent({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",- },+ ...(provider === DiscountProvider.shopify+ ? []+ : [+ ...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",+ },+ ]),]}/></InlineBadgePopover>diff --git a/packages/prisma/client.ts b/packages/prisma/client.tsindex ccfb957cf3..b487f5b27e 100644--- a/packages/prisma/client.ts+++ b/packages/prisma/client.ts@@ -10,6 +10,7 @@ export {CampaignType,CommissionStatus,CommissionType,+ DiscountProvider,EmailDomainStatus,EventType,FolderType,@@ -25,9 +26,9 @@ export {PartnerLinkStructure,PartnerProfileType,PartnerRole,- PlanPeriod,PayoutMode,PayoutStatus,+ PlanPeriod,PlatformType,PreferredEarningStructure,Prisma,diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prismaindex 05d9a6089c..07deddad5b 100644--- a/packages/prisma/schema/discount.prisma+++ b/packages/prisma/schema/discount.prisma@@ -1,15 +1,21 @@+enum DiscountProvider {+ stripe+ shopify+}+model Discount {- id String @id @default(cuid())+ id String @id @default(cuid())programId String- amount Int @default(0)- type RewardStructure @default(percentage)+ amount Int @default(0)+ type RewardStructure @default(percentage)maxDuration Int? // in months (0 -> one-time purchase, 1, 3, 6, 12, 18, 24, 36, 48 -> months, null -> lifetime)description String?couponId String?couponTestId String?autoProvisionEnabledAt DateTime? // Auto create discount codes for partners when they join the group- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ provider DiscountProvider @default(stripe)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAtprogramEnrollments ProgramEnrollment[]program Program @relation("ProgramDiscounts", fields: [programId], references: [id])