The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Refactor promotion code creation to use partner group ID instead of discount ID, and update related error handling and logging messages.
Kiran Keec3829bdd9f
diff --git a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.tsindex 02c9869acd..3e77edfb00 100644--- a/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts+++ b/apps/web/app/(ee)/api/cron/links/create-promotion-codes/route.ts@@ -9,7 +9,7 @@ import { logAndRespond } from "../../utils";export const dynamic = "force-dynamic";const schema = z.object({- discountId: z.string(),+ groupId: z.string(),});// POST /api/cron/links/create-promotion-codes@@ -18,49 +18,51 @@ export async function POST(req: Request) {const rawBody = await req.text();await verifyQstashSignature({ req, rawBody });- const { discountId } = schema.parse(JSON.parse(rawBody));+ const { groupId } = schema.parse(JSON.parse(rawBody));- const discount = await prisma.discount.findUnique({+ const group = await prisma.partnerGroup.findUnique({where: {- id: discountId,+ id: groupId,},include: {- partnerGroup: true,program: true,+ discount: true,},});- if (!discount) {+ if (!group) {return logAndRespond({- message: `Discount ${discountId} not found.`,+ message: `Partner group ${groupId} not found.`,logLevel: "error",});}- if (!discount.couponId) {+ const { discount, program } = group;++ if (!discount) {return logAndRespond({- message: `Discount ${discountId} does not have a couponId set.`,+ message: `Partner group ${groupId} does not have a discount.`,logLevel: "error",});}- if (!discount.couponCodeTrackingEnabledAt) {+ if (!discount.couponId) {return logAndRespond({- message: `Discount ${discountId} is not enabled for coupon code tracking.`,+ message: `Discount ${discount.id} does not have a couponId set.`,+ logLevel: "error",});}- if (!discount.partnerGroup) {+ if (!discount.couponCodeTrackingEnabledAt) {return logAndRespond({- message: `Discount ${discountId} is not associated with a partner group.`,- logLevel: "error",+ message: `Discount ${discount.id} is not enabled for coupon code tracking.`,});}// Find the workspace for the programconst workspace = await prisma.project.findUnique({where: {- id: discount.program.workspaceId,+ id: program.workspaceId,},select: {stripeConnectId: true,@@ -69,14 +71,14 @@ export async function POST(req: Request) {if (!workspace) {return logAndRespond({- message: `Workspace ${discount.program.workspaceId} not found.`,+ message: `Workspace ${program.workspaceId} not found.`,logLevel: "error",});}if (!workspace.stripeConnectId) {return logAndRespond({- message: `Workspace ${discount.program.workspaceId} does not have a stripeConnectId set.`,+ message: `Workspace ${program.workspaceId} does not have a stripeConnectId set.`,logLevel: "error",});}@@ -89,7 +91,7 @@ export async function POST(req: Request) {// Find all enrollments for the partner groupconst enrollments = await prisma.programEnrollment.findMany({where: {- groupId: discount.partnerGroup.id,+ groupId: group.id,},orderBy: {id: "desc",@@ -106,7 +108,7 @@ export async function POST(req: Request) {// Find all links for the enrollmentsconst links = await prisma.link.findMany({where: {- programId: discount.programId,+ programId: program.id,partnerId: {in: enrollments.map(({ partnerId }) => partnerId),},@@ -155,7 +157,7 @@ export async function POST(req: Request) {}return logAndRespond({- message: `Promotion codes created for discount ${discountId}.`,+ message: `Promotion codes created for discount ${discount.id} in group ${groupId}.`,});} catch (error) {console.log(error);diff --git a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.tsindex ae5db84003..2a3fc5f3d1 100644--- a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts+++ b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts@@ -4,6 +4,7 @@ import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@dub/prisma";import { chunk } from "@dub/utils";import { z } from "zod";+import { logAndRespond } from "../../utils";export const dynamic = "force-dynamic";@@ -34,8 +35,10 @@ export async function POST(req: Request) {});if (!group) {- console.error(`Group ${groupId} not found.`);- return new Response("OK");+ return logAndRespond({+ message: `Group ${groupId} not found.`,+ logLevel: "error",+ });}// Find all the links of the partners in the group@@ -59,30 +62,30 @@ export async function POST(req: Request) {});if (programEnrollments.length === 0) {- console.log(`No program enrollments found for group ${groupId}.`);- return new Response("OK");+ return logAndRespond({+ message: `No program enrollments found for group ${groupId}.`,+ });}const links = programEnrollments.flatMap((enrollment) => enrollment.links);if (links.length === 0) {- console.log(`No links found for partners in the group ${groupId}.`);- return new Response("OK");+ return logAndRespond({+ message: `No links found for partners in the group ${groupId}.`,+ });}- console.log(`Found ${links.length} links to invalidate the cache for.`);-const linkChunks = chunk(links, 100);// Expire the cache for the linksfor (const linkChunk of linkChunks) {const toExpire = linkChunk.map(({ domain, key }) => ({ domain, key }));await linkCache.expireMany(toExpire);- console.log(toExpire);- console.log(`Expired cache for ${toExpire.length} links.`);}- return new Response("OK");+ return logAndRespond({+ message: `Expired cache for ${links.length} links.`,+ });} catch (error) {return handleAndReturnErrorResponse(error);}diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.tsindex d4abf2499e..51f81c1de5 100644--- a/apps/web/lib/actions/partners/create-discount.ts+++ b/apps/web/lib/actions/partners/create-discount.ts@@ -77,7 +77,7 @@ export const createDiscountAction = authActionClienttype,maxDuration,couponId,- couponTestId,+ ...(couponTestId && { couponTestId }),...(enableCouponTracking && {couponCodeTrackingEnabledAt: new Date(),}),@@ -119,7 +119,7 @@ export const createDiscountAction = authActionClientqstash.publishJSON({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,body: {- discountId: discount.id,+ groupId,},}),diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.tsindex a4dc7c585f..d3f31f0a1d 100644--- a/apps/web/lib/actions/partners/update-discount.ts+++ b/apps/web/lib/actions/partners/update-discount.ts@@ -10,16 +10,11 @@ import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { authActionClient } from "../safe-action";-// TODO:-// Allow updating couponCodeTrackingEnabledAt-// If couponCodeTrackingEnabledAt is set to true, create promotion codes for all links in the group-// If couponCodeTrackingEnabledAt is set to false, remove promotion codes for all links in the group-export const updateDiscountAction = authActionClient.schema(updateDiscountSchema).action(async ({ parsedInput, ctx }) => {const { workspace, user } = ctx;- let { discountId, couponId, couponTestId } = parsedInput;+ let { discountId, enableCouponTracking, couponTestId } = parsedInput;const programId = getDefaultProgramIdOrThrow(workspace);@@ -33,8 +28,8 @@ export const updateDiscountAction = authActionClientid: discountId,},data: {- couponId,- couponTestId,+ couponTestId: couponTestId || null,+ couponCodeTrackingEnabledAt: enableCouponTracking ? new Date() : null,},include: {partnerGroup: {@@ -45,13 +40,23 @@ export const updateDiscountAction = authActionClient},});- const discountChanged =- discount.couponId !== updatedDiscount.couponId ||+ const couponTestIdChanged =discount.couponTestId !== updatedDiscount.couponTestId;+ const trackingEnabledChanged =+ discount.couponCodeTrackingEnabledAt !==+ updatedDiscount.couponCodeTrackingEnabledAt;++ const shouldCreatePromotionCodes =+ discount.couponCodeTrackingEnabledAt === null &&+ updatedDiscount.couponCodeTrackingEnabledAt !== null;- if (discountChanged) {- waitUntil(- Promise.allSettled([+ const shouldDeletePromotionCodes =+ discount.couponCodeTrackingEnabledAt !== null &&+ updatedDiscount.couponCodeTrackingEnabledAt === null;++ waitUntil(+ Promise.allSettled([+ couponTestIdChanged &&qstash.publishJSON({url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,body: {@@ -59,6 +64,23 @@ export const updateDiscountAction = authActionClient},}),+ shouldCreatePromotionCodes &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/create-promotion-codes`,+ body: {+ groupId: partnerGroup?.id,+ },+ }),++ shouldDeletePromotionCodes &&+ qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/delete-promotion-codes`,+ body: {+ groupId: partnerGroup?.id,+ },+ }),++ (couponTestIdChanged || trackingEnabledChanged) &&recordAuditLog({workspaceId: workspace.id,programId,@@ -73,7 +95,6 @@ export const updateDiscountAction = authActionClient},],}),- ]),- );- }+ ]),+ );});diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.tsindex 8ed393fabf..01231963a0 100644--- a/apps/web/lib/zod/schemas/discount.ts+++ b/apps/web/lib/zod/schemas/discount.ts@@ -36,8 +36,8 @@ export const createDiscountSchema = z.object({export const updateDiscountSchema = createDiscountSchema.pick({workspaceId: true,- couponId: true,couponTestId: true,+ enableCouponTracking: true,}).extend({discountId: z.string(),diff --git a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsxindex fce5323b23..97845c5764 100644--- a/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx+++ b/apps/web/ui/partners/discounts/add-edit-discount-sheet.tsx@@ -162,23 +162,23 @@ function DiscountSheetContent({return;}- if (!discount) {- await createDiscount({- ...data,+ if (discount) {+ await updateDiscount({workspaceId,- groupId: group.id,- amount: data.type === "flat" ? data.amount * 100 : data.amount || 0,- maxDuration:- Number(data.maxDuration) === Infinity ? null : data.maxDuration,+ discountId: discount.id,+ couponTestId: data.couponTestId,+ enableCouponTracking: data.enableCouponTracking,});return;}- await updateDiscount({+ await createDiscount({+ ...data,workspaceId,- discountId: discount.id,- couponId: data.couponId,- couponTestId: data.couponTestId,+ groupId: group.id,+ amount: data.type === "flat" ? data.amount * 100 : data.amount || 0,+ maxDuration:+ Number(data.maxDuration) === Infinity ? null : data.maxDuration,});};@@ -303,6 +303,7 @@ function DiscountSheetContent({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>@@ -355,37 +356,35 @@ function DiscountSheetContent({</>)}- {!discount && (- <div className="flex items-center gap-3">- <Switch- fn={() =>- setValue(- "enableCouponTracking",- !watch("enableCouponTracking"),- )+ <div className="flex items-center gap-3">+ <Switch+ fn={() =>+ setValue(+ "enableCouponTracking",+ !watch("enableCouponTracking"),+ )+ }+ checked={watch("enableCouponTracking")}+ 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">+ Enable automatic coupon code tracking+ </h3>++ <InfoTooltip+ content={+ <SimpleTooltipContent+ title="Enabling this will allow the partners to create a promo code for their links."+ href="https://dub.co/help/article/coupon-codes-tracking"+ cta="Learn more"+ />}- checked={watch("enableCouponTracking")}- 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">- Enable automatic coupon code tracking- </h3>-- <InfoTooltip- content={- <SimpleTooltipContent- title="Enabling this will allow the partners to create a promo code for their links."- href="https://dub.co/help/article/coupon-codes-tracking"- cta="Learn more"- />- }- />- </div></div>- )}+ </div></div></div>}