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.

create links for affiliate coupons

Kiran Kbb861bf17daf
diff --git a/apps/web/app/(ee)/api/cron/import/rewardful/route.ts b/apps/web/app/(ee)/api/cron/import/rewardful/route.ts
index 8bb4c4bd72..b73fc7794e 100644
--- a/apps/web/app/(ee)/api/cron/import/rewardful/route.ts
+++ b/apps/web/app/(ee)/api/cron/import/rewardful/route.ts
@@ -1,5 +1,6 @@
import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { importAffiliateCoupons } from "@/lib/rewardful/import-affiliate-coupons";
import { importCampaigns } from "@/lib/rewardful/import-campaigns";
import { importCommissions } from "@/lib/rewardful/import-commissions";
import { importCustomers } from "@/lib/rewardful/import-customers";
@@ -23,6 +24,9 @@ export async function POST(req: Request) {
case "import-partners":
await importPartners(payload);
break;
+ case "import-affiliate-coupons":
+ await importAffiliateCoupons(payload);
+ break;
case "import-customers":
await importCustomers(payload);
break;
diff --git a/apps/web/lib/rewardful/api.ts b/apps/web/lib/rewardful/api.ts
index 0bc3ac0015..5df2cb3728 100644
--- a/apps/web/lib/rewardful/api.ts
+++ b/apps/web/lib/rewardful/api.ts
@@ -1,6 +1,7 @@
import { DubApiError } from "@/lib/api/errors";
import {
RewardfulAffiliate,
+ RewardfulAffiliateCoupon,
RewardfulCampaign,
RewardfulCommission,
RewardfulReferral,
@@ -32,8 +33,6 @@ export class RewardfulApi {
},
});
- console.log( `Basic ${Buffer.from(`${this.token}:`).toString("base64")}`)
-
if (!response.ok) {
const error = await response.text();
console.log("Rewardful API Error:", error);
@@ -95,4 +94,16 @@ export class RewardfulApi {
return data;
}
+
+ async listAffiliateCoupons({ page = 1 }: { page?: number }) {
+ const searchParams = new URLSearchParams();
+ searchParams.append("page", page.toString());
+ searchParams.append("limit", PAGE_LIMIT.toString());
+
+ const { data } = await this.fetch<{ data: RewardfulAffiliateCoupon[] }>(
+ `${this.baseUrl}/affiliate_coupons?${searchParams.toString()}`,
+ );
+
+ return data;
+ }
}
diff --git a/apps/web/lib/rewardful/import-affiliate-coupons.ts b/apps/web/lib/rewardful/import-affiliate-coupons.ts
new file mode 100644
index 0000000000..3fceb8039d
--- /dev/null
+++ b/apps/web/lib/rewardful/import-affiliate-coupons.ts
@@ -0,0 +1,103 @@
+import { prisma } from "@dub/prisma";
+import { bulkCreateLinks } from "../api/links";
+import { redis } from "../upstash";
+import { RewardfulApi } from "./api";
+import { MAX_BATCHES, rewardfulImporter } from "./importer";
+import { RewardfulImportPayload } from "./types";
+
+export async function importAffiliateCoupons(payload: RewardfulImportPayload) {
+ const { programId, userId, page = 1 } = payload;
+
+ const program = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ });
+
+ const { token } = await rewardfulImporter.getCredentials(program.workspaceId);
+
+ const rewardfulApi = new RewardfulApi({ token });
+
+ let currentPage = page;
+ let hasMore = true;
+ let processedBatches = 0;
+
+ while (hasMore && processedBatches < MAX_BATCHES) {
+ const affiliateCoupons = await rewardfulApi.listAffiliateCoupons({
+ page: currentPage,
+ });
+
+ if (affiliateCoupons.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const affiliateIds = affiliateCoupons.map(
+ (affiliateCoupon) => affiliateCoupon.affiliate_id,
+ );
+
+ const results = await redis.hmget<Record<string, string>>(
+ `rewardful:affiliates:${program.id}`,
+ ...affiliateIds,
+ );
+
+ const filteredPartners = Object.fromEntries(
+ Object.entries(results ?? {}).filter(
+ ([_, value]) => value !== null && value !== undefined,
+ ),
+ );
+
+ const affiliateIdToCouponsMap = affiliateCoupons.reduce(
+ (acc, coupon) => {
+ if (!acc[coupon.affiliate_id]) {
+ acc[coupon.affiliate_id] = [];
+ }
+
+ acc[coupon.affiliate_id].push(coupon);
+ return acc;
+ },
+ {} as Record<string, typeof affiliateCoupons>,
+ );
+
+ if (Object.keys(filteredPartners).length > 0) {
+ const linksToCreate: any[] = [];
+
+ for (const [affiliateId, partnerId] of Object.entries(filteredPartners)) {
+ const coupons = affiliateIdToCouponsMap[affiliateId];
+
+ if (!coupons) {
+ continue;
+ }
+
+ linksToCreate.push(
+ ...coupons.map((coupon) => ({
+ domain: program.domain,
+ key: coupon.token.toLowerCase(),
+ url: program.url,
+ trackConversion: true,
+ programId,
+ partnerId,
+ folderId: program.defaultFolderId,
+ userId,
+ projectId: program.workspaceId,
+ })),
+ );
+ }
+
+ await bulkCreateLinks({
+ links: linksToCreate,
+ });
+ }
+
+ currentPage++;
+ processedBatches++;
+ }
+
+ const action = hasMore ? "import-affiliate-coupons" : "import-customers";
+
+ await rewardfulImporter.queue({
+ ...payload,
+ action,
+ page: hasMore ? currentPage : undefined,
+ });
+}
diff --git a/apps/web/lib/rewardful/import-campaigns.ts b/apps/web/lib/rewardful/import-campaigns.ts
index 0287d88a87..19e0624fa7 100644
--- a/apps/web/lib/rewardful/import-campaigns.ts
+++ b/apps/web/lib/rewardful/import-campaigns.ts
@@ -5,10 +5,6 @@ import { randomValue } from "@dub/utils";
import { differenceInSeconds } from "date-fns";
import { createId } from "../api/create-id";
import { stripeAppClient } from "../stripe";
-import {
- stripeCouponToDubDiscount,
- validateStripeCouponForDubDiscount,
-} from "../stripe/coupon-discount-converter";
import { RewardfulApi } from "./api";
import { rewardfulImporter } from "./importer";
import { RewardfulImportPayload } from "./types";
@@ -52,11 +48,8 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
max_commission_period_months,
days_until_commissions_are_due,
reward_type,
- stripe_coupon_id: stripeCouponId,
} = campaign;
- console.log({ campaignId, stripeCouponId });
-
const groupSlug = `rewardful-${campaignId}`;
const createdGroup = await prisma.partnerGroup.upsert({
where: {
@@ -111,6 +104,7 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
: commission_percent,
},
});
+
console.log(
`Since group was newly created, also created reward ${createdReward.id} with amount ${createdReward.amount} and type ${createdReward.type}`,
);
@@ -130,44 +124,10 @@ export async function importCampaigns(payload: RewardfulImportPayload) {
`Updated program ${programId} with min payout amount ${minimum_payout_cents} and holding period days ${days_until_commissions_are_due}`,
);
}
-
- // Create a Discount for the program if a stripe_coupon_id exists for the campaign
- if (stripeCouponId && workspace.stripeConnectId) {
- // TODO:
- // Will invalid coupon throws error or return null
-
- const stripeCoupon = await stripe.coupons.retrieve(stripeCouponId, {
- stripeAccount: workspace.stripeConnectId,
- });
-
- const validation = validateStripeCouponForDubDiscount(stripeCoupon);
-
- if (!validation.isValid) {
- console.warn(`Invalid Stripe coupon: ${validation.errors.join(", ")}`);
- continue;
- }
-
- const dubDiscountAttrs = stripeCouponToDubDiscount(stripeCoupon);
-
- const discount = await prisma.discount.create({
- data: {
- id: createId({ prefix: "disc_" }),
- programId,
- couponId: stripeCouponId,
- amount: dubDiscountAttrs.amount,
- type: dubDiscountAttrs.type,
- maxDuration: dubDiscountAttrs.maxDuration,
- },
- });
-
- console.log(
- `Created discount ${discount.id} for campaign ${campaign.name} (${campaignId})`,
- );
- }
}
- // return await rewardfulImporter.queue({
- // ...payload,
- // action: "import-partners",
- // });
+ return await rewardfulImporter.queue({
+ ...payload,
+ action: "import-partners",
+ });
}
diff --git a/apps/web/lib/rewardful/import-partners.ts b/apps/web/lib/rewardful/import-partners.ts
index bb310dedaa..3fa8a2ae57 100644
--- a/apps/web/lib/rewardful/import-partners.ts
+++ b/apps/web/lib/rewardful/import-partners.ts
@@ -4,6 +4,7 @@ import { nanoid } from "@dub/utils";
import { createId } from "../api/create-id";
import { bulkCreateLinks } from "../api/links";
import { logImportError } from "../tinybird/log-import-error";
+import { redis } from "../upstash";
import { RewardfulApi } from "./api";
import { MAX_BATCHES, rewardfulImporter } from "./importer";
import { RewardfulAffiliate, RewardfulImportPayload } from "./types";
@@ -72,7 +73,7 @@ export async function importPartners(payload: RewardfulImportPayload) {
}
if (activeAffiliates.length > 0) {
- await Promise.all(
+ const partners = await Promise.all(
activeAffiliates.map((affiliate) => {
const groupId = campaignIdToGroupMap[affiliate.campaign.id];
const group = program.groups.find((group) => group.id === groupId);
@@ -103,6 +104,15 @@ export async function importPartners(payload: RewardfulImportPayload) {
});
}),
);
+
+ await redis.hset(
+ `rewardful:affiliates:${program.id}`,
+ Object.fromEntries(
+ partners
+ .filter((p): p is NonNullable<typeof p> => p !== undefined)
+ .map((p) => [p.rewardfulAffiliateId, p.dubPartnerId]),
+ ),
+ );
}
if (notImportedAffiliates.length > 0) {
@@ -120,7 +130,7 @@ export async function importPartners(payload: RewardfulImportPayload) {
processedBatches++;
}
- const action = hasMore ? "import-partners" : "import-customers";
+ const action = hasMore ? "import-partners" : "import-affiliate-coupons";
await rewardfulImporter.queue({
...payload,
@@ -207,4 +217,9 @@ async function createPartnerAndLinks({
partnerGroupDefaultLinkId: idx === 0 ? partnerGroupDefaultLinkId : null,
})),
});
+
+ return {
+ rewardfulAffiliateId: affiliate.id,
+ dubPartnerId: partner.id,
+ };
}
diff --git a/apps/web/lib/rewardful/schemas.ts b/apps/web/lib/rewardful/schemas.ts
index 33ef36e006..38fe68b03f 100644
--- a/apps/web/lib/rewardful/schemas.ts
+++ b/apps/web/lib/rewardful/schemas.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
export const rewardfulImportSteps = z.enum([
"import-campaigns",
"import-partners",
+ "import-affiliate-coupons",
"import-customers",
"import-commissions",
]);
diff --git a/apps/web/lib/rewardful/types.ts b/apps/web/lib/rewardful/types.ts
index 6fa5296ef4..7635b546ce 100644
--- a/apps/web/lib/rewardful/types.ts
+++ b/apps/web/lib/rewardful/types.ts
@@ -101,6 +101,15 @@ export interface RewardfulCommission {
sale: RewardfulCommissionSale;
}
+export interface RewardfulAffiliateCoupon {
+ id: string;
+ external_id: string;
+ archived: boolean;
+ archived_at: string;
+ token: string;
+ affiliate_id: string;
+}
+
export type RewardfulImportPayload = z.infer<
typeof rewardfulImportPayloadSchema
>;