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.

Recreated coupons in Rewardful importer (#3323)

Steven Tey74068b5fc169
diff --git a/apps/web/lib/rewardful/import-affiliate-coupons.ts b/apps/web/lib/rewardful/import-affiliate-coupons.ts
index 76145bfca5..4c89ac8445 100644
--- a/apps/web/lib/rewardful/import-affiliate-coupons.ts
+++ b/apps/web/lib/rewardful/import-affiliate-coupons.ts
@@ -1,4 +1,5 @@
import { prisma } from "@dub/prisma";
+import { createId } from "../api/create-id";
import { bulkCreateLinks } from "../api/links";
import { ProcessedLinkProps } from "../types";
import { redis } from "../upstash";
@@ -44,10 +45,12 @@ export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
(affiliateCoupon) => affiliateCoupon.affiliate_id,
);
- const results = await redis.hmget<Record<string, string>>(
- `rewardful:affiliates:${program.id}`,
- ...affiliateIds,
- );
+ const results = await redis.hmget<
+ Record<
+ string,
+ { partnerId: string; groupId: string | null; discountId: string | null }
+ >
+ >(`rewardful:affiliates:${program.id}`, ...affiliateIds);
const filteredPartners = Object.fromEntries(
Object.entries(results ?? {}).filter(
@@ -79,7 +82,7 @@ export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
for (const [affiliateId, coupons] of Object.entries(
affiliateIdToCouponsMap,
)) {
- const partnerId = filteredPartners[affiliateId];
+ const { partnerId } = filteredPartners[affiliateId];
if (!partnerId) {
continue;
@@ -103,9 +106,39 @@ export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
}
if (linksToCreate.length > 0) {
- await bulkCreateLinks({
+ const createdLinks = await bulkCreateLinks({
links: linksToCreate as ProcessedLinkProps[],
});
+ console.log(`Created ${createdLinks.length} links`);
+
+ const createdDiscountCodes = await prisma.discountCode.createMany({
+ data: filteredCoupons
+ .map((coupon) => {
+ const { partnerId, discountId } =
+ filteredPartners[coupon.affiliate_id];
+
+ // link should always exist since we return all links (including duplicates) from bulkCreateLinks
+ const link = createdLinks.find(
+ (link) => link.key.toLowerCase() === coupon.token.toLowerCase(),
+ );
+ if (!link) {
+ console.error(`Link not found for coupon ${coupon.token}`);
+ return null;
+ }
+
+ return {
+ id: createId({ prefix: "dcode_" }),
+ code: coupon.token,
+ programId,
+ partnerId,
+ linkId: link.id,
+ discountId,
+ };
+ })
+ .filter((code): code is NonNullable<typeof code> => code !== null),
+ });
+
+ console.log(`Created ${createdDiscountCodes.count} discount codes`);
}
currentPage++;
diff --git a/apps/web/lib/rewardful/import-campaigns.ts b/apps/web/lib/rewardful/import-campaigns.ts
index 14bc0de6b1..1b6bc91f2d 100644
--- a/apps/web/lib/rewardful/import-campaigns.ts
+++ b/apps/web/lib/rewardful/import-campaigns.ts
@@ -4,14 +4,23 @@ import { EventType, Prisma, RewardStructure } from "@dub/prisma/client";
import { randomValue } from "@dub/utils";
import { differenceInSeconds } from "date-fns";
import { createId } from "../api/create-id";
-
import { serializeReward } from "../api/partners/serialize-reward";
import { getRewardAmount } from "../partners/get-reward-amount";
+import { stripeAppClient } from "../stripe";
+import {
+ DubDiscountAttributes,
+ stripeCouponToDubDiscount,
+ validateStripeCouponForDubDiscount,
+} from "../stripe/coupon-discount-converter";
import { DEFAULT_PARTNER_GROUP } from "../zod/schemas/groups";
import { RewardfulApi } from "./api";
import { rewardfulImporter } from "./importer";
import { RewardfulImportPayload } from "./types";
+const stripe = stripeAppClient({
+ ...(process.env.VERCEL_ENV && { mode: "live" }),
+});
+
export async function importCampaigns(payload: RewardfulImportPayload) {
const { programId, campaignIds } = payload;
@@ -20,6 +29,11 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
id: programId,
},
include: {
+ workspace: {
+ select: {
+ stripeConnectId: true,
+ },
+ },
groups: {
where: {
slug: DEFAULT_PARTNER_GROUP.slug,
@@ -144,7 +158,58 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
});
console.log(
- `Since group was newly created, also created reward ${createdReward.id} with amount ${getRewardAmount(serializeReward(createdReward))} and type ${createdReward.type}`,
+ `Created sale reward ${createdReward.id} with amount ${getRewardAmount(serializeReward(createdReward))} and type ${createdReward.type}`,
+ );
+ }
+
+ if (!createdGroup.discountId && campaign.stripe_coupon_id) {
+ let dubDiscountAttrs: DubDiscountAttributes | undefined;
+
+ if (program.workspace.stripeConnectId) {
+ try {
+ const stripeCoupon = await stripe.coupons.retrieve(
+ campaign.stripe_coupon_id,
+ {
+ stripeAccount: program.workspace.stripeConnectId,
+ },
+ );
+
+ // Validate the Stripe coupon can be converted to a Dub discount
+ const validation = validateStripeCouponForDubDiscount(stripeCoupon);
+ if (validation.isValid) {
+ // Convert Stripe coupon to Dub discount attributes
+ dubDiscountAttrs = stripeCouponToDubDiscount(stripeCoupon);
+ } else {
+ console.error(
+ `Invalid Stripe coupon ${campaign.stripe_coupon_id}: ${validation.errors.join(", ")}`,
+ );
+ }
+ } catch (error) {
+ console.error(
+ `Error retrieving Stripe coupon ${campaign.stripe_coupon_id}: ${error}`,
+ );
+ }
+ }
+
+ const createdDiscount = await prisma.discount.create({
+ data: {
+ id: createId({ prefix: "disc_" }),
+ programId,
+ amount: dubDiscountAttrs?.amount ?? 0,
+ type: dubDiscountAttrs?.type ?? "percentage",
+ maxDuration: dubDiscountAttrs?.maxDuration ?? null,
+ couponId: campaign.stripe_coupon_id,
+ // connect the discount to the group
+ partnerGroup: {
+ connect: {
+ id: createdGroup.id,
+ },
+ },
+ },
+ });
+
+ console.log(
+ `Created discount ${createdDiscount.id} (${createdDiscount.couponId}) with amount ${createdDiscount.amount} and type ${createdDiscount.type}`,
);
}
diff --git a/apps/web/lib/rewardful/import-partners.ts b/apps/web/lib/rewardful/import-partners.ts
index 1063aba320..acbea09e95 100644
--- a/apps/web/lib/rewardful/import-partners.ts
+++ b/apps/web/lib/rewardful/import-partners.ts
@@ -115,7 +115,11 @@ export async function importPartners(payload: RewardfulImportPayload) {
Object.fromEntries(
filteredPartners.map((p) => [
p.rewardfulAffiliateId,
- p.dubPartnerId,
+ {
+ partnerId: p.dubPartnerId,
+ groupId: p.dubPartnerGroupId,
+ discountId: p.dubDiscountId,
+ },
]),
),
);
@@ -229,5 +233,7 @@ async function createPartnerAndLinks({
return {
rewardfulAffiliateId: affiliate.id,
dubPartnerId: partner.id,
+ dubPartnerGroupId: programEnrollment.groupId,
+ dubDiscountId: programEnrollment.discountId,
};
}
diff --git a/apps/web/lib/rewardful/types.ts b/apps/web/lib/rewardful/types.ts
index 78806a11bb..eaa45b9474 100644
--- a/apps/web/lib/rewardful/types.ts
+++ b/apps/web/lib/rewardful/types.ts
@@ -20,6 +20,7 @@ export interface RewardfulCampaign {
default: boolean;
reward_type: "amount" | "percent";
commission_percent: number;
+ stripe_coupon_id?: string | null;
created_at: string;
updated_at: string;
}