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.

Add domain renewal reminders cron and refactor Stripe webhook handlers

Kiran Kd4b647e4ad55
diff --git a/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts b/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts
new file mode 100644
index 0000000000..57b502c04f
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/domains/renewal-reminders/route.ts
@@ -0,0 +1,47 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { prisma } from "@dub/prisma";
+import { log } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+/**
+ * Cron to check if domains are verified.
+ * If a domain is invalid for more than 14 days, we send a reminder email to the workspace owner.
+ * If a domain is invalid for more than 28 days, we send a second and final reminder email to the workspace owner.
+ * If a domain is invalid for more than 30 days, we delete it from the database.
+ **/
+// Runs every hour (0 * * * *)
+
+export const dynamic = "force-dynamic";
+
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ const domains = await prisma.registeredDomain.findMany({
+ where: {
+ autoRenewalDisabledAt: null,
+ expiresAt: {
+ lte: new Date(Date.now() + 1000 * 60 * 60 * 24 * 30),
+ },
+ },
+ });
+
+ if (domains.length === 0) {
+ return NextResponse.json("No domains found to send reminders for.");
+ }
+
+ // for (const domain of domains) {
+ // await sendDomainRenewalReminderEmail(domain);
+ // }
+
+ return NextResponse.json("OK");
+ } catch (error) {
+ await log({
+ message: "Domains renewal cron failed. Error: " + error.message,
+ type: "errors",
+ });
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
index 56f95b67c9..d4c8386912 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
@@ -6,6 +6,7 @@ import { stripe } from "@/lib/stripe";
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";
@@ -13,25 +14,32 @@ import Stripe from "stripe";
export async function chargeFailed(event: Stripe.Event) {
const charge = event.data.object as Stripe.Charge;
- const {
- amount,
- transfer_group: invoiceId,
- failure_message: failedReason,
- } = charge;
+ const { transfer_group: invoiceId, failure_message: failedReason } = charge;
if (!invoiceId) {
console.log("No transfer group found, skipping...");
return;
}
- await log({
- message: `Partner payout failed for invoice ${invoiceId}.`,
- type: "errors",
- mention: true,
+ const invoice = await prisma.invoice.findUnique({
+ where: {
+ id: invoiceId,
+ },
+ select: {
+ id: true,
+ status: true,
+ type: true,
+ workspaceId: true,
+ amount: true,
+ },
});
- // Mark the invoice as failed
- const invoice = await prisma.invoice.update({
+ if (!invoice) {
+ console.log(`Invoice with transfer group ${invoiceId} not found.`);
+ return;
+ }
+
+ await prisma.invoice.update({
where: {
id: invoiceId,
},
@@ -41,10 +49,30 @@ export async function chargeFailed(event: Stripe.Event) {
},
});
+ if (invoice.type === "partnerPayout") {
+ await processPayoutInvoice({ invoice, charge });
+ } else if (invoice.type === "domainRenewal") {
+ await processRenewalInvoice({ invoice, charge });
+ }
+}
+
+async function processPayoutInvoice({
+ invoice,
+ charge,
+}: {
+ invoice: Pick<Invoice, "id" | "workspaceId" | "amount">;
+ 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,
+ invoiceId: invoice.id,
},
data: {
status: "pending",
@@ -149,7 +177,7 @@ export async function chargeFailed(event: Stripe.Event) {
name: workspace.programs[0].name,
},
payout: {
- amount,
+ amount: charge.amount,
...(chargedFailureFee && {
failureFee: PAYOUT_FAILURE_FEE_CENTS,
cardLast4,
@@ -175,3 +203,15 @@ export async function chargeFailed(event: Stripe.Event) {
})(),
);
}
+
+async function processRenewalInvoice({
+ invoice,
+ charge,
+}: {
+ invoice: Pick<Invoice, "id">;
+ charge: Stripe.Charge;
+}) {
+ // TODO:
+ // Schedule another charge in 3 days (total 3 charges) using qstash
+ // Send email to the user
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
index 307cb513b5..0a44912f34 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
@@ -1,51 +1,71 @@
import { qstash } from "@/lib/cron";
import { prisma } from "@dub/prisma";
+import { Invoice } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import Stripe from "stripe";
export async function chargeSucceeded(event: Stripe.Event) {
const charge = event.data.object as Stripe.Charge;
- const { id: chargeId, receipt_url, transfer_group, payment_intent } = charge;
+ const { transfer_group: invoiceId } = charge;
- if (!transfer_group) {
+ if (!invoiceId) {
console.log("No transfer group found, skipping...");
return;
}
- console.log({ chargeId, receipt_url, transfer_group });
-
const invoice = await prisma.invoice.findUnique({
where: {
- id: transfer_group,
+ id: invoiceId,
},
- include: {
- payouts: {
- where: {
- status: {
- not: "completed",
- },
- },
- include: {
- program: true,
- partner: true,
- },
- },
+ select: {
+ id: true,
+ status: true,
+ type: true,
},
});
if (!invoice) {
- console.log(`Invoice with transfer group ${transfer_group} not found.`);
+ console.log(`Invoice with transfer group ${invoiceId} not found.`);
return;
}
if (invoice.status === "completed") {
- console.log("Invoice already completed, skipping...");
+ console.log(`Invoice ${invoice.id} already completed, skipping...`);
return;
}
- if (invoice.payouts.length === 0) {
- console.log("No payouts found with status not completed, skipping...");
+ if (invoice.type === "partnerPayout") {
+ await processPayoutInvoice({ invoice, charge });
+ } else if (invoice.type === "domainRenewal") {
+ await processRenewalInvoice({ invoice, charge });
+ }
+}
+
+async function processPayoutInvoice({
+ invoice,
+ charge,
+}: {
+ invoice: Pick<Invoice, "id">;
+ charge: Stripe.Charge;
+}) {
+ const payouts = await prisma.payout.findMany({
+ where: {
+ invoiceId: invoice.id,
+ status: {
+ not: "completed",
+ },
+ },
+ include: {
+ program: true,
+ partner: true,
+ },
+ });
+
+ if (payouts.length === 0) {
+ console.log(
+ `No payouts found with status not completed for invoice ${invoice.id}, skipping...`,
+ );
return;
}
@@ -54,7 +74,7 @@ export async function chargeSucceeded(event: Stripe.Event) {
id: invoice.id,
},
data: {
- receiptUrl: receipt_url,
+ receiptUrl: charge.receipt_url,
status: "completed",
paidAt: new Date(),
stripeChargeMetadata: JSON.parse(JSON.stringify(charge)),
@@ -74,3 +94,17 @@ export async function chargeSucceeded(event: Stripe.Event) {
console.error("Error sending message to Qstash", qstashResponse);
}
}
+
+async function processRenewalInvoice({
+ invoice,
+ charge,
+}: {
+ invoice: Pick<Invoice, "id">;
+ charge: Stripe.Charge;
+}) {
+ // TODO:
+ // Find all domains associated with the invoice
+ // Update the domains with the new expiration date
+ // set domain's renew_option to "auto" on Dynadot
+ // Send email to the user
+}
diff --git a/packages/prisma/schema/domain.prisma b/packages/prisma/schema/domain.prisma
index e8e251abe7..2f0dc2bd62 100644
--- a/packages/prisma/schema/domain.prisma
+++ b/packages/prisma/schema/domain.prisma
@@ -32,7 +32,7 @@ model RegisteredDomain {
domainId String? @unique
invoiceId String?
autoRenewalDisabledAt DateTime?
- renewalFee Int @default(0)
+ renewalFee Int @default(1200) // $12
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt