Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Add subscription renewal reminder email
Cursor Agent6e8a6f9cdd69
diff --git a/components/emails/subscription-renewal-reminder.tsx b/components/emails/subscription-renewal-reminder.tsxnew file mode 100644index 00000000..bcc8f394--- /dev/null+++ b/components/emails/subscription-renewal-reminder.tsx@@ -0,0 +1,59 @@+import React from "react";++import {+ Body,+ Head,+ Html,+ Preview,+ Tailwind,+ Text,+} from "@react-email/components";++interface SubscriptionRenewalReminderEmailProps {+ customerName: string | null;+ renewalDate: string;+ amount: string;+ currency: string;+}++const SubscriptionRenewalReminderEmail = ({+ customerName,+ renewalDate,+ amount,+ currency,+}: SubscriptionRenewalReminderEmailProps) => {+ return (+ <Html>+ <Head />+ <Preview>Is your payment information up to date?</Preview>+ <Tailwind>+ <Body className="font-sans text-sm">+ <Text className="font-bold">+ Is your payment information up to date?+ </Text>+ <Text>Hi{customerName && ` ${customerName}`},</Text>+ <Text>+ Another year has come and gone, which means your annual Papermark+ subscription will automatically renew on {renewalDate}.+ </Text>+ <Text>+ We know many things can change in a year, so if you could make sure+ the payment method listed on your account is up to date, that would+ be dandy.+ </Text>+ <Text>+ Your subscription will renew for {amount} {currency.toUpperCase()}.+ </Text>+ <Text>+ If you need to update your billing details or have any questions,+ please visit your account settings.+ </Text>+ <Text>Best regards,</Text>+ <Text>The Papermark Team</Text>+ </Body>+ </Tailwind>+ </Html>+ );+};++export default SubscriptionRenewalReminderEmail;diff --git a/ee/stripe/webhooks/invoice-upcoming.ts b/ee/stripe/webhooks/invoice-upcoming.tsnew file mode 100644index 00000000..0a063959--- /dev/null+++ b/ee/stripe/webhooks/invoice-upcoming.ts@@ -0,0 +1,98 @@+import { tasks } from "@trigger.dev/sdk/v3";+import Stripe from "stripe";++import { sendRenewalReminderEmailTask } from "@/lib/trigger/send-renewal-reminder";+import { log } from "@/lib/utils";++export async function invoiceUpcoming(event: Stripe.Event) {+ const invoice = event.data.object as Stripe.Invoice;++ // Only process invoices for yearly renewals+ const lineItems = invoice.lines.data;+ if (!lineItems || lineItems.length === 0) {+ await log({+ message: "No line items found in invoice.upcoming event",+ type: "info",+ });+ return;+ }++ // Check if this is a yearly subscription+ const hasYearlyPlan = lineItems.some((item) => {+ if (item.price && item.price.recurring) {+ return (+ item.price.recurring.interval === "year" ||+ (item.price.recurring.interval === "month" &&+ item.price.recurring.interval_count === 12)+ );+ }+ return false;+ });++ if (!hasYearlyPlan) {+ await log({+ message: "Invoice is not for yearly renewal, skipping reminder email",+ type: "info",+ });+ return;+ }++ const customerEmail = invoice.customer_email;+ const customerName = invoice.customer_name;++ if (!customerEmail) {+ await log({+ message: "No customer email found in invoice.upcoming event",+ type: "error",+ });+ return;+ }++ // Calculate renewal date (period_end is when the invoice will be charged)+ const renewalTimestamp = invoice.period_end;+ const renewalDate = new Date(renewalTimestamp * 1000);+ const formattedRenewalDate = renewalDate.toLocaleDateString("en-US", {+ year: "numeric",+ month: "long",+ day: "numeric",+ });++ // Format amount (convert from cents to dollars/euros)+ const amount = (invoice.amount_due / 100).toFixed(2);+ const currency = invoice.currency;++ // Calculate delay: webhook arrives ~7 days before, we want to send 3 days before+ // So we delay by 4 days+ const delayInMs = 4 * 24 * 60 * 60 * 1000; // 4 days in milliseconds+ const scheduledTime = new Date(Date.now() + delayInMs);++ try {+ // Schedule the task to run in 4 days+ const handle = await tasks.trigger(+ sendRenewalReminderEmailTask.id,+ {+ customerEmail,+ customerName,+ renewalDate: formattedRenewalDate,+ amount,+ currency,+ },+ {+ delay: delayInMs,+ },+ );++ await log({+ message: `Scheduled renewal reminder email for ${customerEmail} to be sent on ${scheduledTime.toISOString()}. Renewal date: ${formattedRenewalDate}`,+ type: "info",+ });++ return handle;+ } catch (error) {+ await log({+ message: `Failed to schedule renewal reminder email for ${customerEmail}: ${error}`,+ type: "error",+ });+ throw error;+ }+}diff --git a/lib/emails/send-subscription-renewal-reminder.ts b/lib/emails/send-subscription-renewal-reminder.tsnew file mode 100644index 00000000..c2ff2dad--- /dev/null+++ b/lib/emails/send-subscription-renewal-reminder.ts@@ -0,0 +1,34 @@+import { sendEmail } from "@/lib/resend";++import SubscriptionRenewalReminderEmail from "@/components/emails/subscription-renewal-reminder";++export const sendSubscriptionRenewalReminderEmail = async (params: {+ customerName: string | null;+ customerEmail: string;+ renewalDate: string;+ amount: string;+ currency: string;+}) => {+ const { customerName, customerEmail, renewalDate, amount, currency } =+ params;++ const emailTemplate = SubscriptionRenewalReminderEmail({+ customerName,+ renewalDate,+ amount,+ currency,+ });++ try {+ await sendEmail({+ to: customerEmail,+ subject: "Your Papermark subscription renews soon",+ react: emailTemplate,+ system: true,+ test: process.env.NODE_ENV === "development",+ });+ } catch (e) {+ console.error("Error sending subscription renewal reminder email:", e);+ throw e;+ }+};diff --git a/lib/trigger/send-renewal-reminder.ts b/lib/trigger/send-renewal-reminder.tsnew file mode 100644index 00000000..1089e793--- /dev/null+++ b/lib/trigger/send-renewal-reminder.ts@@ -0,0 +1,40 @@+import { logger, task } from "@trigger.dev/sdk/v3";++import { sendSubscriptionRenewalReminderEmail } from "@/lib/emails/send-subscription-renewal-reminder";++export const sendRenewalReminderEmailTask = task({+ id: "send-renewal-reminder-email",+ retry: { maxAttempts: 3 },+ run: async (payload: {+ customerEmail: string;+ customerName: string | null;+ renewalDate: string;+ amount: string;+ currency: string;+ }) => {+ try {+ logger.info("Sending renewal reminder email", {+ to: payload.customerEmail,+ renewalDate: payload.renewalDate,+ });++ await sendSubscriptionRenewalReminderEmail({+ customerEmail: payload.customerEmail,+ customerName: payload.customerName,+ renewalDate: payload.renewalDate,+ amount: payload.amount,+ currency: payload.currency,+ });++ logger.info("Renewal reminder email sent successfully", {+ to: payload.customerEmail,+ });+ } catch (error) {+ logger.error("Error sending renewal reminder email", {+ error,+ customerEmail: payload.customerEmail,+ });+ throw error;+ }+ },+});diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex 754d18f1..d3849373 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -5,6 +5,7 @@ import { stripeInstance } from "@/ee/stripe";import { checkoutSessionCompleted } from "@/ee/stripe/webhooks/checkout-session-completed";import { customerSubscriptionDeleted } from "@/ee/stripe/webhooks/customer-subscription-deleted";import { customerSubsciptionUpdated } from "@/ee/stripe/webhooks/customer-subscription-updated";+import { invoiceUpcoming } from "@/ee/stripe/webhooks/invoice-upcoming";import { Readable } from "node:stream";import type Stripe from "stripe";@@ -32,6 +33,7 @@ const relevantEvents = new Set(["customer.subscription.updated","customer.subscription.deleted","payment_intent.payment_failed",+ "invoice.upcoming",]);export default async function webhookHandler(@@ -71,6 +73,9 @@ export default async function webhookHandler(case "payment_intent.payment_failed":await processPaymentFailure(event);break;+ case "invoice.upcoming":+ await invoiceUpcoming(event);+ break;}} catch (error) {await log({