Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(settings): ask why before cancelling, and offer three days to put it right (#1312)
Cihan401558db6d8f
diff --git a/server/.env.example b/server/.env.exampleindex 79174fe81..f8edbf98e 100644--- a/server/.env.example+++ b/server/.env.example@@ -125,6 +125,12 @@ AI_VOLUME_MULTIPLIER=0.45# RESEND_API_KEY=re_...# RESEND_FROM_EMAIL="Ansvisor <[email protected]>"+# Where Settings › Billing › Cancel Subscription answers go (cloud only): why+# the customer cancels, or their request for three days first. Comma-separated;+# replies go to the customer. Sent through Resend above; empty = only kept in+# the cancellation_feedback table.+# Public URL of the web app, used for links in Daily Pulse emails and in the# action_task.sent webhook (Action Center → Send to webhook)# PUBLIC_APP_URL=https://app.example.comdiff --git a/server/src/lib/cancel-feedback.js b/server/src/lib/cancel-feedback.jsnew file mode 100644index 000000000..9685023ea--- /dev/null+++ b/server/src/lib/cancel-feedback.js@@ -0,0 +1,153 @@+import { z } from 'zod';++/**+ * Why a customer cancels, or asks for three days first (Settings › Billing ›+ * Cancel Subscription): the reasons they ticked and their message, both+ * optional, and what they chose —+ * - 'cancel': the plan is cancelled at the end of the period (the web app+ * has already done that through Stripe when this is sent);+ * - 'wait': the team acts within three days, and the plan stays as it is.+ *+ * E-mailed to the team (CANCEL_FEEDBACK_EMAILS) with replies going to the+ * customer, and kept in cancellation_feedback (00222).+ */++export const CANCEL_REASONS = [+ 'too_expensive',+ 'missing_feature',+ 'no_results',+ 'switching',+ 'temporary',+ 'other',+];++const REASON_LABELS = {+ too_expensive: 'Too expensive',+ missing_feature: 'Missing a feature they need',+ no_results: 'Not seeing results',+ switching: 'Switching to another tool',+ temporary: 'Only needed it for a while',+ other: 'Something else',+};++/** How long the team has to act when the customer waits. */+export const WAIT_DAYS = 3;++const DAY_MS = 86_400_000;++/** The subscription states with a plan to cancel or keep. */+export const SUBSCRIBED_STATUSES = ['active', 'trialing', 'past_due'];++/**+ * Whether waiting can be offered: the plan renews (or the trial ends) at+ * least a day after the team's answer is due, so the customer still has+ * time to cancel after hearing back. The web's canWait is the same rule.+ */+export function canWait(periodEnd, now = new Date()) {+ if (!periodEnd) return false;+ const end = new Date(periodEnd).getTime();+ return Number.isFinite(end) && end > now.getTime() + (WAIT_DAYS + 1) * DAY_MS;+}++/** Answers an organization can send in a day: room to change their mind, not a flood of e-mail. */+export const DAILY_LIMIT = 5;++export const MESSAGE_MAX = 2000;++export const cancelFeedbackSchema = z.object({+ reasons: z+ .array(z.enum(CANCEL_REASONS))+ .max(CANCEL_REASONS.length)+ .default([])+ .transform((reasons) => [...new Set(reasons)]),+ message: z.string().trim().max(MESSAGE_MAX).default(''),+ choice: z.enum(['cancel', 'wait']),+});++/** The team's addresses, from CANCEL_FEEDBACK_EMAILS (comma-separated). None: nothing is sent. */+export function feedbackRecipients(value = process.env.CANCEL_FEEDBACK_EMAILS) {+ return String(value ?? '')+ .split(',')+ .map((address) => address.trim())+ .filter(Boolean);+}++function escapeHtml(value) {+ return String(value ?? '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');+}++const formatDate = (date) =>+ new Date(date).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ timeZone: 'UTC',+ });++/**+ * The moment with its time, in UTC: "October 24, 2026, 17:00 UTC". The+ * customer sees the same moment in their own time zone, which can fall on+ * another day.+ */+const formatMoment = (date) => {+ const d = new Date(date);+ const time = `${String(d.getUTCHours()).padStart(2, '0')}:${String(d.getUTCMinutes()).padStart(2, '0')}`;+ return `${formatDate(d)}, ${time} UTC`;+};++/**+ * The e-mail to the team: what the customer chose in the subject, then who+ * they are, their plan, and what they said. Plain tables and inline styles,+ * for any mail client.+ */+export function buildCancelFeedbackEmail({ org, user, feedback, now = new Date() }) {+ const orgName = org?.name || 'An organization';+ const wait = feedback.choice === 'wait';+ const subject = wait+ ? `${orgName} asks us to act within ${WAIT_DAYS} days before cancelling`+ : `${orgName} cancelled their plan`;++ const who = user.name ? `${user.name} <${user.email ?? ''}>` : (user.email ?? 'Unknown');+ const rows = [+ ['Chose', wait ? `Wait ${WAIT_DAYS} days for us to act` : 'Cancel at the end of the period'],+ ...(wait ? [['Act by', formatMoment(now.getTime() + WAIT_DAYS * DAY_MS)]] : []),+ ['Organization', orgName],+ ['Plan', [org?.plan, org?.subscription_status].filter(Boolean).join(' · ') || '—'],+ ...(org?.subscription_ends_at+ ? [['Current period ends', formatDate(org.subscription_ends_at)]]+ : []),+ ['Who', user.role ? `${who} (${user.role})` : who],+ [+ 'Reasons',+ feedback.reasons.length+ ? feedback.reasons.map((reason) => REASON_LABELS[reason]).join(', ')+ : 'None ticked',+ ],+ ];++ const cell = 'padding:6px 12px 6px 0;vertical-align:top;font-size:14px;';+ const html = `<!doctype html>+<html><head><meta charset="utf-8"></head>+<body style="margin:0;padding:24px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#1C1A17;">+<p style="margin:0 0 16px;font-size:16px;font-weight:600;">${escapeHtml(subject)}</p>+<table role="presentation" cellpadding="0" cellspacing="0" style="border-collapse:collapse;">+${rows+ .map(+ ([label, value]) =>+ `<tr><td style="${cell}color:#464442;white-space:nowrap;">${escapeHtml(label)}</td><td style="${cell}">${escapeHtml(value)}</td></tr>`,+ )+ .join('\n')}+</table>+<p style="margin:16px 0 4px;font-size:14px;color:#464442;">Message</p>+<p style="margin:0;padding:12px;background:#F0EEEA;border-radius:8px;font-size:14px;white-space:pre-wrap;">${+ feedback.message ? escapeHtml(feedback.message) : '<em>No message</em>'+ }</p>+<p style="margin:16px 0 0;font-size:12px;color:#464442;">Reply to this e-mail to answer the customer.</p>+</body></html>`;++ return { subject, html };+}diff --git a/server/src/lib/cancel-feedback.test.js b/server/src/lib/cancel-feedback.test.jsnew file mode 100644index 000000000..4cb525163--- /dev/null+++ b/server/src/lib/cancel-feedback.test.js@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest';+import {+ buildCancelFeedbackEmail,+ canWait,+ cancelFeedbackSchema,+ feedbackRecipients,+} from './cancel-feedback.js';++/**+ * Why a customer cancels, or asks for three days first: what is accepted,+ * who it goes to, and the e-mail the team reads.+ */++describe('cancelFeedbackSchema', () => {+ it('takes the reasons once each and a trimmed message, both optional', () => {+ expect(+ cancelFeedbackSchema.parse({+ reasons: ['too_expensive', 'too_expensive', 'switching'],+ message: ' Too pricey for us. ',+ choice: 'cancel',+ }),+ ).toEqual({+ reasons: ['too_expensive', 'switching'],+ message: 'Too pricey for us.',+ choice: 'cancel',+ });+ expect(cancelFeedbackSchema.parse({ choice: 'wait' })).toEqual({+ reasons: [],+ message: '',+ choice: 'wait',+ });+ });++ it('refuses an unknown reason or choice, and a message over 2,000 characters', () => {+ expect(cancelFeedbackSchema.safeParse({ reasons: ['bored'], choice: 'cancel' }).success).toBe(+ false,+ );+ expect(cancelFeedbackSchema.safeParse({ choice: 'pause' }).success).toBe(false);+ expect(+ cancelFeedbackSchema.safeParse({ choice: 'cancel', message: 'x'.repeat(2001) }).success,+ ).toBe(false);+ });+});++describe('feedbackRecipients', () => {+ it('reads the comma-separated addresses, and none when unset', () => {+ expect(feedbackRecipients(' [email protected], [email protected] ,')).toEqual([+ '[email protected]',+ '[email protected]',+ ]);+ expect(feedbackRecipients('')).toEqual([]);+ });+});++describe('buildCancelFeedbackEmail', () => {+ const org = {+ name: 'Acme Coffee',+ plan: 'growth',+ subscription_status: 'active',+ subscription_ends_at: '2026-11-03T10:00:00Z',+ };+ const user = { name: 'Ada', email: '[email protected]', role: 'admin' };+ const now = new Date('2026-10-21T12:00:00Z');++ it('says in the subject that the customer waits, and by when to act', () => {+ const { subject, html } = buildCancelFeedbackEmail({+ org,+ user,+ feedback: { reasons: ['missing_feature'], message: 'We need Slack alerts.', choice: 'wait' },+ now,+ });+ expect(subject).toBe('Acme Coffee asks us to act within 3 days before cancelling');+ expect(html).toContain('Wait 3 days for us to act');+ // The moment to act by, with its time: the customer sees it in their own zone.+ expect(html).toContain('October 24, 2026, 12:00 UTC');+ expect(html).toContain('November 3, 2026');+ expect(html).toContain('growth · active');+ expect(html).toContain('Ada <[email protected]> (admin)');+ expect(html).toContain('Missing a feature they need');+ expect(html).toContain('We need Slack alerts.');+ });++ it('says the plan was cancelled, with no reasons or message given', () => {+ const { subject, html } = buildCancelFeedbackEmail({+ org,+ user,+ feedback: { reasons: [], message: '', choice: 'cancel' },+ now,+ });+ expect(subject).toBe('Acme Coffee cancelled their plan');+ expect(html).toContain('Cancel at the end of the period');+ expect(html).not.toContain('Act by');+ expect(html).toContain('None ticked');+ expect(html).toContain('No message');+ });++ it('escapes what the customer wrote', () => {+ const { html } = buildCancelFeedbackEmail({+ org: { ...org, name: '<b>Acme</b>' },+ user,+ feedback: { reasons: [], message: '<script>alert(1)</script>', choice: 'cancel' },+ now,+ });+ expect(html).not.toContain('<script>');+ expect(html).not.toContain('<b>Acme</b>');+ expect(html).toContain('<script>alert(1)</script>');+ });+});++describe('canWait', () => {+ const now = new Date('2026-10-21T12:00:00Z');+ it('offers three days only with a day to spare before the plan renews', () => {+ expect(canWait('2026-10-25T12:00:01Z', now)).toBe(true);+ expect(canWait('2026-10-25T12:00:00Z', now)).toBe(false);+ expect(canWait('2026-10-24T13:00:00Z', now)).toBe(false);+ expect(canWait(null, now)).toBe(false);+ expect(canWait('not a date', now)).toBe(false);+ });+});diff --git a/server/src/lib/email.js b/server/src/lib/email.jsindex 2444d1e70..81b51be90 100644--- a/server/src/lib/email.js+++ b/server/src/lib/email.js@@ -9,8 +9,9 @@ import { logger } from './logger.js';* Resend may have sent it all the same;* - 'skipped': not configured or no recipients. Missing config is a silent* no-op, so self-host and misconfigured environments never fail a caller.+ * `replyTo`, when given, is where a reply goes instead of the sender.*/-export async function deliverEmail({ to, subject, html, headers }) {+export async function deliverEmail({ to, subject, html, headers, replyTo }) {const apiKey = process.env.RESEND_API_KEY;const from = process.env.RESEND_FROM_EMAIL;if (!apiKey || !from || !to.length) return 'skipped';@@ -22,7 +23,14 @@ export async function deliverEmail({ to, subject, html, headers }) {Authorization: `Bearer ${apiKey}`,'Content-Type': 'application/json',},- body: JSON.stringify({ from, to, subject, html, ...(headers ? { headers } : {}) }),+ body: JSON.stringify({+ from,+ to,+ subject,+ html,+ ...(headers ? { headers } : {}),+ ...(replyTo ? { reply_to: replyTo } : {}),+ }),signal: AbortSignal.timeout(15000),});if (!res.ok) {diff --git a/server/src/lib/email.test.js b/server/src/lib/email.test.jsindex 5119b46e2..f9b8313e6 100644--- a/server/src/lib/email.test.js+++ b/server/src/lib/email.test.js@@ -38,6 +38,14 @@ describe('deliverEmail', () => {expect(await deliverEmail(message)).toBe('unknown');});+ it('sends a reply to replyTo when given', async () => {+ fetchMock.mockResolvedValue(answer(200));+ await deliverEmail({ ...message, replyTo: '[email protected]' });+ expect(JSON.parse(fetchMock.mock.calls[0][1].body).reply_to).toBe('[email protected]');+ await deliverEmail(message);+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).not.toHaveProperty('reply_to');+ });+it('skips without config or recipients', async () => {expect(await deliverEmail({ ...message, to: [] })).toBe('skipped');vi.stubEnv('RESEND_API_KEY', '');diff --git a/server/src/routes/billing.js b/server/src/routes/billing.jsnew file mode 100644index 000000000..74a8eced3--- /dev/null+++ b/server/src/routes/billing.js@@ -0,0 +1,124 @@+/**+ * Billing answers that go to the team (the plan itself is changed by the web+ * app, through Stripe).+ *+ * POST /api/billing/cancel-feedback — { reasons, message, choice } → kept and+ * e-mailed to CANCEL_FEEDBACK_EMAILS, with+ * replies going to the customer+ */++import { Router } from 'express';+import supabaseAdmin from '../config/supabase.js';+import { deliverEmail } from '../lib/email.js';+import {+ DAILY_LIMIT,+ SUBSCRIBED_STATUSES,+ buildCancelFeedbackEmail,+ canWait,+ cancelFeedbackSchema,+ feedbackRecipients,+} from '../lib/cancel-feedback.js';++const router = Router();++router.post('/cancel-feedback', async (req, res) => {+ try {+ const parsed = cancelFeedbackSchema.safeParse(req.body ?? {});+ if (!parsed.success) return res.status(400).json({ error: 'Invalid request' });+ const feedback = parsed.data;++ const { data: profile } = await supabaseAdmin+ .from('profiles')+ .select('organization_id, role, full_name')+ .eq('id', req.user.id)+ .single();+ const orgId = profile?.organization_id;+ if (!orgId) return res.status(403).json({ error: 'No organization' });+ // Cancelling is the admins', as the web's DELETE is: no one else can+ // tell the team the plan was cancelled, or ask for three days.+ if (profile.role !== 'admin') {+ return res.status(403).json({ error: 'Only admins can cancel the plan', code: 'admin_only' });+ }++ const { data: org } = await supabaseAdmin+ .from('organizations')+ .select('name, plan, subscription_status, subscription_ends_at, stripe_subscription_id')+ .eq('id', orgId)+ .single();+ // The browser's checks, again here: a direct request can't report a+ // plan that isn't there, or promise an answer after it renews.+ if (!org?.stripe_subscription_id || !SUBSCRIBED_STATUSES.includes(org.subscription_status)) {+ return res.status(400).json({ error: 'No subscription to cancel', code: 'no_subscription' });+ }+ // Only a period end the DB knows, still ahead and too close, refuses+ // waiting. A missing or past one means the DB is behind Stripe (only a+ // subscription update writes it), and the dialog checked Stripe's date.+ const endsAt = org.subscription_ends_at ? new Date(org.subscription_ends_at) : null;+ if (feedback.choice === 'wait' && endsAt && endsAt > new Date() && !canWait(endsAt)) {+ return res+ .status(400)+ .json({ error: 'The plan renews before we could answer', code: 'too_late' });+ }++ const { count } = await supabaseAdmin+ .from('cancellation_feedback')+ .select('id', { count: 'exact', head: true })+ .eq('organization_id', orgId)+ .gte('created_at', new Date(Date.now() - 86_400_000).toISOString());+ if ((count ?? 0) >= DAILY_LIMIT) {+ return res+ .status(429)+ .json({ error: 'Too many messages today. Please write to support.', code: 'too_many' });+ }++ // Kept before the e-mail goes, so a failed send loses nothing.+ const { data: row, error } = await supabaseAdmin+ .from('cancellation_feedback')+ .insert({+ organization_id: orgId,+ created_by: req.user.id,+ reasons: feedback.reasons,+ message: feedback.message,+ choice: feedback.choice,+ plan: org?.plan ?? null,+ subscription_status: org?.subscription_status ?? null,+ })+ .select('id')+ .single();+ if (error) throw new Error(error.message);++ const { subject, html } = buildCancelFeedbackEmail({+ org,+ user: { name: profile.full_name, email: req.user.email, role: profile.role },+ feedback,+ });+ const emailStatus = await deliverEmail({+ to: feedbackRecipients(),+ subject,+ html,+ replyTo: req.user.email || undefined,+ });+ if (emailStatus !== 'sent') {+ req.log.warn({ emailStatus, feedbackId: row.id }, '[billing] cancel feedback not e-mailed');+ }+ await supabaseAdmin+ .from('cancellation_feedback')+ .update({ email_status: emailStatus })+ .eq('id', row.id);+ // A wait is a promise to answer: when the team surely wasn't told, say so+ // rather than "we're on it". A cancel is done anyway; 'unknown' may have+ // gone out.+ if (feedback.choice === 'wait' && (emailStatus === 'skipped' || emailStatus === 'refused')) {+ return res+ .status(503)+ .json({ error: "Your message didn't reach the team", code: 'not_sent' });+ }++ return res.status(201).json({ ok: true });+ } catch (error) {+ req.log.error({ err: error }, '[billing] cancel feedback failed');+ return res.status(500).json({ error: 'Could not send your message' });+ }+});++export default router;diff --git a/server/src/routes/billing.test.js b/server/src/routes/billing.test.jsnew file mode 100644index 000000000..c21c3696a--- /dev/null+++ b/server/src/routes/billing.test.js@@ -0,0 +1,213 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * Cancel Subscription's answers: kept, then e-mailed to the team with replies+ * going to the customer; a few a day per organization.+ */++let profile;+let org;+let sentToday;+const inserted = [];+const updated = [];++function table(name) {+ const state = {};+ const result = () => {+ if (name === 'profiles') return { data: profile, error: null };+ if (name === 'organizations') return { data: org, error: null };+ if (name === 'cancellation_feedback') {+ if (state.insert) return { data: { id: 'f1' }, error: null };+ if (state.update) return { data: null, error: null };+ return { count: sentToday, data: null, error: null };+ }+ return { data: null, error: null };+ };+ const chain = new Proxy(+ {},+ {+ get: (_t, prop) => {+ if (prop === 'then')+ return (resolve, reject) => Promise.resolve(result()).then(resolve, reject);+ if (prop === 'single' || prop === 'maybeSingle') return async () => result();+ if (prop === 'insert')+ return (row) => {+ state.insert = row;+ inserted.push(row);+ return chain;+ };+ if (prop === 'update')+ return (row) => {+ state.update = row;+ updated.push(row);+ return chain;+ };+ return () => chain;+ },+ },+ );+ return chain;+}++const deliverEmail = vi.fn();+vi.mock('../config/supabase.js', () => ({ default: { from: (name) => table(name) } }));+vi.mock('../lib/email.js', () => ({ deliverEmail: (...args) => deliverEmail(...args) }));++const { default: router } = await import('./billing.js');++let server;+let baseUrl;++beforeEach(async () => {+ vi.stubEnv('CANCEL_FEEDBACK_EMAILS', '[email protected],[email protected]');+ profile = { organization_id: 'o1', role: 'admin', full_name: 'Ada' };+ org = {+ name: 'Acme Coffee',+ plan: 'starter',+ subscription_status: 'trialing',+ // Ten days on: room for the three days and a day to spare.+ subscription_ends_at: new Date(Date.now() + 10 * 86_400_000).toISOString(),+ stripe_subscription_id: 'sub_1',+ };+ sentToday = 0;+ inserted.length = 0;+ updated.length = 0;+ deliverEmail.mockReset().mockResolvedValue('sent');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1', email: '[email protected]' };+ req.log = { error: vi.fn(), warn: vi.fn() };+ next();+ });+ app.use('/api/billing', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/billing`;+});++afterEach(async () => {+ vi.unstubAllEnvs();+ await new Promise((resolve) => server.close(resolve));+});++const send = (body) =>+ fetch(`${baseUrl}/cancel-feedback`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++describe('POST /api/billing/cancel-feedback', () => {+ it('keeps the answer, then e-mails the team with replies going to the customer', async () => {+ const res = await send({+ reasons: ['no_results'],+ message: 'Not seeing results yet.',+ choice: 'wait',+ });+ expect(res.status).toBe(201);+ expect(inserted).toEqual([+ {+ organization_id: 'o1',+ created_by: 'u1',+ reasons: ['no_results'],+ message: 'Not seeing results yet.',+ choice: 'wait',+ plan: 'starter',+ subscription_status: 'trialing',+ },+ ]);+ expect(deliverEmail).toHaveBeenCalledTimes(1);+ const mail = deliverEmail.mock.calls[0][0];+ expect(mail.to).toEqual(['[email protected]', '[email protected]']);+ expect(mail.replyTo).toBe('[email protected]');+ expect(mail.subject).toBe('Acme Coffee asks us to act within 3 days before cancelling');+ expect(updated).toEqual([{ email_status: 'sent' }]);+ });++ it('still keeps the answer when the e-mail does not go out', async () => {+ deliverEmail.mockResolvedValue('skipped');+ const res = await send({ choice: 'cancel' });+ expect(res.status).toBe(201);+ expect(inserted).toHaveLength(1);+ expect(updated).toEqual([{ email_status: 'skipped' }]);+ });++ it('says a wait the team was never told about was not sent, and keeps it', async () => {+ // No addresses set, then Resend refusing it.+ for (const status of ['skipped', 'refused']) {+ inserted.length = 0;+ updated.length = 0;+ deliverEmail.mockResolvedValue(status);+ const res = await send({ reasons: ['too_expensive'], choice: 'wait' });+ expect(res.status).toBe(503);+ expect((await res.json()).code).toBe('not_sent');+ expect(inserted).toHaveLength(1);+ expect(updated).toEqual([{ email_status: status }]);+ }+ // A send Resend may have made still counts.+ deliverEmail.mockResolvedValue('unknown');+ expect((await send({ reasons: ['too_expensive'], choice: 'wait' })).status).toBe(201);+ });++ it('takes a few answers a day per organization', async () => {+ sentToday = 5;+ const res = await send({ choice: 'cancel' });+ expect(res.status).toBe(429);+ expect((await res.json()).code).toBe('too_many');+ expect(inserted).toHaveLength(0);+ expect(deliverEmail).not.toHaveBeenCalled();+ });++ it('is the admins’: anyone else is refused before anything is kept or sent', async () => {+ for (const role of ['manager', 'analyst', 'agency_partner']) {+ profile = { ...profile, role };+ const res = await send({ choice: 'cancel' });+ expect(res.status).toBe(403);+ expect((await res.json()).code).toBe('admin_only');+ }+ expect(inserted).toHaveLength(0);+ expect(deliverEmail).not.toHaveBeenCalled();+ });++ it('needs a plan to cancel, and time to answer before it renews', async () => {+ org = { ...org, stripe_subscription_id: null };+ let res = await send({ choice: 'cancel' });+ expect(res.status).toBe(400);+ expect((await res.json()).code).toBe('no_subscription');++ org = { ...org, stripe_subscription_id: 'sub_1', subscription_status: 'canceled' };+ expect((await send({ choice: 'cancel' })).status).toBe(400);++ // Renewing in three days and a few hours: no day left after the answer.+ org = {+ ...org,+ subscription_status: 'active',+ subscription_ends_at: new Date(Date.now() + 3.2 * 86_400_000).toISOString(),+ };+ res = await send({ choice: 'wait' });+ expect(res.status).toBe(400);+ expect((await res.json()).code).toBe('too_late');+ // Cancelling then is still fine.+ expect((await send({ choice: 'cancel' })).status).toBe(201);+ expect(inserted).toHaveLength(1);+ });++ it('lets a wait through when the DB has no period end, or a past one', async () => {+ // A new trial has none until Stripe's first update; a stale one lags it.+ for (const endsAt of [null, new Date(Date.now() - 2 * 86_400_000).toISOString()]) {+ org = { ...org, subscription_ends_at: endsAt };+ expect((await send({ reasons: ['no_results'], choice: 'wait' })).status).toBe(201);+ }+ expect(inserted).toHaveLength(2);+ });++ it('refuses a malformed answer, or a user with no organization', async () => {+ expect((await send({ choice: 'later' })).status).toBe(400);+ profile = { organization_id: null, role: 'admin', full_name: null };+ expect((await send({ choice: 'cancel' })).status).toBe(403);+ expect(inserted).toHaveLength(0);+ });+});diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex 36a0eb696..da6acaf14 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -14,6 +14,7 @@ import mentionRoutes from './mentions.js';import brandRoutes from './brands.js';import actionCenterRoutes from './action-center.js';import botRoutes from './bots.js';+import billingRoutes from './billing.js';const router = Router();@@ -32,6 +33,7 @@ router.use('/mentions', mentionRoutes);router.use('/brands', brandRoutes);router.use('/action-center', actionCenterRoutes);router.use('/bots', botRoutes);+router.use('/billing', billingRoutes);router.get('/health', (req, res) => {res.json({ status: 'ok', user: req.user?.id });diff --git a/supabase/migrations/00222_cancellation_feedback.sql b/supabase/migrations/00222_cancellation_feedback.sqlnew file mode 100644index 000000000..d947fc187--- /dev/null+++ b/supabase/migrations/00222_cancellation_feedback.sql@@ -0,0 +1,40 @@+-- ============================================================================+-- 00222: why a customer cancels, or asks for three days first+-- ============================================================================+-- Settings › Billing › Cancel Subscription asks what went wrong before the+-- plan is cancelled: a few reasons to tick and a message, both optional. The+-- customer then either cancels (at the end of the period, as before) or asks+-- the team to act within three days, and the plan stays as it is.+--+-- Each answer is e-mailed to the team (CANCEL_FEEDBACK_EMAILS on the server)+-- and kept here, so a failed e-mail loses nothing and the reasons can be+-- counted later.+--+-- Written and read by the Express server's service-role client only: RLS on,+-- no policies, and the default grants to anon and authenticated revoked (as+-- 00183 does), since the table holds customers' free-text messages.++create table if not exists public.cancellation_feedback (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations (id) on delete cascade,+ created_by uuid references auth.users (id) on delete set null,+ reasons text[] not null default '{}',+ message text not null default '' check (char_length(message) <= 2000),+ -- 'cancel': cancelled the plan; 'wait': asked the team to act within three days.+ choice text not null check (choice in ('cancel', 'wait')),+ -- The plan and its state when the answer was given.+ plan text,+ subscription_status text,+ -- What became of the e-mail: sent, refused, unknown or skipped (see server/src/lib/email.js).+ email_status text,+ created_at timestamptz not null default now()+);++create index if not exists cancellation_feedback_org_created_idx+ on public.cancellation_feedback (organization_id, created_at desc);++alter table public.cancellation_feedback enable row level security;+revoke all on public.cancellation_feedback from anon, authenticated;++comment on table public.cancellation_feedback is+ 'Why a customer cancels, or asks the team for three days first (Settings › Billing). E-mailed to CANCEL_FEEDBACK_EMAILS; server-only.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 396375674..f225db818 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -32569,6 +32569,50 @@ grant execute on function public.content_plan_pages(uuid, integer) to authenticacomment on function public.content_plan_pages(uuid, integer) is'Content Editor (CE-014): the brand''s 100 most cited pages over the last N (7, 30 or 90) whole UTC days to yesterday and the N before, from the daily rollups: citations, the brand''s answers in each window, platforms citing at a lower rate, AI visits and how many of its other pages compete for the same prompts; with the earlier window''s first day and the brand''s first tracked day. Security definer with an organization check.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00222_cancellation_feedback.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00222: why a customer cancels, or asks for three days first+-- ============================================================================+-- Settings › Billing › Cancel Subscription asks what went wrong before the+-- plan is cancelled: a few reasons to tick and a message, both optional. The+-- customer then either cancels (at the end of the period, as before) or asks+-- the team to act within three days, and the plan stays as it is.+--+-- Each answer is e-mailed to the team (CANCEL_FEEDBACK_EMAILS on the server)+-- and kept here, so a failed e-mail loses nothing and the reasons can be+-- counted later.+--+-- Written and read by the Express server's service-role client only: RLS on,+-- no policies, and the default grants to anon and authenticated revoked (as+-- 00183 does), since the table holds customers' free-text messages.++create table if not exists public.cancellation_feedback (+ id uuid primary key default gen_random_uuid(),+ organization_id uuid not null references public.organizations (id) on delete cascade,+ created_by uuid references auth.users (id) on delete set null,+ reasons text[] not null default '{}',+ message text not null default '' check (char_length(message) <= 2000),+ -- 'cancel': cancelled the plan; 'wait': asked the team to act within three days.+ choice text not null check (choice in ('cancel', 'wait')),+ -- The plan and its state when the answer was given.+ plan text,+ subscription_status text,+ -- What became of the e-mail: sent, refused, unknown or skipped (see server/src/lib/email.js).+ email_status text,+ created_at timestamptz not null default now()+);++create index if not exists cancellation_feedback_org_created_idx+ on public.cancellation_feedback (organization_id, created_at desc);++alter table public.cancellation_feedback enable row level security;+revoke all on public.cancellation_feedback from anon, authenticated;++comment on table public.cancellation_feedback is+ 'Why a customer cancels, or asks the team for three days first (Settings › Billing). E-mailed to CANCEL_FEEDBACK_EMAILS; server-only.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00223_mention_sentiment_override_api.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/messages/en.json b/web/messages/en.jsonindex 7cb3a18be..d80a88937 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5996,9 +5996,31 @@"trialEndsOn": "Your free trial ends on {date}","processing": "Processing...","cancelSubscription": "Cancel Subscription",- "cancelConfirmTitle": "Cancel your subscription?","cancelConfirmDescription": "Your subscription will remain active until the end of the current billing period. After that, you will lose access to paid features.",- "cancelConfirm": "Yes, Cancel",+ "cancelFeedbackTitle": "Before you go, what went wrong?",+ "cancelFeedbackDescription": "Your answer goes straight to our team. Tick what applies or tell us in your own words; both are optional.",+ "cancelReasonsLabel": "Reasons for cancelling",+ "cancelReasons": {+ "too_expensive": "Too expensive",+ "missing_feature": "Missing a feature I need",+ "no_results": "Not seeing results",+ "switching": "Switching to another tool",+ "temporary": "Only needed it for a while",+ "other": "Something else"+ },+ "cancelMessageLabel": "Your message",+ "cancelMessagePlaceholder": "Tell us more (optional)",+ "cancelWaitOffer": "<b>Give us {days} days?</b> We'll get back to you by {date} and try to put it right. Your plan stays as it is, and you can still cancel any time.",+ "cancelWaitNeedsInput": "Tick a reason or write a message so we know what to fix.",+ "sendAndCancel": "Send and cancel",+ "sendAndWait": "Send and give us {days} days",+ "cancelWaitSentTitle": "Thanks, we're on it",+ "cancelWaitSent": "We'll get back to you by {date}. Your plan stays as it is.",+ "cancelWaitClose": "Close",+ "cancelFeedbackTooMany": "You've sent several messages today. Please write to our support team instead.",+ "cancelFeedbackFailed": "Couldn't send your message. Please try again.",+ "cancelFeedbackTooLate": "Your plan renews before we could get back to you. You can still cancel it here.",+ "cancelFeedbackNotSent": "Your message didn't reach our team. Please write to our support team, or cancel the plan here.","reactivate": "Reactivate Subscription","subscriptionReactivated": "Subscription reactivated.","manageBilling": "Manage Billing",diff --git a/web/src/components/settings/cancel-subscription-dialog.test.tsx b/web/src/components/settings/cancel-subscription-dialog.test.tsxnew file mode 100644index 000000000..25ec270dc--- /dev/null+++ b/web/src/components/settings/cancel-subscription-dialog.test.tsx@@ -0,0 +1,177 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { toast } from 'sonner';+import messages from '../../../messages/en.json';+import { sendCancelFeedback } from '@/lib/actions/cancel-feedback';+import { CancelSubscriptionDialog } from './cancel-subscription-dialog';++vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));+vi.mock('@/lib/actions/cancel-feedback', () => ({ sendCancelFeedback: vi.fn() }));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const DAY = 86_400_000;+const inDays = (days: number) => new Date(Date.now() + days * DAY).toISOString();+const formatted = (days: number) =>+ new Date(Date.now() + days * DAY).toLocaleDateString('en-US', {+ year: 'numeric',+ month: 'long',+ day: 'numeric',+ });++let container: HTMLDivElement;+let root: Root;+const onOpenChange = vi.fn();+const onCancel = vi.fn<() => Promise<boolean>>();++async function render(currentPeriodEnd: string | null = inDays(20)) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <CancelSubscriptionDialog+ open+ onOpenChange={onOpenChange}+ currentPeriodEnd={currentPeriodEnd}+ onCancel={onCancel}+ />+ </NextIntlClientProvider>,+ );+ });+}++const button = (label: string) =>+ [...document.querySelectorAll('button')].find((b) => b.textContent?.trim() === label);++async function click(label: string) {+ await act(async () => {+ button(label)!.click();+ });+}++function write(text: string) {+ const box = document.querySelector<HTMLTextAreaElement>('#cancel-feedback-message')!;+ act(() => {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;+ setter.call(box, text);+ box.dispatchEvent(new Event('input', { bubbles: true }));+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ onCancel.mockResolvedValue(true);+ vi.mocked(sendCancelFeedback).mockResolvedValue({ ok: true });+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('cancelling', () => {+ it('asks what went wrong, and sends the answer once the plan is cancelled', async () => {+ await render();+ expect(document.body.textContent).toContain('Before you go, what went wrong?');+ await click('Too expensive');+ expect(button('Too expensive')!.getAttribute('aria-pressed')).toBe('true');+ write('Too pricey for a team of two.');+ await click('Send and cancel');+ expect(onCancel).toHaveBeenCalledTimes(1);+ expect(sendCancelFeedback).toHaveBeenCalledWith({+ reasons: ['too_expensive'],+ message: 'Too pricey for a team of two.',+ choice: 'cancel',+ });+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });++ it('cancels with nothing said, and still tells the team', async () => {+ await render();+ await click('Cancel Subscription');+ expect(sendCancelFeedback).toHaveBeenCalledWith({ reasons: [], message: '', choice: 'cancel' });+ });++ it('sends nothing and stays open when cancelling failed', async () => {+ onCancel.mockResolvedValue(false);+ await render();+ await click('Cancel Subscription');+ expect(sendCancelFeedback).not.toHaveBeenCalled();+ expect(onOpenChange).not.toHaveBeenCalledWith(false);+ });+});++describe('giving the team three days', () => {+ it('sends the answer and keeps the plan, once there is something to fix', async () => {+ await render();+ expect(document.body.textContent).toContain(`We'll get back to you by ${formatted(3)}`);+ expect(button('Send and give us 3 days')!.hasAttribute('disabled')).toBe(true);+ await click('Missing a feature I need');+ expect(button('Send and give us 3 days')!.hasAttribute('disabled')).toBe(false);+ await click('Send and give us 3 days');+ expect(onCancel).not.toHaveBeenCalled();+ expect(sendCancelFeedback).toHaveBeenCalledWith({+ reasons: ['missing_feature'],+ message: '',+ choice: 'wait',+ });+ expect(document.body.textContent).toContain("Thanks, we're on it");+ expect(document.body.textContent).toContain(+ `We'll get back to you by ${formatted(3)}. Your plan stays as it is.`,+ );+ });++ it('isn’t offered when the plan renews within those days, or a day after', async () => {+ await render(inDays(2));+ expect(button('Send and give us 3 days')).toBeUndefined();+ await render(inDays(3.5));+ expect(button('Send and give us 3 days')).toBeUndefined();+ expect(document.body.textContent).not.toContain('Give us 3 days?');+ await render(null);+ expect(button('Send and give us 3 days')).toBeUndefined();+ });++ it('says so when the message can’t go, and keeps the form', async () => {+ vi.mocked(sendCancelFeedback).mockResolvedValue({ error: 'too_many' });+ await render();+ write('Please call me.');+ await click('Send and give us 3 days');+ expect(toast.error).toHaveBeenCalledWith(+ "You've sent several messages today. Please write to our support team instead.",+ );+ expect(document.body.textContent).toContain('Before you go, what went wrong?');+ });++ it('leaves only cancelling when the server says waiting can’t work', async () => {+ for (const [error, said] of [+ [+ 'too_late',+ 'Your plan renews before we could get back to you. You can still cancel it here.',+ ],+ [+ 'not_sent',+ "Your message didn't reach our team. Please write to our support team, or cancel the plan here.",+ ],+ ] as const) {+ vi.mocked(sendCancelFeedback).mockResolvedValue({ error });+ await render();+ write('Please call me.');+ await click('Send and give us 3 days');+ expect(toast.error).toHaveBeenLastCalledWith(said);+ expect(document.body.textContent).not.toContain("Thanks, we're on it");+ expect(button('Send and give us 3 days')).toBeUndefined();+ expect(button('Send and cancel')).toBeDefined();+ // A fresh dialog for the next refusal.+ act(() => root.unmount());+ root = createRoot(container);+ }+ });+});diff --git a/web/src/components/settings/cancel-subscription-dialog.tsx b/web/src/components/settings/cancel-subscription-dialog.tsxnew file mode 100644index 000000000..b8011c730--- /dev/null+++ b/web/src/components/settings/cancel-subscription-dialog.tsx@@ -0,0 +1,217 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Textarea } from '@/components/ui/textarea';+import { sendCancelFeedback } from '@/lib/actions/cancel-feedback';+import {+ CANCEL_MESSAGE_MAX,+ CANCEL_REASONS,+ WAIT_DAYS,+ canWait,+ waitUntil,+ type CancelReason,+} from '@/lib/billing/cancel-feedback';+import { cn } from '@/lib/utils';++const formatDate = (date: Date) =>+ date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });++/**+ * Cancel Subscription asks what went wrong first: reasons to tick and a+ * message, both optional, which go to the team. Then the customer cancels+ * (at the end of the period, as before) or gives the team three days to put+ * it right, the plan unchanged. Waiting isn't offered when the plan renews+ * within those days, so no one is charged while they wait.+ */+export function CancelSubscriptionDialog({+ open,+ onOpenChange,+ currentPeriodEnd,+ onCancel,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ currentPeriodEnd: string | null;+ /** Cancels the plan at the end of the period; false when that failed (it says why). */+ onCancel: () => Promise<boolean>;+}) {+ const t = useTranslations('settings');+ const [reasons, setReasons] = useState<CancelReason[]>([]);+ const [message, setMessage] = useState('');+ const [busy, setBusy] = useState<'cancel' | 'wait' | null>(null);+ const [answerBy, setAnswerBy] = useState<Date | null>(null);+ // The server said waiting can't work (renews too soon, or the team can't+ // be told): only cancelling is left.+ const [waitRefused, setWaitRefused] = useState(false);++ const said = reasons.length > 0 || message.trim().length > 0;+ const offerWait = canWait(currentPeriodEnd) && !waitRefused;++ function reset() {+ setReasons([]);+ setMessage('');+ setAnswerBy(null);+ }++ function toggle(reason: CancelReason) {+ setReasons((current) =>+ current.includes(reason) ? current.filter((r) => r !== reason) : [...current, reason],+ );+ }++ async function cancel() {+ setBusy('cancel');+ try {+ if (!(await onCancel())) return;+ // The plan is cancelled either way: a message that doesn't reach the+ // team isn't worth an error now.+ await sendCancelFeedback({ reasons, message, choice: 'cancel' }).catch(() => null);+ onOpenChange(false);+ reset();+ } finally {+ setBusy(null);+ }+ }++ async function wait() {+ setBusy('wait');+ try {+ const result = await sendCancelFeedback({ reasons, message, choice: 'wait' });+ if ('ok' in result) {+ setAnswerBy(waitUntil());+ } else if (result.error === 'too_late' || result.error === 'not_sent') {+ setWaitRefused(true);+ toast.error(+ result.error === 'too_late' ? t('cancelFeedbackTooLate') : t('cancelFeedbackNotSent'),+ );+ } else {+ toast.error(+ result.error === 'too_many' ? t('cancelFeedbackTooMany') : t('cancelFeedbackFailed'),+ );+ }+ } finally {+ setBusy(null);+ }+ }++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (busy) return;+ onOpenChange(next);+ if (!next) reset();+ }}+ >+ <DialogContent className="max-w-lg">+ {answerBy ? (+ <>+ <DialogHeader>+ <DialogTitle>{t('cancelWaitSentTitle')}</DialogTitle>+ <DialogDescription>+ {t('cancelWaitSent', { date: formatDate(answerBy) })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ onClick={() => {+ onOpenChange(false);+ reset();+ }}+ >+ {t('cancelWaitClose')}+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>{t('cancelFeedbackTitle')}</DialogTitle>+ <DialogDescription>{t('cancelFeedbackDescription')}</DialogDescription>+ </DialogHeader>+ <div className="space-y-3">+ <div+ className="flex flex-wrap gap-1.5"+ role="group"+ aria-label={t('cancelReasonsLabel')}+ >+ {CANCEL_REASONS.map((reason) => (+ <button+ key={reason}+ type="button"+ aria-pressed={reasons.includes(reason)}+ onClick={() => toggle(reason)}+ className={cn(+ 'rounded-md border px-2.5 py-1 text-xs font-medium transition-colors',+ reasons.includes(reason)+ ? 'border-primary bg-primary text-primary-foreground'+ : 'bg-background hover:bg-muted',+ )}+ >+ {t(`cancelReasons.${reason}`)}+ </button>+ ))}+ </div>+ <label htmlFor="cancel-feedback-message" className="sr-only">+ {t('cancelMessageLabel')}+ </label>+ <Textarea+ id="cancel-feedback-message"+ value={message}+ maxLength={CANCEL_MESSAGE_MAX}+ rows={4}+ placeholder={t('cancelMessagePlaceholder')}+ onChange={(e) => setMessage(e.target.value)}+ />+ {offerWait && (+ <p className="rounded-md border bg-muted/30 p-3 text-sm">+ {t.rich('cancelWaitOffer', {+ days: WAIT_DAYS,+ date: formatDate(waitUntil()),+ b: (chunks) => <span className="font-medium">{chunks}</span>,+ })}+ {!said && (+ <span className="mt-1 block text-xs text-muted-foreground">+ {t('cancelWaitNeedsInput')}+ </span>+ )}+ </p>+ )}+ <p className="text-xs text-muted-foreground">{t('cancelConfirmDescription')}</p>+ </div>+ <DialogFooter>+ <Button+ variant={offerWait ? 'outline' : 'destructive'}+ className={offerWait ? 'text-destructive hover:text-destructive' : undefined}+ onClick={cancel}+ disabled={busy != null}+ >+ {busy === 'cancel'+ ? t('processing')+ : said+ ? t('sendAndCancel')+ : t('cancelSubscription')}+ </Button>+ {offerWait && (+ <Button onClick={wait} disabled={busy != null || !said}>+ {busy === 'wait' ? t('processing') : t('sendAndWait', { days: WAIT_DAYS })}+ </Button>+ )}+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/web/src/components/settings/plan-switcher.test.tsx b/web/src/components/settings/plan-switcher.test.tsxindex 2cd39ad9c..02ff54064 100644--- a/web/src/components/settings/plan-switcher.test.tsx+++ b/web/src/components/settings/plan-switcher.test.tsx@@ -6,9 +6,13 @@ import messages from '../../../messages/en.json';import { toast } from 'sonner';import { RoleProvider } from '@/components/providers/role-provider';import type { TeamRole } from '@/components/providers/role-provider';+import { sendCancelFeedback } from '@/lib/actions/cancel-feedback';import { PlanSwitcher } from './plan-switcher';vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }) }));+vi.mock('@/lib/actions/cancel-feedback', () => ({+ sendCancelFeedback: vi.fn(async () => ({ ok: true })),+}));(globalThis as typeof globalThis & {@@ -283,3 +287,31 @@ describe('buying during the free trial', () => {expect(document.body.textContent).toContain('Buy Starter now?');});});++describe('cancelling', () => {+ it('asks what went wrong first, then cancels at the end of the period and tells the team', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () =>+ Response.json({ cancelAtPeriodEnd: true, currentPeriodEnd: '2026-11-20T00:00:00Z' }),+ ),+ );+ await render('growth');+ await click('Cancel Subscription');+ const dialog = document.querySelector('[role="dialog"]')!;+ expect(dialog.textContent).toContain('Before you go, what went wrong?');+ await act(async () => {+ [...dialog.querySelectorAll('button')]+ .find((b) => b.textContent?.trim() === 'Cancel Subscription')!+ .click();+ });+ expect(fetch).toHaveBeenCalledWith('/api/stripe/subscription', { method: 'DELETE' });+ expect(onUpdate).toHaveBeenCalledWith(+ expect.objectContaining({+ cancelAtPeriodEnd: true,+ currentPeriodEnd: '2026-11-20T00:00:00Z',+ }),+ );+ expect(sendCancelFeedback).toHaveBeenCalledWith({ reasons: [], message: '', choice: 'cancel' });+ });+});diff --git a/web/src/components/settings/plan-switcher.tsx b/web/src/components/settings/plan-switcher.tsxindex b509a61e1..a842394fa 100644--- a/web/src/components/settings/plan-switcher.tsx+++ b/web/src/components/settings/plan-switcher.tsx@@ -15,7 +15,6 @@ import {DialogFooter,DialogHeader,DialogTitle,- DialogTrigger,} from '@/components/ui/dialog';import {CONTACT_SALES_URL,@@ -33,6 +32,7 @@ import {import { useUserRole } from '@/hooks/use-user-role';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';+import { CancelSubscriptionDialog } from './cancel-subscription-dialog';interface SubscriptionData {planId: string;@@ -55,7 +55,6 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {// as the subscription route checks.const { canAdmin } = useUserRole();const [loading, setLoading] = useState(false);- const [cancelLoading, setCancelLoading] = useState(false);const [portalLoading, setPortalLoading] = useState(false);const [cancelOpen, setCancelOpen] = useState(false);// The plan a card's button asked for: bought now during a trial, or changed to.@@ -111,7 +110,6 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {}async function handleCancel() {- setCancelLoading(true);try {const res = await fetch('/api/stripe/subscription', { method: 'DELETE' });if (!res.ok) {@@ -125,11 +123,10 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {currentPeriodEnd: data.currentPeriodEnd,});toast.success(t('subscriptionCanceled'));- setCancelOpen(false);+ return true;} catch (err) {toast.error(err instanceof Error ? err.message : 'Failed to cancel');- } finally {- setCancelLoading(false);+ return false;}}@@ -529,26 +526,13 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {{subscription.cancelAtPeriodEnd || !canAdmin ? (<span />) : (- <Dialog open={cancelOpen} onOpenChange={setCancelOpen}>- <DialogTrigger- render={- <Button variant="ghost" className="text-destructive hover:text-destructive" />- }- >- {t('cancelSubscription')}- </DialogTrigger>- <DialogContent className="max-w-md">- <DialogHeader>- <DialogTitle>{t('cancelConfirmTitle')}</DialogTitle>- <DialogDescription>{t('cancelConfirmDescription')}</DialogDescription>- </DialogHeader>- <DialogFooter>- <Button variant="destructive" onClick={handleCancel} disabled={cancelLoading}>- {cancelLoading ? t('processing') : t('cancelConfirm')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>+ <Button+ variant="ghost"+ className="text-destructive hover:text-destructive"+ onClick={() => setCancelOpen(true)}+ >+ {t('cancelSubscription')}+ </Button>)}<Buttonvariant="outline"@@ -560,6 +544,16 @@ export function PlanSwitcher({ subscription, onUpdate }: PlanSwitcherProps) {<ExternalLink className="ml-2 h-4 w-4" /></Button></div>+ {/* Mounted outside the button's branch: it still sends the answer once+ the plan is cancelled. Admins only, as the button is. */}+ {canAdmin && (+ <CancelSubscriptionDialog+ open={cancelOpen}+ onOpenChange={setCancelOpen}+ currentPeriodEnd={subscription.currentPeriodEnd}+ onCancel={handleCancel}+ />+ )}</div>);}diff --git a/web/src/lib/actions/cancel-feedback.ts b/web/src/lib/actions/cancel-feedback.tsnew file mode 100644index 000000000..d11db7b87--- /dev/null+++ b/web/src/lib/actions/cancel-feedback.ts@@ -0,0 +1,51 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';+import type { CancelChoice, CancelReason } from '@/lib/billing/cancel-feedback';++export type CancelFeedbackResult =+ | { ok: true }+ | { error: CancelFeedbackRefusal | 'server' | 'unreachable' | 'unauthenticated' };++/** The server's refusals the dialog words on their own; anything else is `server`. */+const REFUSALS = ['too_many', 'too_late', 'not_sent'] as const;+type CancelFeedbackRefusal = (typeof REFUSALS)[number];++/**+ * Send the team why the customer cancels, or their request for three days+ * first. The server keeps it and e-mails it, with replies going to the+ * customer.+ */+export async function sendCancelFeedback(input: {+ reasons: CancelReason[];+ message: string;+ choice: CancelChoice;+}): Promise<CancelFeedbackResult> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'unauthenticated' };++ try {+ const res = await fetch(`${API_BASE_URL}/api/billing/cancel-feedback`, {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${session.access_token}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(input),+ cache: 'no-store',+ // The server gives Resend 15 s.+ signal: AbortSignal.timeout(30_000),+ });+ if (res.ok) return { ok: true };+ const data = await res.json().catch(() => ({}));+ return {+ error: REFUSALS.includes(data.code) ? (data.code as CancelFeedbackRefusal) : 'server',+ };+ } catch {+ return { error: 'unreachable' };+ }+}diff --git a/web/src/lib/billing/cancel-feedback.test.ts b/web/src/lib/billing/cancel-feedback.test.tsnew file mode 100644index 000000000..5118ab21b--- /dev/null+++ b/web/src/lib/billing/cancel-feedback.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';+import { canWait, waitUntil } from './cancel-feedback';++describe('waiting three days before cancelling', () => {+ const now = new Date('2026-10-21T12:00:00Z');++ it('is answered three days on', () => {+ expect(waitUntil(now).toISOString()).toBe('2026-10-24T12:00:00.000Z');+ });++ it('is offered only when the plan renews a day or more after the team has answered', () => {+ expect(canWait('2026-10-30T00:00:00Z', now)).toBe(true);+ expect(canWait('2026-10-25T12:00:01Z', now)).toBe(true);+ // A minute after the three days: no time left to cancel after hearing back.+ expect(canWait('2026-10-24T12:01:00Z', now)).toBe(false);+ expect(canWait('2026-10-25T12:00:00Z', now)).toBe(false);+ expect(canWait('2026-10-23T00:00:00Z', now)).toBe(false);+ });++ it('isn’t offered without a known period end', () => {+ expect(canWait(null, now)).toBe(false);+ expect(canWait('not a date', now)).toBe(false);+ });+});diff --git a/web/src/lib/billing/cancel-feedback.ts b/web/src/lib/billing/cancel-feedback.tsnew file mode 100644index 000000000..b3aa1c96e--- /dev/null+++ b/web/src/lib/billing/cancel-feedback.ts@@ -0,0 +1,43 @@+/**+ * Why a customer cancels, or asks for three days first (Settings › Billing ›+ * Cancel Subscription). The reasons match the server's+ * (server/src/lib/cancel-feedback.js), which keeps the answer and e-mails it+ * to the team.+ */++export const CANCEL_REASONS = [+ 'too_expensive',+ 'missing_feature',+ 'no_results',+ 'switching',+ 'temporary',+ 'other',+] as const;++export type CancelReason = (typeof CANCEL_REASONS)[number];++export type CancelChoice = 'cancel' | 'wait';++/** How long the team has to act when the customer waits. */+export const WAIT_DAYS = 3;++export const CANCEL_MESSAGE_MAX = 2000;++const DAY_MS = 86_400_000;++/** The day the team answers by, when the customer gives it three days. */+export function waitUntil(now = new Date()): Date {+ return new Date(now.getTime() + WAIT_DAYS * DAY_MS);+}++/**+ * Whether waiting is offered: only when the plan renews (or the trial ends)+ * at least a day after the team has answered, so no one is charged while+ * they wait and there is still time to cancel after hearing back. With no+ * known period end, it isn't. The server checks the same rule.+ */+export function canWait(currentPeriodEnd: string | null, now = new Date()): boolean {+ if (!currentPeriodEnd) return false;+ const end = new Date(currentPeriodEnd).getTime();+ return Number.isFinite(end) && end > waitUntil(now).getTime() + DAY_MS;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 9f1a71271..09e2b78e9 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -727,6 +727,53 @@ export type Database = {},]}+ cancellation_feedback: {+ Row: {+ choice: string+ created_at: string+ created_by: string | null+ email_status: string | null+ id: string+ message: string+ organization_id: string+ plan: string | null+ reasons: string[]+ subscription_status: string | null+ }+ Insert: {+ choice: string+ created_at?: string+ created_by?: string | null+ email_status?: string | null+ id?: string+ message?: string+ organization_id: string+ plan?: string | null+ reasons?: string[]+ subscription_status?: string | null+ }+ Update: {+ choice?: string+ created_at?: string+ created_by?: string | null+ email_status?: string | null+ id?: string+ message?: string+ organization_id?: string+ plan?: string | null+ reasons?: string[]+ subscription_status?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "cancellation_feedback_organization_id_fkey"+ columns: ["organization_id"]+ isOneToOne: false+ referencedRelation: "organizations"+ referencedColumns: ["id"]+ },+ ]+ }citation_urls: {Row: {domain: string