The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add more customer stats (`firstSaleAt`, `subscriptionCanceledAt`) (#3379)
Steven Tey6ab9c5d5df48
diff --git a/apps/web/app/(ee)/api/cron/partners/ban/cancel-commissions.ts b/apps/web/app/(ee)/api/cron/partners/ban/cancel-commissions.tsindex de31cb6b1e..bfd60af4a6 100644--- a/apps/web/app/(ee)/api/cron/partners/ban/cancel-commissions.ts+++ b/apps/web/app/(ee)/api/cron/partners/ban/cancel-commissions.ts@@ -1,6 +1,6 @@import { prisma } from "@dub/prisma";-// Mark the commissions as cancelled+// Mark the commissions as canceledexport async function cancelCommissions({programId,partnerId,@@ -63,9 +63,9 @@ export async function cancelCommissions({if (failedBatches > 0) {console.warn(- `Cancelled ${canceledCommissions} commissions with ${failedBatches} failed batch(es).`,+ `Canceled ${canceledCommissions} commissions with ${failedBatches} failed batch(es).`,);} else {- console.info(`Cancelled ${canceledCommissions} commissions.`);+ console.info(`Canceled ${canceledCommissions} commissions.`);}}diff --git a/apps/web/app/(ee)/api/cron/partners/ban/route.ts b/apps/web/app/(ee)/api/cron/partners/ban/route.tsindex 5d18da0e5f..93f68c8960 100644--- a/apps/web/app/(ee)/api/cron/partners/ban/route.ts+++ b/apps/web/app/(ee)/api/cron/partners/ban/route.ts@@ -109,9 +109,9 @@ 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(`Cancelled ${payouts.count} payouts.`);+ console.info(`Canceled ${payouts.count} payouts.`);- // Mark the commissions as cancelled+ // Mark the commissions as canceledawait cancelCommissions({programId,partnerId,diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 11ca4dbe55..740f93f542 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -431,6 +431,8 @@ export async function checkoutSessionCompleted(saleAmount: {increment: chargeAmountTotal,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),+ subscriptionCanceledAt: null,},}),]);diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.tsnew file mode 100644index 0000000000..47d3bf2683--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.ts@@ -0,0 +1,24 @@+import { prisma } from "@dub/prisma";+import type Stripe from "stripe";++// Handle event "customer.subscription.deleted"+export async function customerSubscriptionDeleted(event: Stripe.Event) {+ const deletedSubscription = event.data.object as Stripe.Subscription;++ const customer = await prisma.customer.findUnique({+ where: {+ stripeCustomerId: deletedSubscription.customer.toString(),+ },+ });++ if (!customer) {+ return "Customer not found, skipping subscription cancellation...";+ }++ const updatedCustomer = await prisma.customer.update({+ where: { id: customer.id },+ data: { subscriptionCanceledAt: new Date() },+ });++ return `Subscription cancelled, updating customer ${updatedCustomer.id} with subscriptionCanceledAt: ${updatedCustomer.subscriptionCanceledAt}`;+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex fa6742b941..612e971729 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@ -208,6 +208,7 @@ export async function invoicePaid(event: Stripe.Event, mode: StripeMode) {saleAmount: {increment: invoiceSaleAmount,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),},}),]);diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.tsindex 99c544d579..000198a107 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts@@ -8,18 +8,20 @@ import { chargeRefunded } from "./charge-refunded";import { checkoutSessionCompleted } from "./checkout-session-completed";import { couponDeleted } from "./coupon-deleted";import { customerCreated } from "./customer-created";+import { customerSubscriptionDeleted } from "./customer-subscription-deleted";import { customerUpdated } from "./customer-updated";import { invoicePaid } from "./invoice-paid";import { promotionCodeUpdated } from "./promotion-code-updated";const relevantEvents = new Set([+ "account.application.deauthorized",+ "charge.refunded",+ "checkout.session.completed",+ "coupon.deleted","customer.created","customer.updated",- "checkout.session.completed",+ "customer.subscription.deleted","invoice.paid",- "charge.refunded",- "account.application.deauthorized",- "coupon.deleted","promotion_code.updated",]);@@ -80,27 +82,30 @@ export const POST = withAxiom(async (req: Request) => {let response = "OK";switch (event.type) {+ case "account.application.deauthorized":+ response = await accountApplicationDeauthorized(event);+ break;+ case "charge.refunded":+ response = await chargeRefunded(event, mode);+ break;+ case "checkout.session.completed":+ response = await checkoutSessionCompleted(event, mode);+ break;+ case "coupon.deleted":+ response = await couponDeleted(event);+ break;case "customer.created":response = await customerCreated(event);break;case "customer.updated":response = await customerUpdated(event);break;- case "checkout.session.completed":- response = await checkoutSessionCompleted(event, mode);+ case "customer.subscription.deleted":+ response = await customerSubscriptionDeleted(event);break;case "invoice.paid":response = await invoicePaid(event, mode);break;- case "charge.refunded":- response = await chargeRefunded(event, mode);- break;- case "account.application.deauthorized":- response = await accountApplicationDeauthorized(event);- break;- case "coupon.deleted":- response = await couponDeleted(event);- break;case "promotion_code.updated":response = await promotionCodeUpdated(event);break;diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsindex 9dbe9d8d72..81f51ffcc5 100644--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ b/apps/web/lib/actions/partners/create-manual-commission.ts@@ -469,6 +469,7 @@ export const createManualCommissionAction = authActionClientsaleAmount: {increment: saleAmount,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),}),},});diff --git a/apps/web/lib/api/conversions/track-sale.ts b/apps/web/lib/api/conversions/track-sale.tsindex 0f2fed1087..ceb5e3d884 100644--- a/apps/web/lib/api/conversions/track-sale.ts+++ b/apps/web/lib/api/conversions/track-sale.ts@@ -625,6 +625,7 @@ const _trackSale = async ({saleAmount: {increment: amount,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),},});})(),diff --git a/apps/web/lib/firstpromoter/import-commissions.ts b/apps/web/lib/firstpromoter/import-commissions.tsindex 214951edd9..239ce3dab1 100644--- a/apps/web/lib/firstpromoter/import-commissions.ts+++ b/apps/web/lib/firstpromoter/import-commissions.ts@@ -388,6 +388,7 @@ async function createCommission({saleAmount: {increment: saleAmount,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),},}),]);diff --git a/apps/web/lib/integrations/shopify/create-sale.ts b/apps/web/lib/integrations/shopify/create-sale.tsindex 732ea25692..f6ec7aae53 100644--- a/apps/web/lib/integrations/shopify/create-sale.ts+++ b/apps/web/lib/integrations/shopify/create-sale.ts@@ -116,7 +116,7 @@ export async function createShopifySale({}),prisma.customer.update({where: {- id: customerId,+ id: existingCustomer.id,},data: {sales: {@@ -125,6 +125,7 @@ export async function createShopifySale({saleAmount: {increment: amount,},+ firstSaleAt: existingCustomer.firstSaleAt ? undefined : new Date(),},}),redis.del(`shopify:checkout:${checkoutToken}`),diff --git a/apps/web/lib/partnerstack/import-commissions.ts b/apps/web/lib/partnerstack/import-commissions.tsindex 9ca47554a8..cb7a746508 100644--- a/apps/web/lib/partnerstack/import-commissions.ts+++ b/apps/web/lib/partnerstack/import-commissions.ts@@ -498,6 +498,7 @@ async function createCommission({saleAmount: {increment: amount,},+ firstSaleAt: customer.firstSaleAt ? undefined : new Date(),},}),]);diff --git a/apps/web/lib/rewardful/import-commissions.ts b/apps/web/lib/rewardful/import-commissions.tsindex 1062530b8f..8b20534e31 100644--- a/apps/web/lib/rewardful/import-commissions.ts+++ b/apps/web/lib/rewardful/import-commissions.ts@@ -384,6 +384,7 @@ async function createCommission({data: {sales: { increment: 1 },saleAmount: { increment: amount },+ firstSaleAt: customerFound.firstSaleAt ? undefined : new Date(),},}),]);diff --git a/apps/web/lib/tolt/import-commissions.ts b/apps/web/lib/tolt/import-commissions.tsindex 215db93818..bc72422e85 100644--- a/apps/web/lib/tolt/import-commissions.ts+++ b/apps/web/lib/tolt/import-commissions.ts@@ -396,6 +396,7 @@ async function createCommission({saleAmount: {increment: saleAmount,},+ firstSaleAt: customerFound.firstSaleAt ? undefined : new Date(),},}),]);diff --git a/apps/web/scripts/dev/seed.ts b/apps/web/scripts/dev/seed.tsindex 6a8fedf27a..7ebe538e58 100644--- a/apps/web/scripts/dev/seed.ts+++ b/apps/web/scripts/dev/seed.ts@@ -541,7 +541,7 @@ async function main() {);if (!confirmed) {- console.log("\nTruncate cancelled. Exiting...");+ console.log("\nTruncate canceled. Exiting...");process.exit(0);}diff --git a/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts b/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.tsnew file mode 100644index 0000000000..21269b4b63--- /dev/null+++ b/apps/web/scripts/migrations/backfill-customer-subscription-cancellation.ts@@ -0,0 +1,76 @@+import { prisma } from "@dub/prisma";+import "dotenv-flow/config";+import { stripeAppClient } from "../../lib/stripe";++async function main() {+ const stripeCustomers = await prisma.customer.findMany({+ where: {+ AND: [+ {+ stripeCustomerId: {+ not: null,+ },+ },+ {+ stripeCustomerId: {+ notIn: [],+ },+ },+ {+ firstSaleAt: null,+ },+ ],+ },+ take: 20,+ });++ let testModeCustomerIds: string[] = [];++ await Promise.all(+ stripeCustomers.map(async (customer) => {+ try {+ const customerSubscriptions = await stripeAppClient({+ mode: "live",+ }).subscriptions.list(+ {+ customer: customer.stripeCustomerId!,+ status: "all",+ },+ {+ stripeAccount: customer.projectConnectId!,+ },+ );++ if (customerSubscriptions.data.length === 0) {+ console.log(`No subscriptions found for customer ${customer.email}`);+ return;+ }++ const subscription = customerSubscriptions.data[0];++ const data = {+ startDate: new Date(subscription.created * 1000),+ subscriptionCanceledAt: subscription.canceled_at+ ? new Date(subscription.canceled_at * 1000)+ : null,+ };++ console.log({+ email: customer.email,+ ...data,+ });++ await prisma.customer.update({+ where: { id: customer.id },+ data,+ });+ } catch (error) {+ testModeCustomerIds.push(customer.id);+ }+ }),+ );++ console.log(`Test mode customer ids: "${testModeCustomerIds.join('", "')}"`);+}++main();diff --git a/apps/web/scripts/perplexity/ban-partners.ts b/apps/web/scripts/perplexity/ban-partners.tsindex 06c12ec119..5785f182fd 100644--- a/apps/web/scripts/perplexity/ban-partners.ts+++ b/apps/web/scripts/perplexity/ban-partners.ts@@ -95,7 +95,7 @@ async function main() {// },// });// console.log(- // `Cancelled ${res.count} commissions for partner ${enrollment.partnerId}`,+ // `Canceled ${res.count} commissions for partner ${enrollment.partnerId}`,// );// }// }diff --git a/packages/prisma/schema/customer.prisma b/packages/prisma/schema/customer.prismaindex 7997ff7419..07f9f0af8b 100644--- a/packages/prisma/schema/customer.prisma+++ b/packages/prisma/schema/customer.prisma@@ -11,8 +11,10 @@ model Customer {clickedAt DateTime?country String?- sales Int @default(0)- saleAmount Int @default(0)+ sales Int @default(0)+ saleAmount Int @default(0)+ firstSaleAt DateTime?+ subscriptionCanceledAt DateTime?projectId StringprojectConnectId String?@@ -38,6 +40,7 @@ model Customer {@@index([projectId, createdAt])@@index([projectId, saleAmount])@@index([programId, partnerId])+ @@index(partnerId)@@index(linkId)@@index(country)@@fulltext([email, name]) // For full-text searchdiff --git a/packages/prisma/schema/referral.prisma b/packages/prisma/schema/referral.prismaindex 08937fd8cd..f312b52f06 100644--- a/packages/prisma/schema/referral.prisma+++ b/packages/prisma/schema/referral.prisma@@ -19,10 +19,10 @@ model PartnerReferral {createdAt DateTime @default(now())updatedAt DateTime @updatedAt- program Program @relation(fields: [programId], references: [id])- partner Partner @relation(fields: [partnerId], references: [id])- programEnrollment ProgramEnrollment @relation(fields: [programId, partnerId], references: [programId, partnerId])- customer Customer? @relation(fields: [customerId], references: [id])+ program Program @relation(fields: [programId], references: [id])+ partner Partner @relation(fields: [partnerId], references: [id])+ programEnrollment ProgramEnrollment @relation(fields: [programId, partnerId], references: [programId, partnerId])+ customer Customer? @relation(fields: [customerId], references: [id])@@index([programId, partnerId])@@index(partnerId)