Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

⏱️ Delay the subscription feedback email and store queued email kind as text (#3536)

Luke Vellabf497183e6f7
diff --git a/apps/web/src/emails/queue.ts b/apps/web/src/emails/queue.ts
index 6ded85b40..0b0513272 100644
--- a/apps/web/src/emails/queue.ts
+++ b/apps/web/src/emails/queue.ts
@@ -4,6 +4,7 @@ import { createLogger } from "@rallly/logger";
import { Effect, Layer } from "effect";
import { after } from "next/server";
import { env } from "@/env";
+import { sendSubscriptionFeedbackEmail } from "@/features/billing/webhook/mutations";
import {
QUEUED_EMAIL_BATCH_SIZE,
QUEUED_EMAIL_IMMEDIATE_BATCH_SIZE,
@@ -30,6 +31,7 @@ const queuedEmailLayer = Layer.mergeAll(
QueuedEmailHandlers.of({
scheduled_event_invite: sendScheduledEventInviteEmail,
review_request: sendReviewRequest,
+ subscription_feedback: sendSubscriptionFeedbackEmail,
}),
),
SendRateLimiter.layer,
diff --git a/apps/web/src/features/billing/constants.ts b/apps/web/src/features/billing/constants.ts
index 1970bd878..063332d87 100644
--- a/apps/web/src/features/billing/constants.ts
+++ b/apps/web/src/features/billing/constants.ts
@@ -10,6 +10,10 @@ export { PLAN_NAMES } from "@rallly/billing/pricing";
// Flash set by /api/stripe/return after a portal flow; value is the flow name.
export const BILLING_FLASH_KEY = "billing";
+// Long enough that the founder's note doesn't arrive alongside the Stripe
+// receipt and read as part of it
+export const subscriptionFeedbackEmailDelayMs = 30 * 60_000;
+
export const CANCELLATION_COMMENT_MAX_LENGTH = 500;
// How many polls a free organizer can have open at once in a space. Pro has
diff --git a/apps/web/src/features/billing/data.ts b/apps/web/src/features/billing/data.ts
index 38f379fad..cc5739e89 100644
--- a/apps/web/src/features/billing/data.ts
+++ b/apps/web/src/features/billing/data.ts
@@ -75,3 +75,16 @@ export async function getPaymentMethods(userId: string) {
};
});
}
+
+/** What the subscription feedback email needs to know when it is sent. */
+export async function getSubscriptionFeedbackRecipient(subscriptionId: string) {
+ return prisma.subscription.findUnique({
+ where: { id: subscriptionId },
+ select: {
+ active: true,
+ user: {
+ select: { email: true, banned: true, deletedAt: true },
+ },
+ },
+ });
+}
diff --git a/apps/web/src/features/billing/webhook/mutations.ts b/apps/web/src/features/billing/webhook/mutations.ts
index da5494d5d..84a00ad5d 100644
--- a/apps/web/src/features/billing/webhook/mutations.ts
+++ b/apps/web/src/features/billing/webhook/mutations.ts
@@ -6,9 +6,11 @@ import { prisma } from "@rallly/database";
import { sendRawEmail } from "@rallly/emails";
import { sendLicenseKeyEmail } from "@rallly/emails/templates/license-key";
import * as Sentry from "@sentry/nextjs";
-import { after } from "next/server";
+import { Effect } from "effect";
import { getInstanceBranding } from "@/emails/branding";
import { env } from "@/env";
+import { subscriptionFeedbackEmailDelayMs } from "@/features/billing/constants";
+import { getSubscriptionFeedbackRecipient } from "@/features/billing/data";
import {
cancellationReasonSchema,
customerMetadataSchema,
@@ -20,6 +22,11 @@ import {
isSubscriptionActive,
toDate,
} from "@/features/billing/webhook/utils";
+import { queueEmails } from "@/features/email-queue/mutations";
+import {
+ QueuedEmailFailed,
+ QueuedEmailSkipped,
+} from "@/features/email-queue/service";
import { licenseManager } from "@/features/licensing/mutations";
import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";
import { spaceExists } from "@/features/space/data";
@@ -302,6 +309,22 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
},
});
+ if (isActive) {
+ // Stripe can deliver the same event more than once
+ const alreadyQueued = await tx.queuedEmail.count({
+ where: { kind: "subscription_feedback", batchId: subscription.id },
+ });
+ if (alreadyQueued === 0) {
+ await queueEmails(tx, {
+ kind: "subscription_feedback",
+ userId,
+ batchId: subscription.id,
+ subjectIds: [subscription.id],
+ sendAfter: new Date(Date.now() + subscriptionFeedbackEmailDelayMs),
+ });
+ }
+ }
+
return syncSpaceTier(tx, spaceId);
});
@@ -327,30 +350,6 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
space: spaceId,
},
});
-
- if (isActive) {
- after(async () => {
- const user = await prisma.user.findUnique({
- where: { id: userId },
- select: { email: true, name: true },
- });
-
- if (user) {
- await sendRawEmail({
- to: user.email,
- from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
- subject: "Thanks for subscribing to Rallly Pro",
- text: [
- "Hey there,",
- "Thanks so much for subscribing to Rallly Pro! I really appreciate your support.",
- "I'd love to learn more about how you're using Rallly. What kind of events are you scheduling? Are there any features you wish Rallly had?",
- "Just hit reply and let me know. I read every response and it helps shape what we build next.",
- "Luke\nFounder, Rallly",
- ].join("\n\n"),
- });
- }
- });
- }
}
async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
@@ -657,3 +656,53 @@ export async function handleStripeWebhookEvent(event: Stripe.Event) {
return { handled: true };
}
+
+const failWith = (message: string) => () => new QueuedEmailFailed({ message });
+
+/**
+ * Sends the founder's feedback request queued when a subscription starts.
+ * The subject is the subscription, so one cancelled before the send gets no
+ * email.
+ */
+export const sendSubscriptionFeedbackEmail = Effect.fn(
+ "billing.sendSubscriptionFeedbackEmail",
+)(function* ({ subjectId }: { id: string; subjectId: string }) {
+ const subscription = yield* Effect.tryPromise({
+ try: () => getSubscriptionFeedbackRecipient(subjectId),
+ catch: failWith("Failed to load the subscription"),
+ });
+ if (!subscription?.active) {
+ return yield* new QueuedEmailSkipped({
+ reason: "Subscription no longer active",
+ });
+ }
+ const { user } = subscription;
+ if (user.deletedAt) {
+ return yield* new QueuedEmailSkipped({ reason: "User no longer exists" });
+ }
+ if (user.banned) {
+ return yield* new QueuedEmailSkipped({ reason: "User is banned" });
+ }
+
+ // The mailer logs and swallows transport failures, so its result is what
+ // tells a sent email from a failed one.
+ const sent = yield* Effect.tryPromise({
+ try: () =>
+ sendRawEmail({
+ to: user.email,
+ from: { name: "Luke from Rallly", address: env.SUPPORT_EMAIL },
+ subject: "Thanks for subscribing to Rallly Pro",
+ text: [
+ "Hey there,",
+ "Thanks so much for subscribing to Rallly Pro! I really appreciate your support.",
+ "I'd love to learn more about how you're using Rallly. What kind of events are you scheduling? Are there any features you wish Rallly had?",
+ "Just hit reply and let me know. I read every response and it helps shape what we build next.",
+ "Luke\nFounder, Rallly",
+ ].join("\n\n"),
+ }),
+ catch: failWith("Failed to send the subscription feedback email"),
+ });
+ if (!sent) {
+ return yield* new QueuedEmailFailed({ message: "Transport failed" });
+ }
+});
diff --git a/apps/web/src/features/email-queue/constants.ts b/apps/web/src/features/email-queue/constants.ts
index 8dbc87722..a563e3e2b 100644
--- a/apps/web/src/features/email-queue/constants.ts
+++ b/apps/web/src/features/email-queue/constants.ts
@@ -1,6 +1,7 @@
export const QUEUED_EMAIL_KINDS = [
"scheduled_event_invite",
"review_request",
+ "subscription_feedback",
] as const;
/**
diff --git a/apps/web/src/features/email-queue/mutations.test.ts b/apps/web/src/features/email-queue/mutations.test.ts
index fabda4889..6745184a9 100644
--- a/apps/web/src/features/email-queue/mutations.test.ts
+++ b/apps/web/src/features/email-queue/mutations.test.ts
@@ -28,6 +28,7 @@ function attemptWith(handler: QueuedEmailHandler, banned = false) {
QueuedEmailHandlers.of({
scheduled_event_invite: handler,
review_request: handler,
+ subscription_feedback: handler,
}),
),
),
diff --git a/apps/web/src/features/email-queue/mutations.ts b/apps/web/src/features/email-queue/mutations.ts
index 3a71c5994..4fc0aa3e2 100644
--- a/apps/web/src/features/email-queue/mutations.ts
+++ b/apps/web/src/features/email-queue/mutations.ts
@@ -19,6 +19,7 @@ import {
import { listPurgeableQueuedEmailIds, listQueuedEmails } from "./data";
import { QueuedEmailHandlers, SendRateLimiter } from "./service";
import type { QueuedEmailKind } from "./types";
+import { isQueuedEmailKind } from "./utils";
const logger = createLogger("email-queue");
@@ -146,7 +147,7 @@ export const claimQueuedEmails = Effect.fn("emailQueue.claimQueuedEmails")(
WHERE id IN (
SELECT id FROM queued_emails
WHERE status = 'pending'
- AND kind::text = ANY(${[...QUEUED_EMAIL_KINDS]})
+ AND kind = ANY(${[...QUEUED_EMAIL_KINDS]})
AND attempts < ${MAX_QUEUED_EMAIL_ATTEMPTS}
AND (send_after IS NULL OR send_after <= ${now})
AND (claimed_at IS NULL OR claimed_at < ${staleBefore})
@@ -190,6 +191,14 @@ export const attemptQueuedEmail = Effect.fn("emailQueue.attemptQueuedEmail")(
reason: "Queued by a banned account",
} satisfies QueuedEmailAttempt as QueuedEmailAttempt;
}
+ // The claim only takes known kinds, so this guards the type, not the data
+ if (!isQueuedEmailKind(email.kind)) {
+ return {
+ ok: false,
+ skip: false,
+ error: `Unknown kind: ${email.kind}`,
+ } satisfies QueuedEmailAttempt as QueuedEmailAttempt;
+ }
const handlers = yield* QueuedEmailHandlers;
yield* handlers[email.kind]({ id: email.id, subjectId: email.subjectId });
return { ok: true } satisfies QueuedEmailAttempt as QueuedEmailAttempt;
diff --git a/apps/web/src/features/email-queue/utils.ts b/apps/web/src/features/email-queue/utils.ts
new file mode 100644
index 000000000..96ad4b441
--- /dev/null
+++ b/apps/web/src/features/email-queue/utils.ts
@@ -0,0 +1,6 @@
+import { QUEUED_EMAIL_KINDS } from "./constants";
+import type { QueuedEmailKind } from "./types";
+
+export function isQueuedEmailKind(kind: string): kind is QueuedEmailKind {
+ return (QUEUED_EMAIL_KINDS as readonly string[]).includes(kind);
+}
diff --git a/packages/database/prisma/migrations/20261015120000_queued_email_kind_to_text/migration.sql b/packages/database/prisma/migrations/20261015120000_queued_email_kind_to_text/migration.sql
new file mode 100644
index 000000000..84598d073
--- /dev/null
+++ b/packages/database/prisma/migrations/20261015120000_queued_email_kind_to_text/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "queued_emails" ALTER COLUMN "kind" SET DATA TYPE TEXT USING "kind"::text;
+
+-- DropEnum
+DROP TYPE "queued_email_kind";
diff --git a/packages/database/prisma/models/email-queue.prisma b/packages/database/prisma/models/email-queue.prisma
index b227401d4..d9e913013 100644
--- a/packages/database/prisma/models/email-queue.prisma
+++ b/packages/database/prisma/models/email-queue.prisma
@@ -1,10 +1,3 @@
-enum QueuedEmailKind {
- scheduled_event_invite
- review_request
-
- @@map("queued_email_kind")
-}
-
enum QueuedEmailStatus {
pending
sent
@@ -18,7 +11,9 @@ enum QueuedEmailStatus {
/// email is built when it is sent, from the row its subject points at.
model QueuedEmail {
id String @id @default(cuid())
- kind QueuedEmailKind
+ /// Which handler builds the email. A string rather than an enum so a new
+ /// kind needs no migration; the claim only takes kinds the build knows.
+ kind String
/// The row the email is about, interpreted by the kind. Not a foreign key:
/// kinds point at different tables, and a subject deleted before the send
/// makes its handler skip the email.