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 renewal payments API for domains and enhance invoice processing

Kiran K5b5e0bdac2f0
diff --git a/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts b/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts
new file mode 100644
index 0000000000..a882d0f36d
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts
@@ -0,0 +1,140 @@
+import { createId } from "@/lib/api/create-id";
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
+import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";
+import { prisma } from "@dub/prisma";
+import { log } from "@dub/utils";
+import { Invoice, Project, RegisteredDomain } from "@prisma/client";
+import { addDays, endOfDay, startOfDay } from "date-fns";
+import { NextResponse } from "next/server";
+
+export const dynamic = "force-dynamic";
+
+interface GroupedWorkspace {
+ workspace: Pick<Project, "id" | "stripeId" | "invoicePrefix">;
+ domains: Pick<RegisteredDomain, "id" | "slug" | "expiresAt" | "renewalFee">[];
+}
+
+// GET /api/cron/domains/renewal-payments
+export async function GET(req: Request) {
+ try {
+ await verifyVercelSignature(req);
+
+ const targetDate = addDays(new Date(), 14);
+
+ // Find all domains expiring in 14 days
+ const domains = await prisma.registeredDomain.findMany({
+ where: {
+ autoRenewalDisabledAt: null,
+ expiresAt: {
+ gte: startOfDay(targetDate),
+ lte: endOfDay(targetDate),
+ },
+ },
+ include: {
+ project: {
+ select: {
+ id: true,
+ stripeId: true,
+ invoicePrefix: true,
+ },
+ },
+ },
+ });
+
+ if (domains.length === 0) {
+ return NextResponse.json(
+ "No domains found expiring exactly 14 days from today.",
+ );
+ }
+
+ // Group domains by workspaceId
+ const groupedByWorkspace = domains.reduce(
+ (acc, domain) => {
+ const workspaceId = domain.projectId;
+
+ if (!acc[workspaceId]) {
+ acc[workspaceId] = {
+ workspace: domain.project,
+ domains: [],
+ };
+ }
+
+ acc[workspaceId].domains.push({
+ id: domain.id,
+ slug: domain.slug,
+ expiresAt: domain.expiresAt,
+ renewalFee: domain.renewalFee,
+ });
+
+ return acc;
+ },
+ {} as Record<string, GroupedWorkspace>,
+ );
+
+ const invoices: Invoice[] = [];
+
+ // Create invoice for each workspace + domains group
+ for (const workspaceId in groupedByWorkspace) {
+ const { workspace, domains } = groupedByWorkspace[workspaceId];
+
+ const totalInvoices = await prisma.invoice.count({
+ where: {
+ workspaceId: workspace.id,
+ },
+ });
+
+ const paddedNumber = String(totalInvoices + 1).padStart(4, "0");
+ const invoiceNumber = `${workspace.invoicePrefix}-${paddedNumber}`;
+ const totalAmount = domains.reduce(
+ (acc, domain) => acc + domain.renewalFee,
+ 0,
+ );
+
+ const invoice = await prisma.invoice.create({
+ data: {
+ id: createId({ prefix: "inv_" }),
+ workspaceId: workspace.id,
+ number: invoiceNumber,
+ type: "domainRenewal",
+ amount: totalAmount,
+ total: totalAmount,
+ registeredDomains: domains.map(({ slug }) => slug), // array of domain slugs
+ },
+ });
+
+ console.log(
+ `Invoice ${invoice.id} created for workspace ${workspace.id} to renew ${domains.length} domains.`,
+ );
+
+ invoices.push(invoice);
+ }
+
+ // Create payment intent for each invoice
+ for (const invoice of invoices) {
+ const { workspace } = groupedByWorkspace[invoice.workspaceId];
+
+ if (!workspace.stripeId) {
+ console.log(`Workspace ${workspace.id} has no stripeId, skipping...`);
+ continue;
+ }
+
+ await createPaymentIntent({
+ stripeId: workspace.stripeId!,
+ amount: invoice.total,
+ invoiceId: invoice.id,
+ statementDescriptor: "Dub",
+ description: `Domain renewal invoice (${invoice.id})`,
+ });
+ }
+
+ 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/cron/invoices/retry-failed/route.ts b/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts
index e86c799de3..998251de02 100644
--- a/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts
+++ b/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts
@@ -71,7 +71,7 @@ export async function POST(req: Request) {
description: `Domain renewal invoice (${invoice.id})`,
});
- return new Response(`Retrying invoice ${invoice.id}...`);
+ return new Response(`Retrying invoice charge ${invoice.id}...`);
} catch (error) {
console.error(error);
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 0a44912f34..0dfe9949fc 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts
@@ -1,7 +1,9 @@
import { qstash } from "@/lib/cron";
+import { setRenewOption } from "@/lib/dynadot/set-renew-option";
import { prisma } from "@dub/prisma";
import { Invoice } from "@dub/prisma/client";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { addDays } from "date-fns";
import Stripe from "stripe";
export async function chargeSucceeded(event: Stripe.Event) {
@@ -14,15 +16,10 @@ export async function chargeSucceeded(event: Stripe.Event) {
return;
}
- const invoice = await prisma.invoice.findUnique({
+ let invoice = await prisma.invoice.findUnique({
where: {
id: invoiceId,
},
- select: {
- id: true,
- status: true,
- type: true,
- },
});
if (!invoice) {
@@ -35,20 +32,26 @@ export async function chargeSucceeded(event: Stripe.Event) {
return;
}
+ invoice = await prisma.invoice.update({
+ where: {
+ id: invoice.id,
+ },
+ data: {
+ receiptUrl: charge.receipt_url,
+ status: "completed",
+ paidAt: new Date(),
+ stripeChargeMetadata: JSON.parse(JSON.stringify(charge)),
+ },
+ });
+
if (invoice.type === "partnerPayout") {
- await processPayoutInvoice({ invoice, charge });
+ await processPayoutInvoice({ invoice });
} else if (invoice.type === "domainRenewal") {
- await processRenewalInvoice({ invoice, charge });
+ await processRenewalInvoice({ invoice });
}
}
-async function processPayoutInvoice({
- invoice,
- charge,
-}: {
- invoice: Pick<Invoice, "id">;
- charge: Stripe.Charge;
-}) {
+async function processPayoutInvoice({ invoice }: { invoice: Invoice }) {
const payouts = await prisma.payout.findMany({
where: {
invoiceId: invoice.id,
@@ -69,18 +72,6 @@ async function processPayoutInvoice({
return;
}
- await prisma.invoice.update({
- where: {
- id: invoice.id,
- },
- data: {
- receiptUrl: charge.receipt_url,
- status: "completed",
- paidAt: new Date(),
- stripeChargeMetadata: JSON.parse(JSON.stringify(charge)),
- },
- });
-
const qstashResponse = await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/payouts/charge-succeeded`,
body: {
@@ -95,16 +86,41 @@ async function processPayoutInvoice({
}
}
-async function processRenewalInvoice({
- invoice,
- charge,
-}: {
- invoice: Pick<Invoice, "id">;
- charge: Stripe.Charge;
-}) {
+async function processRenewalInvoice({ invoice }: { invoice: Invoice }) {
+ const domains = await prisma.registeredDomain.findMany({
+ where: {
+ slug: {
+ in: invoice.registeredDomains as string[],
+ },
+ },
+ });
+
+ if (domains.length === 0) {
+ console.log(`No domains found for invoice ${invoice.id}, skipping...`);
+ return;
+ }
+
+ await prisma.registeredDomain.updateMany({
+ where: {
+ id: {
+ in: domains.map(({ id }) => id),
+ },
+ },
+ data: {
+ expiresAt: addDays(new Date(), 365),
+ autoRenewalDisabledAt: null,
+ },
+ });
+
+ await Promise.allSettled(
+ domains.map((domain) =>
+ setRenewOption({
+ domain: domain.slug,
+ autoRenew: true,
+ }),
+ ),
+ );
+
// 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/apps/web/lib/stripe/create-payment-intent.ts b/apps/web/lib/stripe/create-payment-intent.ts
index e29553236d..4365fc8365 100644
--- a/apps/web/lib/stripe/create-payment-intent.ts
+++ b/apps/web/lib/stripe/create-payment-intent.ts
@@ -1,5 +1,5 @@
-import { log } from "@dub/utils";
-import { stripe } from ".";
+import { stripe } from "@/lib/stripe";
+import { currencyFormatter, log } from "@dub/utils";
export const createPaymentIntent = async ({
stripeId,
@@ -53,7 +53,7 @@ export const createPaymentIntent = async ({
});
console.log(
- `Payment intent ${paymentIntent.id} created for the invoice ${invoiceId}.`,
+ `Payment intent ${paymentIntent.id} created for invoice ${invoiceId} with amount ${currencyFormatter(paymentIntent.amount / 100)}`,
);
return paymentIntent;
diff --git a/apps/web/scripts/domain.ts b/apps/web/scripts/domain.ts
new file mode 100644
index 0000000000..4bc9b0f9c0
--- /dev/null
+++ b/apps/web/scripts/domain.ts
@@ -0,0 +1,28 @@
+import { createId } from "@/lib/api/create-id";
+import { prisma } from "@dub/prisma";
+import "dotenv-flow/config";
+
+async function main() {
+ const domain = await prisma.domain.create({
+ data: {
+ id: createId({ prefix: "dom_" }),
+ slug: "thomas.link",
+ verified: true,
+ projectId: "ws_1K1J9DXEDB3W9XT51Z2849M8Y",
+ },
+ });
+
+ const registerDomain = await prisma.registeredDomain.create({
+ data: {
+ id: createId({ prefix: "dom_" }),
+ slug: domain.slug,
+ projectId: domain.projectId!,
+ domainId: domain.id,
+ expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),
+ },
+ });
+
+ console.log(domain, registerDomain);
+}
+
+main();