Skip to content

armgit / dub

Public Imported from GitHub
0

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

simplify

Steven Tey3838bd26c617
diff --git a/apps/web/lib/rewardful/import-affiliate-coupons.ts b/apps/web/lib/rewardful/import-affiliate-coupons.ts
index 67c0262a9d..cd8751d23f 100644
--- a/apps/web/lib/rewardful/import-affiliate-coupons.ts
+++ b/apps/web/lib/rewardful/import-affiliate-coupons.ts
@@ -1,5 +1,4 @@
import { prisma } from "@/lib/prisma";
-import { nanoid } from "@dub/utils";
import { createId } from "../api/create-id";
import { bulkCreateLinks } from "../api/links";
import { ProcessedLinkProps } from "../types";
@@ -64,101 +63,46 @@ export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
(affiliateCoupon) => filteredPartners[affiliateCoupon.affiliate_id],
);
- const existingDiscountCodes = await prisma.discountCode.findMany({
- where: {
- programId,
- code: {
- in: filteredCoupons.map((coupon) => coupon.token),
- },
- },
- select: {
- code: true,
- },
- });
-
- const existingDiscountCodeSet = new Set(
- existingDiscountCodes.map((discountCode) =>
- discountCode.code.toLowerCase(),
- ),
- );
-
- // Skip coupons that already have a discount code, AND dedupe repeated tokens
- // within this batch — two coupons sharing a token can't both own the same
- // (programId, code), and keeping both would overwrite the link mapping and
- // leave an orphan link.
- const seenTokens = new Set<string>();
- const couponsToImport = filteredCoupons.filter((coupon) => {
- const normalizedToken = coupon.token.toLowerCase();
-
- if (
- existingDiscountCodeSet.has(normalizedToken) ||
- seenTokens.has(normalizedToken)
- ) {
- return false;
- }
-
- seenTokens.add(normalizedToken);
- return true;
- });
+ const affiliateIdToCouponsMap = filteredCoupons.reduce(
+ (acc, coupon) => {
+ if (!acc[coupon.affiliate_id]) {
+ acc[coupon.affiliate_id] = [];
+ }
- // A coupon's link MUST be owned by the coupon's partner. But affiliate link
- // tokens (created in import-partners) and coupon tokens share the same
- // Link.key namespace (unique per domain), so a coupon token can collide with
- // a link that already belongs to a *different* partner. Reusing that link
- // would attribute the coupon's sales to the wrong partner (the link owner),
- // so we detect collisions and create a fresh, uniquely-keyed link owned by
- // the coupon's partner instead.
- const existingLinks =
- couponsToImport.length > 0
- ? await prisma.link.findMany({
- where: {
- domain: program.domain!,
- key: {
- in: couponsToImport.map((coupon) => coupon.token),
- },
- },
- select: {
- key: true,
- },
- })
- : [];
+ acc[coupon.affiliate_id].push(coupon);
+ return acc;
+ },
- const takenKeys = new Set(
- existingLinks.map((link) => link.key.toLowerCase()),
+ {} as Record<string, typeof filteredCoupons>,
);
- // map each coupon token to the (possibly fallback) key assigned to its link
- const couponTokenToLinkKey = new Map<string, string>();
const linksToCreate: Partial<ProcessedLinkProps>[] = [];
- for (const coupon of couponsToImport) {
- const { partnerId } = filteredPartners[coupon.affiliate_id];
-
- if (!partnerId) {
- continue;
+ if (Object.keys(affiliateIdToCouponsMap).length > 0) {
+ for (const [affiliateId, coupons] of Object.entries(
+ affiliateIdToCouponsMap,
+ )) {
+ const { partnerId } = filteredPartners[affiliateId];
+
+ if (!partnerId) {
+ continue;
+ }
+
+ linksToCreate.push(
+ ...coupons.map((coupon) => ({
+ domain: program.domain!,
+ key: `${coupon.token}-coupon`,
+ url: program.url!,
+ trackConversion: true,
+ programId,
+ partnerId,
+ folderId: program.defaultFolderId,
+ userId,
+ projectId: program.workspaceId,
+ comments: `Link created for Rewardful coupon "${coupon.token}"`,
+ })),
+ );
}
-
- // Use the coupon token as the link key when it's free; otherwise fall back
- // to a unique key so the link stays owned by this coupon's partner.
- const key = takenKeys.has(coupon.token.toLowerCase())
- ? `${coupon.token}-${nanoid(6)}`
- : coupon.token;
-
- takenKeys.add(key.toLowerCase());
- couponTokenToLinkKey.set(coupon.token, key);
-
- linksToCreate.push({
- domain: program.domain!,
- key,
- url: program.url!,
- trackConversion: true,
- programId,
- partnerId,
- folderId: program.defaultFolderId,
- userId,
- projectId: program.workspaceId,
- comments: `Link created for coupon ${coupon.token}`,
- });
}
if (linksToCreate.length > 0) {
@@ -167,32 +111,21 @@ export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
});
console.log(`Created ${createdLinks.length} links`);
- // index created links by their (case-insensitive) key for robust lookup
- const linkByKey = new Map(
- createdLinks.map((link) => [link.key.toLowerCase(), link]),
- );
-
const createdDiscountCodes = await prisma.discountCode.createMany({
- data: couponsToImport
+ data: filteredCoupons
.map((coupon) => {
const { partnerId, discountId } =
filteredPartners[coupon.affiliate_id];
- const assignedKey = couponTokenToLinkKey.get(coupon.token);
- const link = assignedKey
- ? linkByKey.get(assignedKey.toLowerCase())
- : undefined;
-
+ // link should always exist since we return all links (including duplicates) from bulkCreateLinks
+ // need to remove "-coupon" from the key to match the coupon token
+ const link = createdLinks.find(
+ (link) =>
+ link.key.toLowerCase().replace("-coupon", "") ===
+ coupon.token.toLowerCase(),
+ );
if (!link) {
- console.error(`Link not found for Rewardful coupon`);
- return null;
- }
-
- // Safety net: never bind a discount code to a link owned by a different partner
- if (link.partnerId !== partnerId) {
- console.error(
- `Skipping Rewardful coupon: resolved link is owned by a different partner`,
- );
+ console.error(`Link not found for coupon ${coupon.token}`);
return null;
}
diff --git a/apps/web/lib/rewardful/import-customers.ts b/apps/web/lib/rewardful/import-customers.ts
index 58de365a0c..a3268c7cfe 100644
--- a/apps/web/lib/rewardful/import-customers.ts
+++ b/apps/web/lib/rewardful/import-customers.ts
@@ -1,6 +1,6 @@
import { prisma } from "@/lib/prisma";
import { chunk, nanoid } from "@dub/utils";
-import { Customer, Link, Program, Project } from "@prisma/client";
+import { Customer, Program, Project } from "@prisma/client";
import { createId } from "../api/create-id";
import { updateLinkStatsForImporter } from "../api/links/update-link-stats-for-importer";
import { syncPartnerLinksStats } from "../api/partners/sync-partner-links-stats";
@@ -138,35 +138,29 @@ async function createCustomer({
return;
}
- let link: Link | null = null;
- if (referral.link?.token) {
- // here we're using findFirst because for some reason findUnique uses a weird collation
- // that causes a bunch of LINK_NOT_FOUND errors (for links/coupons that actually exist)
- link = await prisma.link.findFirst({
- where: {
- domain: program.domain!,
- key: referral.link.token,
- },
- });
- } else if (referral.coupon?.token) {
- const discountCode = await prisma.discountCode.findFirst({
- where: {
- programId: program.id,
- code: referral.coupon.token,
- },
- include: {
- link: true,
- },
- });
+ const shortLinkKey =
+ referral.link?.token ||
+ (referral.coupon?.token ? `${referral.coupon?.token}-coupon` : undefined);
- link = discountCode?.link ?? null;
+ if (!shortLinkKey) {
+ console.error(`Short link token not found for referral ${referralId}.`);
+ return;
}
+ // here we're using findFirst because for some reason findUnique uses a weird collation
+ // that causes a bunch of LINK_NOT_FOUND errors (for links/coupons that actually exist)
+ const link = await prisma.link.findFirst({
+ where: {
+ domain: program.domain!,
+ key: shortLinkKey,
+ },
+ });
+
if (!link) {
await logImportError({
...commonImportLogInputs,
code: "LINK_NOT_FOUND",
- message: `Link not found for referral ${referralId}.`,
+ message: `Link not found for referral ${referralId} (token: ${shortLinkKey}).`,
});
return;