Skip to content

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

🐛 Track subscription starts when payment completes, not at creation (#3542)

Luke Vella12ccdf5b941c
diff --git a/apps/web/src/features/billing/webhook/mutations.ts b/apps/web/src/features/billing/webhook/mutations.ts
index 84a00ad5d..8927536b3 100644
--- a/apps/web/src/features/billing/webhook/mutations.ts
+++ b/apps/web/src/features/billing/webhook/mutations.ts
@@ -19,6 +19,7 @@ import {
import { getStripe } from "@/features/billing/service";
import {
getSubscriptionDetails,
+ isActivationEvent,
isSubscriptionActive,
toDate,
} from "@/features/billing/webhook/utils";
@@ -69,6 +70,51 @@ async function syncSpaceTier(tx: Prisma.TransactionClient, spaceId: string) {
return tier;
}
+async function queueSubscriptionFeedbackEmail(
+ tx: Prisma.TransactionClient,
+ { userId, subscriptionId }: { userId: string; subscriptionId: string },
+) {
+ // Stripe can deliver the same event more than once
+ const alreadyQueued = await tx.queuedEmail.count({
+ where: { kind: "subscription_feedback", batchId: subscriptionId },
+ });
+ if (alreadyQueued === 0) {
+ await queueEmails(tx, {
+ kind: "subscription_feedback",
+ userId,
+ batchId: subscriptionId,
+ subjectIds: [subscriptionId],
+ sendAfter: new Date(Date.now() + subscriptionFeedbackEmailDelayMs),
+ });
+ }
+}
+
+function captureSubscriptionCreate({
+ userId,
+ spaceId,
+ interval,
+ tier,
+}: {
+ userId: string;
+ spaceId: string;
+ interval: string;
+ tier: string;
+}) {
+ posthog()?.capture({
+ distinctId: userId,
+ event: "subscription_create",
+ properties: {
+ interval,
+ $set: {
+ tier,
+ },
+ },
+ groups: {
+ space: spaceId,
+ },
+ });
+}
+
async function createOrUpdatePaymentMethod(
userId: string,
paymentMethod: Stripe.PaymentMethod,
@@ -229,6 +275,7 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
);
const isActive = isSubscriptionActive(subscription);
+ const activated = isActivationEvent(event);
const {
priceId,
currency,
@@ -309,20 +356,11 @@ 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 (activated) {
+ await queueSubscriptionFeedbackEmail(tx, {
+ userId,
+ subscriptionId: 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);
@@ -337,19 +375,9 @@ async function onCustomerSubscriptionCreated(event: Stripe.Event) {
},
});
- posthog()?.capture({
- distinctId: userId,
- event: "subscription_create",
- properties: {
- interval,
- $set: {
- tier,
- },
- },
- groups: {
- space: spaceId,
- },
- });
+ if (activated) {
+ captureSubscriptionCreate({ userId, spaceId, interval, tier });
+ }
}
async function onCustomerSubscriptionDeleted(event: Stripe.Event) {
@@ -459,6 +487,7 @@ async function onCustomerSubscriptionUpdated(event: Stripe.Event) {
);
const isActive = isSubscriptionActive(subscription);
+ const activated = isActivationEvent(event);
const {
priceId,
currency,
@@ -533,6 +562,13 @@ async function onCustomerSubscriptionUpdated(event: Stripe.Event) {
},
});
+ if (activated) {
+ await queueSubscriptionFeedbackEmail(tx, {
+ userId,
+ subscriptionId: subscription.id,
+ });
+ }
+
return syncSpaceTier(tx, spaceId);
});
@@ -559,6 +595,10 @@ async function onCustomerSubscriptionUpdated(event: Stripe.Event) {
space: spaceId,
},
});
+
+ if (activated) {
+ captureSubscriptionCreate({ userId, spaceId, interval, tier });
+ }
}
async function onPaymentMethodAttached(event: Stripe.Event) {
diff --git a/apps/web/src/features/billing/webhook/utils.test.ts b/apps/web/src/features/billing/webhook/utils.test.ts
new file mode 100644
index 000000000..a4cd88a5f
--- /dev/null
+++ b/apps/web/src/features/billing/webhook/utils.test.ts
@@ -0,0 +1,94 @@
+import type { Stripe } from "@rallly/billing";
+import { describe, expect, it } from "vitest";
+import { isActivationEvent } from "@/features/billing/webhook/utils";
+
+function subscriptionEvent({
+ type,
+ status,
+ previousStatus,
+}: {
+ type: "customer.subscription.created" | "customer.subscription.updated";
+ status: Stripe.Subscription.Status;
+ previousStatus?: Stripe.Subscription.Status;
+}) {
+ return {
+ type,
+ data: {
+ object: { status },
+ ...(previousStatus
+ ? { previous_attributes: { status: previousStatus } }
+ : {}),
+ },
+ } as unknown as Stripe.Event;
+}
+
+describe("isActivationEvent", () => {
+ it("treats a subscription created active as the start", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.created",
+ status: "active",
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("ignores a subscription created incomplete", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.created",
+ status: "incomplete",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("treats an update from incomplete to active as the start", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.updated",
+ status: "active",
+ previousStatus: "incomplete",
+ }),
+ ),
+ ).toBe(true);
+ });
+
+ it("ignores an incomplete subscription that expires", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.updated",
+ status: "incomplete_expired",
+ previousStatus: "incomplete",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("ignores updates that do not change the status", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.updated",
+ status: "active",
+ }),
+ ),
+ ).toBe(false);
+ });
+
+ it("ignores recovery from past due", () => {
+ expect(
+ isActivationEvent(
+ subscriptionEvent({
+ type: "customer.subscription.updated",
+ status: "active",
+ previousStatus: "past_due",
+ }),
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/billing/webhook/utils.ts b/apps/web/src/features/billing/webhook/utils.ts
index 4eb37b94a..81fc429ef 100644
--- a/apps/web/src/features/billing/webhook/utils.ts
+++ b/apps/web/src/features/billing/webhook/utils.ts
@@ -13,6 +13,31 @@ export function isSubscriptionActive(subscription: Stripe.Subscription) {
);
}
+/**
+ * Whether this event is the moment the subscription first became paid. A
+ * subscription whose first payment needs confirmation (3D Secure, delayed
+ * methods) is created `incomplete` and turns active in a later update event, so
+ * reading the status from the event payload rather than a refetch makes exactly
+ * one of the two events report the start.
+ */
+export function isActivationEvent(event: Stripe.Event) {
+ if (event.type === "customer.subscription.created") {
+ return isSubscriptionActive(event.data.object);
+ }
+
+ if (event.type === "customer.subscription.updated") {
+ const previous = event.data.previous_attributes as
+ | Partial<Stripe.Subscription>
+ | undefined;
+ return (
+ previous?.status === "incomplete" &&
+ isSubscriptionActive(event.data.object)
+ );
+ }
+
+ return false;
+}
+
export function getSubscriptionDetails(subscription: Stripe.Subscription) {
const subscriptionItem = subscription.items.data[0];