The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
rearrange files
Steven Tey7167f244d9cf
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.tsindex a5f5e152c4..b991cce2a5 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts@@ -1,16 +1,7 @@-import {- DIRECT_DEBIT_PAYMENT_METHOD_TYPES,- PAYOUT_FAILURE_FEE_CENTS,-} from "@/lib/partners/constants";-import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";-import { sendEmail } from "@dub/email";-import PartnerPayoutFailed from "@dub/email/templates/partner-payout-failed";import { prisma } from "@dub/prisma";-import { Invoice } from "@dub/prisma/client";-import { log } from "@dub/utils";-import { waitUntil } from "@vercel/functions";import Stripe from "stripe";-import { processDomainRenewalFailure } from "./process-domain-renewal-failure";+import { processDomainRenewalFailure } from "./utils/process-domain-renewal-failure";+import { processPayoutInvoiceFailure } from "./utils/process-payout-invoice-failure";export async function chargeFailed(event: Stripe.Event) {const charge = event.data.object as Stripe.Charge;@@ -47,135 +38,8 @@ export async function chargeFailed(event: Stripe.Event) {});if (invoice.type === "partnerPayout") {- await processPayoutInvoice({ invoice, charge });+ await processPayoutInvoiceFailure({ invoice, charge });} else if (invoice.type === "domainRenewal") {await processDomainRenewalFailure({ invoice });}}--async function processPayoutInvoice({- invoice,- charge,-}: {- invoice: Invoice;- charge: Stripe.Charge;-}) {- await log({- message: `Partner payout failed for invoice ${invoice.id}.`,- type: "errors",- mention: true,- });-- // Mark the payouts as pending again- await prisma.payout.updateMany({- where: {- invoiceId: invoice.id,- },- data: {- status: "pending",- userId: null,- invoiceId: null,- },- });-- const workspace = await prisma.project.update({- where: {- id: invoice.workspaceId,- },- // Reduce the payoutsUsage by the invoice amount since the charge failed- data: {- payoutsUsage: {- decrement: invoice.amount,- },- },- include: {- users: {- select: {- user: {- select: {- email: true,- },- },- },- },- programs: {- select: {- name: true,- },- },- },- });-- if (!workspace.stripeId) {- console.log("Workspace does not have a Stripe ID, skipping...");- return;- }-- let cardLast4: string | undefined;- let chargedFailureFee = false;-- // Charge failure fee for direct debit payment failures- if (- charge.payment_method_details &&- DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(- charge.payment_method_details.type as Stripe.PaymentMethod.Type,- )- ) {- const { paymentIntent, paymentMethod } = await createPaymentIntent({- stripeId: workspace.stripeId,- amount: PAYOUT_FAILURE_FEE_CENTS,- invoiceId: invoice.id,- description: `Dub Partners payout failure fee for invoice ${invoice.id}`,- statementDescriptor: "Dub Partners",- });-- if (paymentIntent) {- chargedFailureFee = true;- console.log(- `Charged a failure fee of $${PAYOUT_FAILURE_FEE_CENTS / 100} to ${workspace.slug}.`,- );- }-- if (paymentMethod?.card) {- cardLast4 = paymentMethod.card.last4;- }- }-- waitUntil(- (async () => {- // Send email to the workspace users about the failed payout- const emailData = workspace.users.map((user) => ({- email: user.user.email!,- workspace: {- slug: workspace.slug,- },- program: {- name: workspace.programs[0].name,- },- payout: {- amount: charge.amount,- ...(chargedFailureFee && {- failureFee: PAYOUT_FAILURE_FEE_CENTS,- cardLast4,- }),- },- }));-- if (emailData.length === 0) {- console.log("No users found to send email, skipping...");- return;- }-- await Promise.all(- emailData.map((data) => {- sendEmail({- subject: "Partner payout failed",- to: data.email,- react: PartnerPayoutFailed(data),- variant: "notifications",- });- }),- );- })(),- );-}diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.tsindex a90292208e..15db8e6b25 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts@@ -9,7 +9,8 @@ import { prisma } from "@dub/prisma";import { FREE_PLAN, getPlanFromPriceId, log } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";-import { sendCancellationFeedback, updateWorkspacePlan } from "./utils";+import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";+import { updateWorkspacePlan } from "./utils/update-workspace-plan";export async function customerSubscriptionDeleted(event: Stripe.Event) {const subscriptionDeleted = event.data.object as Stripe.Subscription;diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.tsindex 99083b2bf1..e73f887b0f 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts@@ -2,7 +2,8 @@ import { prisma } from "@dub/prisma";import { getPlanFromPriceId } from "@dub/utils";import { NextResponse } from "next/server";import Stripe from "stripe";-import { sendCancellationFeedback, updateWorkspacePlan } from "./utils";+import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";+import { updateWorkspacePlan } from "./utils/update-workspace-plan";export async function customerSubscriptionUpdated(event: Stripe.Event) {const subscriptionUpdated = event.data.object as Stripe.Subscription;diff --git a/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.tsindex a1a918ac8c..791ce50394 100644--- a/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts@@ -1,6 +1,6 @@import { prisma } from "@dub/prisma";import Stripe from "stripe";-import { processDomainRenewalFailure } from "./process-domain-renewal-failure";+import { processDomainRenewalFailure } from "./utils/process-domain-renewal-failure";export async function paymentIntentRequiresAction(event: Stripe.Event) {const { transfer_group: invoiceId } = event.datadiff --git a/apps/web/app/(ee)/api/stripe/webhook/process-domain-renewal-failure.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/process-domain-renewal-failure.tssimilarity index 100%rename from apps/web/app/(ee)/api/stripe/webhook/process-domain-renewal-failure.tsrename to apps/web/app/(ee)/api/stripe/webhook/utils/process-domain-renewal-failure.tsdiff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/process-payout-invoice-failure.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/process-payout-invoice-failure.tsnew file mode 100644index 0000000000..c06a6c3353--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/process-payout-invoice-failure.ts@@ -0,0 +1,139 @@+import {+ DIRECT_DEBIT_PAYMENT_METHOD_TYPES,+ PAYOUT_FAILURE_FEE_CENTS,+} from "@/lib/partners/constants";+import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";+import { sendEmail } from "@dub/email";+import PartnerPayoutFailed from "@dub/email/templates/partner-payout-failed";+import { prisma } from "@dub/prisma";+import { Invoice } from "@dub/prisma/client";+import { log } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import Stripe from "stripe";++export async function processPayoutInvoiceFailure({+ invoice,+ charge,+}: {+ invoice: Invoice;+ charge: Stripe.Charge;+}) {+ await log({+ message: `Partner payout failed for invoice ${invoice.id}.`,+ type: "errors",+ mention: true,+ });++ // Mark the payouts as pending again+ await prisma.payout.updateMany({+ where: {+ invoiceId: invoice.id,+ },+ data: {+ status: "pending",+ userId: null,+ invoiceId: null,+ },+ });++ const workspace = await prisma.project.update({+ where: {+ id: invoice.workspaceId,+ },+ // Reduce the payoutsUsage by the invoice amount since the charge failed+ data: {+ payoutsUsage: {+ decrement: invoice.amount,+ },+ },+ include: {+ users: {+ select: {+ user: {+ select: {+ email: true,+ },+ },+ },+ },+ programs: {+ select: {+ name: true,+ },+ },+ },+ });++ if (!workspace.stripeId) {+ console.log("Workspace does not have a Stripe ID, skipping...");+ return;+ }++ let cardLast4: string | undefined;+ let chargedFailureFee = false;++ // Charge failure fee for direct debit payment failures+ if (+ charge.payment_method_details &&+ DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(+ charge.payment_method_details.type as Stripe.PaymentMethod.Type,+ )+ ) {+ const { paymentIntent, paymentMethod } = await createPaymentIntent({+ stripeId: workspace.stripeId,+ amount: PAYOUT_FAILURE_FEE_CENTS,+ invoiceId: invoice.id,+ description: `Dub Partners payout failure fee for invoice ${invoice.id}`,+ statementDescriptor: "Dub Partners",+ });++ if (paymentIntent) {+ chargedFailureFee = true;+ console.log(+ `Charged a failure fee of $${PAYOUT_FAILURE_FEE_CENTS / 100} to ${workspace.slug}.`,+ );+ }++ if (paymentMethod?.card) {+ cardLast4 = paymentMethod.card.last4;+ }+ }++ waitUntil(+ (async () => {+ // Send email to the workspace users about the failed payout+ const emailData = workspace.users.map((user) => ({+ email: user.user.email!,+ workspace: {+ slug: workspace.slug,+ },+ program: {+ name: workspace.programs[0].name,+ },+ payout: {+ amount: charge.amount,+ ...(chargedFailureFee && {+ failureFee: PAYOUT_FAILURE_FEE_CENTS,+ cardLast4,+ }),+ },+ }));++ if (emailData.length === 0) {+ console.log("No users found to send email, skipping...");+ return;+ }++ await Promise.all(+ emailData.map((data) => {+ sendEmail({+ subject: "Partner payout failed",+ to: data.email,+ react: PartnerPayoutFailed(data),+ variant: "notifications",+ });+ }),+ );+ })(),+ );+}diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.tsnew file mode 100644index 0000000000..d4bdaa617e--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/send-cancellation-feedback.ts@@ -0,0 +1,39 @@+import { sendEmail } from "@dub/email";+import Stripe from "stripe";++const cancellationReasonMap = {+ customer_service: "you had a bad experience with our customer service",+ low_quality: "the product didn't meet your expectations",+ missing_features: "you were expecting more features",+ switched_service: "you switched to a different service",+ too_complex: "the product was too complex",+ too_expensive: "the product was too expensive",+ unused: "you didn't use the product",+};++export async function sendCancellationFeedback({+ owners,+ reason,+}: {+ owners: {+ name: string | null;+ email: string | null;+ }[];+ reason?: Stripe.Subscription.CancellationDetails.Feedback | null;+}) {+ const reasonText = reason ? cancellationReasonMap[reason] : "";++ return await Promise.all(+ owners.map(+ (owner) =>+ owner.email &&+ sendEmail({+ to: owner.email,+ from: "Steven Tey <[email protected]>",+ replyTo: "[email protected]",+ subject: "Feedback for Dub.co?",+ text: `Hey ${owner.name ? owner.name.split(" ")[0] : "there"}!\n\nSaw you canceled your Dub subscription${reasonText ? ` and mentioned that ${reasonText}` : ""} – do you mind sharing if there's anything we could've done better on our side?\n\nWe're always looking to improve our product offering so any feedback would be greatly appreciated!\n\nThank you so much in advance!\n\nBest,\nSteven Tey\nFounder, Dub.co`,+ }),+ ),+ );+}diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils.ts b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.tssimilarity index 74%rename from apps/web/app/(ee)/api/stripe/webhook/utils.tsrename to apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.tsindex 8d2f9aeb2e..2fd282bed7 100644--- a/apps/web/app/(ee)/api/stripe/webhook/utils.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/utils/update-workspace-plan.ts@@ -3,48 +3,9 @@ import { tokenCache } from "@/lib/auth/token-cache";import { getPlanCapabilities } from "@/lib/plan-capabilities";import { WorkspaceProps } from "@/lib/types";import { webhookCache } from "@/lib/webhook/cache";-import { sendEmail } from "@dub/email";import { prisma } from "@dub/prisma";import { getPlanFromPriceId } from "@dub/utils";import { NEW_BUSINESS_PRICE_IDS } from "@dub/utils/src";-import Stripe from "stripe";--const cancellationReasonMap = {- customer_service: "you had a bad experience with our customer service",- low_quality: "the product didn't meet your expectations",- missing_features: "you were expecting more features",- switched_service: "you switched to a different service",- too_complex: "the product was too complex",- too_expensive: "the product was too expensive",- unused: "you didn't use the product",-};--export async function sendCancellationFeedback({- owners,- reason,-}: {- owners: {- name: string | null;- email: string | null;- }[];- reason?: Stripe.Subscription.CancellationDetails.Feedback | null;-}) {- const reasonText = reason ? cancellationReasonMap[reason] : "";-- return await Promise.all(- owners.map(- (owner) =>- owner.email &&- sendEmail({- to: owner.email,- from: "Steven Tey <[email protected]>",- replyTo: "[email protected]",- subject: "Feedback for Dub.co?",- text: `Hey ${owner.name ? owner.name.split(" ")[0] : "there"}!\n\nSaw you canceled your Dub subscription${reasonText ? ` and mentioned that ${reasonText}` : ""} – do you mind sharing if there's anything we could've done better on our side?\n\nWe're always looking to improve our product offering so any feedback would be greatly appreciated!\n\nThank you so much in advance!\n\nBest,\nSteven Tey\nFounder, Dub.co`,- }),- ),- );-}export async function updateWorkspacePlan({workspace,