Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(stripe-payment-bot): post subscription cancellations to Macro channels (#5824)
teod165f666f71e
diff --git a/services/bots/stripe-payment-bot/README.md b/services/bots/stripe-payment-bot/README.mdindex 06f12ef0ac..5ebcafe47a 100644--- a/services/bots/stripe-payment-bot/README.md+++ b/services/bots/stripe-payment-bot/README.md@@ -1,19 +1,20 @@# stripe-payment-bot-Posts to every Macro channel containing the bot when a new Stripe payment is-received. It can be deployed from any Cloudflare account; it has no dependency-on a Macro-owned Worker or domain.+Posts to every Macro channel containing the bot when Stripe reports a new+payment or a subscription cancellation. It can be deployed from any Cloudflare+account; it has no dependency on a Macro-owned Worker or domain.-The bot handles paid Checkout sessions, delayed payment methods, and the first-successful invoice after a free trial. Unpaid sessions and unrelated Stripe-events are acknowledged and ignored.+The bot handles paid Checkout sessions, delayed payment methods, the first+successful invoice after a free trial, `customer.subscription.deleted`, and+`customer.subscription.updated` when `cancel_at_period_end` flips from false to+true. Unpaid sessions and unrelated Stripe events are acknowledged and ignored.## How it works```textStripe webhook ──POST /webhook──> Cloudflare Worker│ Stripe SDK verifies the signature- │ identify the first real payment+ │ map the event to a payment or cancellation▼Macro SDK → list the bot's channel memberships→ POST each channel's bot webhook@@ -55,8 +56,9 @@ printf '%s' 'https://your-storage-api.example.com' | \wrangler secret put MACRO_STORAGE_URL```-`STRIPE_API_KEY` can be a restricted key with read access to subscriptions; it-is only used to confirm that a paid invoice is the first one after a trial.+`STRIPE_API_KEY` can be a restricted key with read access to subscriptions and+customers. The Worker uses it to confirm that a paid invoice is the first one+after a trial, and to resolve customer name and email on cancellation events.Wrangler prints the URL assigned to the Worker in the deploying Cloudflareaccount. In Stripe Workbench, create a webhook destination pointing to:@@ -70,6 +72,8 @@ Subscribe it to these events:- `checkout.session.completed`- `checkout.session.async_payment_succeeded`- `invoice.paid`+- `customer.subscription.deleted`+- `customer.subscription.updated`Copy that destination's signing secret (`whsec_...`) into the Worker secretabove. Test-mode and live-mode webhook destinations have different signing@@ -87,7 +91,7 @@ Forward Stripe test events to the local server:```bashstripe listen \- --events checkout.session.completed,checkout.session.async_payment_succeeded,invoice.paid \+ --events checkout.session.completed,checkout.session.async_payment_succeeded,invoice.paid,customer.subscription.deleted,customer.subscription.updated \--forward-to localhost:8787/webhook```@@ -102,4 +106,5 @@ than adding a database solely for deduplication.```bashjust check+just test```diff --git a/services/bots/stripe-payment-bot/justfile b/services/bots/stripe-payment-bot/justfileindex 47fe76a7bf..95a3ba7359 100644--- a/services/bots/stripe-payment-bot/justfile+++ b/services/bots/stripe-payment-bot/justfile@@ -3,3 +3,6 @@ dev:check:bunx tsc --noEmit --project tsconfig.json++test:+ bun testdiff --git a/services/bots/stripe-payment-bot/package.json b/services/bots/stripe-payment-bot/package.jsonindex e9557d06c7..865c438238 100644--- a/services/bots/stripe-payment-bot/package.json+++ b/services/bots/stripe-payment-bot/package.json@@ -6,6 +6,7 @@"scripts": {"dev": "wrangler dev","check": "tsc --noEmit --project tsconfig.json",+ "test": "bun test","deploy": "wrangler deploy"},"dependencies": {diff --git a/services/bots/stripe-payment-bot/src/channel.ts b/services/bots/stripe-payment-bot/src/channel.tsindex 7132850217..90b9fd3460 100644--- a/services/bots/stripe-payment-bot/src/channel.ts+++ b/services/bots/stripe-payment-bot/src/channel.ts@@ -44,7 +44,7 @@ export function createChannelBroadcaster();if (failures.length > 0) {failures.forEach((failure) => {- console.error('Failed to post Stripe payment to a Macro channel', {+ console.error('Failed to post Stripe notification to a Macro channel', {error: failure.reason,});});@@ -53,7 +53,7 @@ export function createChannelBroadcaster();}- console.log('Posted Stripe payment notification', {+ console.log('Posted Stripe notification', {channelCount: channels.length,});};diff --git a/services/bots/stripe-payment-bot/src/notification.ts b/services/bots/stripe-payment-bot/src/notification.tsnew file mode 100644index 0000000000..348b122b0f--- /dev/null+++ b/services/bots/stripe-payment-bot/src/notification.ts@@ -0,0 +1,284 @@+import Stripe from 'stripe';++export type PaymentNotification = {+ kind: 'payment';+ amount: number;+ currency: string;+ customer: string;+ eventId: string;+ livemode: boolean;+ subscriptionId?: string;+};++export type CancellationNotification = {+ kind: 'cancellation';+ customer: string;+ eventId: string;+ livemode: boolean;+ subscriptionId: string;+ timing: 'scheduled' | 'ended';+ endsAt?: number;+ reason?: string;+ feedback?: string;+ comment?: string;+};++export type StripeNotification = PaymentNotification | CancellationNotification;++function customerId(+ customer: string | Stripe.Customer | Stripe.DeletedCustomer | null+): string | undefined {+ return typeof customer === 'string' ? customer : customer?.id;+}++function subscriptionId(+ subscription: string | Stripe.Subscription | null+): string | undefined {+ return typeof subscription === 'string' ? subscription : subscription?.id;+}++function customerLabel(+ name?: string | null,+ email?: string | null,+ fallback?: string | null+): string {+ if (email && name) return `${name} (${email})`;+ return email ?? name ?? fallback ?? 'Unknown customer';+}++function fromExpandedCustomer(+ customer: Stripe.Customer | Stripe.DeletedCustomer+): string {+ if ('deleted' in customer && customer.deleted) return customer.id;+ return customerLabel(customer.name, customer.email, customer.id);+}++async function resolveCustomer(+ stripe: Stripe,+ customer: string | Stripe.Customer | Stripe.DeletedCustomer | null+): Promise<string> {+ if (customer && typeof customer === 'object') {+ return fromExpandedCustomer(customer);+ }+ if (typeof customer === 'string') {+ const retrieved = await stripe.customers.retrieve(customer);+ return fromExpandedCustomer(retrieved);+ }+ return 'Unknown customer';+}++function humanize(value: string): string {+ return value.replace(/_/g, ' ');+}++function checkoutPayment(+ event:+ | Stripe.CheckoutSessionCompletedEvent+ | Stripe.CheckoutSessionAsyncPaymentSucceededEvent+): PaymentNotification | undefined {+ const session = event.data.object;+ if (+ session.payment_status !== 'paid' ||+ session.amount_total === null ||+ session.currency === null+ ) {+ return undefined;+ }++ const expandedCustomer =+ typeof session.customer === 'object' &&+ session.customer !== null &&+ !('deleted' in session.customer)+ ? session.customer+ : undefined;+ const email =+ session.customer_details?.email ??+ session.customer_email ??+ expandedCustomer?.email;+ const name = session.customer_details?.name ?? expandedCustomer?.name;++ return {+ kind: 'payment',+ amount: session.amount_total,+ currency: session.currency,+ customer: customerLabel(name, email, customerId(session.customer)),+ eventId: event.id,+ livemode: event.livemode,+ subscriptionId: subscriptionId(session.subscription),+ };+}++async function postTrialPayment(+ stripe: Stripe,+ event: Stripe.InvoicePaidEvent+): Promise<PaymentNotification | undefined> {+ const invoice = event.data.object;+ if (invoice.status !== 'paid' || invoice.amount_paid <= 0) return undefined;++ const legacyInvoice = invoice as Stripe.Invoice & {+ subscription?: string | Stripe.Subscription | null;+ };+ const subscriptionRef =+ invoice.parent?.subscription_details?.subscription ??+ legacyInvoice.subscription;+ if (!subscriptionRef) return undefined;++ const subscription =+ typeof subscriptionRef === 'string'+ ? await stripe.subscriptions.retrieve(subscriptionRef)+ : subscriptionRef;+ const trialEnd = subscription.trial_end;+ const fiveMinutes = 5 * 60;+ if (+ trialEnd === null ||+ trialEnd < invoice.period_start - fiveMinutes ||+ trialEnd > invoice.period_end + fiveMinutes+ ) {+ return undefined;+ }++ return {+ kind: 'payment',+ amount: invoice.amount_paid,+ currency: invoice.currency,+ customer: customerLabel(+ invoice.customer_name,+ invoice.customer_email,+ customerId(invoice.customer)+ ),+ eventId: event.id,+ livemode: event.livemode,+ subscriptionId: subscription.id,+ };+}++function cancellationDetails(subscription: Stripe.Subscription): {+ endsAt?: number;+ reason?: string;+ feedback?: string;+ comment?: string;+} {+ const details = subscription.cancellation_details;+ return {+ endsAt: subscription.cancel_at ?? undefined,+ reason: details?.reason ?? undefined,+ feedback: details?.feedback ?? undefined,+ comment: details?.comment ?? undefined,+ };+}++async function cancellationFromSubscription(+ stripe: Stripe,+ event:+ | Stripe.CustomerSubscriptionDeletedEvent+ | Stripe.CustomerSubscriptionUpdatedEvent,+ timing: CancellationNotification['timing']+): Promise<CancellationNotification> {+ const subscription = event.data.object;+ return {+ kind: 'cancellation',+ customer: await resolveCustomer(stripe, subscription.customer),+ eventId: event.id,+ livemode: event.livemode,+ subscriptionId: subscription.id,+ timing,+ ...cancellationDetails(subscription),+ };+}++function isNewlyScheduledCancel(+ event: Stripe.CustomerSubscriptionUpdatedEvent+): boolean {+ return (+ event.data.object.cancel_at_period_end &&+ event.data.previous_attributes?.cancel_at_period_end === false+ );+}++export async function notificationFromEvent(+ stripe: Stripe,+ event: Stripe.Event+): Promise<StripeNotification | undefined> {+ switch (event.type) {+ case 'checkout.session.completed':+ case 'checkout.session.async_payment_succeeded':+ return checkoutPayment(event);+ case 'invoice.paid':+ return postTrialPayment(stripe, event);+ case 'customer.subscription.deleted':+ return cancellationFromSubscription(stripe, event, 'ended');+ case 'customer.subscription.updated':+ if (!isNewlyScheduledCancel(event)) return undefined;+ return cancellationFromSubscription(stripe, event, 'scheduled');+ default:+ return undefined;+ }+}++function formatAmount(amount: number, currency: string): string {+ const code = currency.toUpperCase();+ const formatter = new Intl.NumberFormat('en-US', {+ style: 'currency',+ currency: code,+ });+ const fractionDigits = formatter.resolvedOptions().maximumFractionDigits ?? 2;+ return `${formatter.format(amount / 10 ** fractionDigits)} ${code}`;+}++function dashboardEventUrl(livemode: boolean, eventId: string): string {+ const prefix = livemode ? '' : 'test/';+ return `https://dashboard.stripe.com/${prefix}events/${eventId}`;+}++function formatUnixDate(seconds: number): string {+ return new Date(seconds * 1000).toISOString().slice(0, 10);+}++function formatPayment(payment: PaymentNotification): string {+ const lines = [+ '💸 New Stripe payment',+ `Customer: ${payment.customer}`,+ `Amount: ${formatAmount(payment.amount, payment.currency)}`,+ ];+ if (payment.subscriptionId) {+ lines.push(`Subscription: ${payment.subscriptionId}`);+ }+ lines.push(dashboardEventUrl(payment.livemode, payment.eventId));+ return lines.join('\n');+}++function formatCancellation(cancellation: CancellationNotification): string {+ const title =+ cancellation.timing === 'scheduled'+ ? '🚫 Stripe subscription cancellation scheduled'+ : '🚫 Stripe subscription canceled';+ const lines = [title, `Customer: ${cancellation.customer}`];+ if (cancellation.timing === 'scheduled' && cancellation.endsAt) {+ lines.push(`Ends: ${formatUnixDate(cancellation.endsAt)}`);+ }+ if (cancellation.reason) {+ lines.push(`Reason: ${humanize(cancellation.reason)}`);+ }+ if (cancellation.feedback) {+ lines.push(`Feedback: ${humanize(cancellation.feedback)}`);+ }+ if (cancellation.comment) {+ lines.push(`Comment: ${cancellation.comment}`);+ }+ lines.push(`Subscription: ${cancellation.subscriptionId}`);+ lines.push(dashboardEventUrl(cancellation.livemode, cancellation.eventId));+ return lines.join('\n');+}++export function formatNotification(notification: StripeNotification): string {+ switch (notification.kind) {+ case 'payment':+ return formatPayment(notification);+ case 'cancellation':+ return formatCancellation(notification);+ default: {+ const _exhaustive: never = notification;+ return _exhaustive;+ }+ }+}diff --git a/services/bots/stripe-payment-bot/src/worker.ts b/services/bots/stripe-payment-bot/src/worker.tsindex a2db2ab8ba..177d25552e 100644--- a/services/bots/stripe-payment-bot/src/worker.ts+++ b/services/bots/stripe-payment-bot/src/worker.ts@@ -1,6 +1,7 @@import Stripe from 'stripe';import type { Env as MacroEnv } from '../../../../packages/sdk/src/config';import { createChannelBroadcaster } from './channel';+import { formatNotification, notificationFromEvent } from './notification';type WorkerEnv = {MACRO_BOT_TOKEN: string;@@ -19,154 +20,8 @@ const REQUIRED_BINDINGS: readonly (keyof WorkerEnv)[] = [const MACRO_ENVIRONMENTS: readonly MacroEnv[] = ['dev', 'prod', 'local'];-type Payment = {- amount: number;- currency: string;- customer: string;- eventId: string;- livemode: boolean;- subscriptionId?: string;-};-const cryptoProvider = Stripe.createSubtleCryptoProvider();-function customerId(- customer: string | Stripe.Customer | Stripe.DeletedCustomer | null-): string | undefined {- return typeof customer === 'string' ? customer : customer?.id;-}--function subscriptionId(- subscription: string | Stripe.Subscription | null-): string | undefined {- return typeof subscription === 'string' ? subscription : subscription?.id;-}--function checkoutPayment(- event:- | Stripe.CheckoutSessionCompletedEvent- | Stripe.CheckoutSessionAsyncPaymentSucceededEvent-): Payment | undefined {- const session = event.data.object;- if (- session.payment_status !== 'paid' ||- session.amount_total === null ||- session.currency === null- ) {- return undefined;- }-- const expandedCustomer =- typeof session.customer === 'object' &&- session.customer !== null &&- !('deleted' in session.customer)- ? session.customer- : undefined;- const email =- session.customer_details?.email ??- session.customer_email ??- expandedCustomer?.email;- const name = session.customer_details?.name ?? expandedCustomer?.name;-- return {- amount: session.amount_total,- currency: session.currency,- customer:- email && name- ? `${name} (${email})`- : (email ?? name ?? customerId(session.customer) ?? 'Unknown customer'),- eventId: event.id,- livemode: event.livemode,- subscriptionId: subscriptionId(session.subscription),- };-}--async function postTrialPayment(- stripe: Stripe,- event: Stripe.InvoicePaidEvent-): Promise<Payment | undefined> {- const invoice = event.data.object;- if (invoice.status !== 'paid' || invoice.amount_paid <= 0) return undefined;-- const legacyInvoice = invoice as Stripe.Invoice & {- subscription?: string | Stripe.Subscription | null;- };- const subscriptionRef =- invoice.parent?.subscription_details?.subscription ??- legacyInvoice.subscription;- if (!subscriptionRef) return undefined;-- const subscription =- typeof subscriptionRef === 'string'- ? await stripe.subscriptions.retrieve(subscriptionRef)- : subscriptionRef;- const trialEnd = subscription.trial_end;- const fiveMinutes = 5 * 60;- if (- trialEnd === null ||- trialEnd < invoice.period_start - fiveMinutes ||- trialEnd > invoice.period_end + fiveMinutes- ) {- return undefined;- }-- return {- amount: invoice.amount_paid,- currency: invoice.currency,- customer:- invoice.customer_email && invoice.customer_name- ? `${invoice.customer_name} (${invoice.customer_email})`- : (invoice.customer_email ??- invoice.customer_name ??- customerId(invoice.customer) ??- 'Unknown customer'),- eventId: event.id,- livemode: event.livemode,- subscriptionId: subscription.id,- };-}--async function paymentFromEvent(- stripe: Stripe,- event: Stripe.Event-): Promise<Payment | undefined> {- switch (event.type) {- case 'checkout.session.completed':- case 'checkout.session.async_payment_succeeded':- return checkoutPayment(event);- case 'invoice.paid':- return postTrialPayment(stripe, event);- default:- return undefined;- }-}--function formatAmount(amount: number, currency: string): string {- const code = currency.toUpperCase();- const formatter = new Intl.NumberFormat('en-US', {- style: 'currency',- currency: code,- });- const fractionDigits = formatter.resolvedOptions().maximumFractionDigits ?? 2;- return `${formatter.format(amount / 10 ** fractionDigits)} ${code}`;-}--function formatPayment(payment: Payment): string {- const dashboardPrefix = payment.livemode ? '' : 'test/';- const lines = [- '💸 New Stripe payment',- `Customer: ${payment.customer}`,- `Amount: ${formatAmount(payment.amount, payment.currency)}`,- ];- if (payment.subscriptionId) {- lines.push(`Subscription: ${payment.subscriptionId}`);- }- lines.push(- `https://dashboard.stripe.com/${dashboardPrefix}events/${payment.eventId}`- );- return lines.join('\n');-}-function missingBindings(env: WorkerEnv): string[] {return REQUIRED_BINDINGS.filter((key) => !env[key]);}@@ -225,33 +80,34 @@ export default {return new Response('Invalid Stripe webhook', { status: 400 });}- let payment: Payment | undefined;+ let notification;try {- payment = await paymentFromEvent(stripe, event);+ notification = await notificationFromEvent(stripe, event);} catch (error) {- console.error('Failed to load Stripe payment details', error);- return new Response('Failed to load Stripe payment details', {+ console.error('Failed to load Stripe notification details', error);+ return new Response('Failed to load Stripe notification details', {status: 502,});}- if (!payment) return Response.json({ ok: true, ignored: true });+ if (!notification) return Response.json({ ok: true, ignored: true });try {await createChannelBroadcaster({botToken: env.MACRO_BOT_TOKEN,env: macroEnv,storageUrl: env.MACRO_STORAGE_URL,- })(formatPayment(payment));+ })(formatNotification(notification));} catch (error) {- console.error('Failed to post Stripe payment to Macro', error);- return new Response('Failed to post Stripe payment to Macro', {+ console.error('Failed to post Stripe notification to Macro', error);+ return new Response('Failed to post Stripe notification to Macro', {status: 502,});}- console.log('Posted Stripe payment', {- eventId: payment.eventId,- subscriptionId: payment.subscriptionId,+ console.log('Posted Stripe notification', {+ kind: notification.kind,+ eventId: notification.eventId,+ subscriptionId: notification.subscriptionId,});return Response.json({ ok: true });},diff --git a/services/bots/stripe-payment-bot/test/notification.test.ts b/services/bots/stripe-payment-bot/test/notification.test.tsnew file mode 100644index 0000000000..4578e5d50f--- /dev/null+++ b/services/bots/stripe-payment-bot/test/notification.test.ts@@ -0,0 +1,308 @@+import { describe, expect, mock, test } from 'bun:test';+import type Stripe from 'stripe';+import {+ formatNotification,+ notificationFromEvent,+ type StripeNotification,+} from '../src/notification';++function stripeStub(overrides?: {+ customer?: Stripe.Customer | Stripe.DeletedCustomer;+ subscription?: Stripe.Subscription;+}): Stripe {+ return {+ customers: {+ retrieve: mock(async () => {+ if (!overrides?.customer) {+ throw new Error('customers.retrieve should not be called');+ }+ return overrides.customer;+ }),+ },+ subscriptions: {+ retrieve: mock(async () => {+ if (!overrides?.subscription) {+ throw new Error('subscriptions.retrieve should not be called');+ }+ return overrides.subscription;+ }),+ },+ } as unknown as Stripe;+}++function checkoutEvent(+ overrides: Partial<Stripe.Checkout.Session> & {+ eventId?: string;+ livemode?: boolean;+ } = {}+): Stripe.CheckoutSessionCompletedEvent {+ const { eventId, livemode, ...session } = overrides;+ return {+ id: eventId ?? 'evt_checkout',+ livemode: livemode ?? true,+ type: 'checkout.session.completed',+ data: {+ object: {+ payment_status: 'paid',+ amount_total: 2000,+ currency: 'usd',+ customer: 'cus_123',+ customer_details: {+ email: '[email protected]',+ name: 'Ada Lovelace',+ },+ customer_email: null,+ subscription: 'sub_123',+ ...session,+ },+ },+ } as Stripe.CheckoutSessionCompletedEvent;+}++function invoicePaidEvent(+ overrides: Partial<Stripe.Invoice> & {+ eventId?: string;+ livemode?: boolean;+ } = {}+): Stripe.InvoicePaidEvent {+ const { eventId, livemode, ...invoice } = overrides;+ return {+ id: eventId ?? 'evt_invoice',+ livemode: livemode ?? true,+ type: 'invoice.paid',+ data: {+ object: {+ status: 'paid',+ amount_paid: 2000,+ currency: 'usd',+ customer: 'cus_123',+ customer_email: '[email protected]',+ customer_name: 'Ada Lovelace',+ period_start: 1_700_000_000,+ period_end: 1_700_086_400,+ parent: { subscription_details: { subscription: 'sub_123' } },+ ...invoice,+ },+ },+ } as Stripe.InvoicePaidEvent;+}++function subscriptionEvent(+ type: 'customer.subscription.deleted' | 'customer.subscription.updated',+ subscription: Partial<Stripe.Subscription>,+ previous?: Partial<Stripe.Subscription>+):+ | Stripe.CustomerSubscriptionDeletedEvent+ | Stripe.CustomerSubscriptionUpdatedEvent {+ return {+ id: type === 'customer.subscription.deleted' ? 'evt_deleted' : 'evt_updated',+ livemode: true,+ type,+ data: {+ object: {+ id: 'sub_123',+ customer: 'cus_123',+ cancel_at_period_end: false,+ cancel_at: null,+ cancellation_details: null,+ ...subscription,+ },+ previous_attributes: previous,+ },+ } as+ | Stripe.CustomerSubscriptionDeletedEvent+ | Stripe.CustomerSubscriptionUpdatedEvent;+}++const retrievedCustomer = {+ id: 'cus_123',+ name: 'Ada Lovelace',+ email: '[email protected]',+} as Stripe.Customer;++describe('notificationFromEvent', () => {+ test('maps a paid checkout session to a payment', async () => {+ const notification = await notificationFromEvent(+ stripeStub(),+ checkoutEvent()+ );+ expect(notification).toEqual({+ kind: 'payment',+ amount: 2000,+ currency: 'usd',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_checkout',+ livemode: true,+ subscriptionId: 'sub_123',+ });+ });++ test('ignores unpaid checkout sessions', async () => {+ const notification = await notificationFromEvent(+ stripeStub(),+ checkoutEvent({ payment_status: 'unpaid' })+ );+ expect(notification).toBeUndefined();+ });++ test('maps a first invoice after a trial to a payment', async () => {+ const notification = await notificationFromEvent(+ stripeStub({+ subscription: {+ id: 'sub_123',+ trial_end: 1_700_043_200,+ } as Stripe.Subscription,+ }),+ invoicePaidEvent()+ );+ expect(notification).toMatchObject({+ kind: 'payment',+ amount: 2000,+ customer: 'Ada Lovelace ([email protected])',+ subscriptionId: 'sub_123',+ });+ });++ test('ignores invoices that are not the first after a trial', async () => {+ const notification = await notificationFromEvent(+ stripeStub({+ subscription: {+ id: 'sub_123',+ trial_end: null,+ } as Stripe.Subscription,+ }),+ invoicePaidEvent()+ );+ expect(notification).toBeUndefined();+ });++ test('maps subscription.deleted to an ended cancellation', async () => {+ const notification = await notificationFromEvent(+ stripeStub({ customer: retrievedCustomer }),+ subscriptionEvent('customer.subscription.deleted', {+ cancellation_details: {+ comment: 'Moving to annual later',+ feedback: 'too_expensive',+ reason: 'cancellation_requested',+ },+ })+ );+ expect(notification).toEqual({+ kind: 'cancellation',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_deleted',+ livemode: true,+ subscriptionId: 'sub_123',+ timing: 'ended',+ reason: 'cancellation_requested',+ feedback: 'too_expensive',+ comment: 'Moving to annual later',+ });+ });++ test('maps cancel_at_period_end flipping on to a scheduled cancellation', async () => {+ const notification = await notificationFromEvent(+ stripeStub({ customer: retrievedCustomer }),+ subscriptionEvent(+ 'customer.subscription.updated',+ {+ cancel_at_period_end: true,+ cancel_at: 1_720_000_000,+ },+ { cancel_at_period_end: false }+ )+ );+ expect(notification).toEqual({+ kind: 'cancellation',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_updated',+ livemode: true,+ subscriptionId: 'sub_123',+ timing: 'scheduled',+ endsAt: 1_720_000_000,+ });+ });++ test('ignores subscription updates that are not a new cancel-at-period-end', async () => {+ const notification = await notificationFromEvent(+ stripeStub({ customer: retrievedCustomer }),+ subscriptionEvent(+ 'customer.subscription.updated',+ { cancel_at_period_end: true, cancel_at: 1_720_000_000 },+ { metadata: { plan: 'pro' } } as Partial<Stripe.Subscription>+ )+ );+ expect(notification).toBeUndefined();+ });+});++describe('formatNotification', () => {+ test('formats a payment with a dashboard link', () => {+ const payment: StripeNotification = {+ kind: 'payment',+ amount: 2000,+ currency: 'usd',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_checkout',+ livemode: true,+ subscriptionId: 'sub_123',+ };+ expect(formatNotification(payment)).toBe(+ [+ '💸 New Stripe payment',+ 'Customer: Ada Lovelace ([email protected])',+ 'Amount: $20.00 USD',+ 'Subscription: sub_123',+ 'https://dashboard.stripe.com/events/evt_checkout',+ ].join('\n')+ );+ });++ test('formats a scheduled cancellation', () => {+ const cancellation: StripeNotification = {+ kind: 'cancellation',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_updated',+ livemode: false,+ subscriptionId: 'sub_123',+ timing: 'scheduled',+ endsAt: 1_720_000_000,+ reason: 'cancellation_requested',+ };+ expect(formatNotification(cancellation)).toBe(+ [+ '🚫 Stripe subscription cancellation scheduled',+ 'Customer: Ada Lovelace ([email protected])',+ 'Ends: 2024-07-03',+ 'Reason: cancellation requested',+ 'Subscription: sub_123',+ 'https://dashboard.stripe.com/test/events/evt_updated',+ ].join('\n')+ );+ });++ test('formats an ended cancellation with feedback', () => {+ const cancellation: StripeNotification = {+ kind: 'cancellation',+ customer: 'Ada Lovelace ([email protected])',+ eventId: 'evt_deleted',+ livemode: true,+ subscriptionId: 'sub_123',+ timing: 'ended',+ reason: 'cancellation_requested',+ feedback: 'too_expensive',+ comment: 'Moving to annual later',+ };+ expect(formatNotification(cancellation)).toBe(+ [+ '🚫 Stripe subscription canceled',+ 'Customer: Ada Lovelace ([email protected])',+ 'Reason: cancellation requested',+ 'Feedback: too expensive',+ 'Comment: Moving to annual later',+ 'Subscription: sub_123',+ 'https://dashboard.stripe.com/events/evt_deleted',+ ].join('\n')+ );+ });+});diff --git a/services/bots/stripe-payment-bot/tsconfig.json b/services/bots/stripe-payment-bot/tsconfig.jsonindex e48a371e23..225377543a 100644--- a/services/bots/stripe-payment-bot/tsconfig.json+++ b/services/bots/stripe-payment-bot/tsconfig.json@@ -14,5 +14,5 @@"types": ["@types/node", "bun-types"]},"exclude": ["node_modules"],- "include": ["src"]+ "include": ["src", "test"]}