From 9289216fb19d9e081c0a4ae92bf7b34b865ac5e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 25 Jul 2026 12:08:26 +0000 Subject: [PATCH 1/5] feat: collect refund reason before self-refund Adds a required freeform "Why are you refunding?" field to every self-service refund dialog (credits, DevPass, chat plans). The answer is stored in a new refund_feedback table along with the product kind, so feedback can be read per surface without joining back to the transaction type. The reason is validated server-side (non-empty, max 1000 chars) on both refund endpoints and persisted before the Stripe refund is issued, so the feedback survives a Stripe failure. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_019XSErvAhCo3gyR9ULqNqDe --- apps/api/src/lib/self-refund.spec.ts | 73 +- apps/api/src/lib/self-refund.ts | 41 +- apps/api/src/routes/dev-plans.ts | 19 + apps/api/src/routes/organization.ts | 23 +- .../dashboard/components/DevPassInvoices.tsx | 42 +- .../pricing/chat-billing-history.tsx | 44 +- .../billing/transactions-client.tsx | 42 +- .../migrations/1784979478_serious_doorman.sql | 17 + .../migrations/meta/1784979478_snapshot.json | 28280 ++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 38 + packages/shared/src/index.ts | 2 + packages/shared/src/refunds.ts | 4 + 13 files changed, 28613 insertions(+), 19 deletions(-) create mode 100644 packages/db/migrations/1784979478_serious_doorman.sql create mode 100644 packages/db/migrations/meta/1784979478_snapshot.json create mode 100644 packages/shared/src/refunds.ts diff --git a/apps/api/src/lib/self-refund.spec.ts b/apps/api/src/lib/self-refund.spec.ts index 66365a2090..db80c0800a 100644 --- a/apps/api/src/lib/self-refund.spec.ts +++ b/apps/api/src/lib/self-refund.spec.ts @@ -671,7 +671,11 @@ describe("self-refund endpoints", () => { const response = await app.request( `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, - { method: "POST", headers: { Cookie: token } }, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({ reason: "Too expensive for my usage" }), + }, ); expect(response.status).toBe(200); @@ -693,6 +697,49 @@ describe("self-refund endpoints", () => { }); expect(auditLogs).toHaveLength(1); expect(auditLogs[0]?.resourceId).toBe(tx.id); + + const feedback = await db.query.refundFeedback.findMany({ + where: { organizationId: { eq: ORG_ID } }, + }); + expect(feedback).toHaveLength(1); + expect(feedback[0]).toMatchObject({ + transactionId: tx.id, + userId: "test-user-id", + kind: "credits", + reason: "Too expensive for my usage", + }); + }); + + test("rejects a missing or blank reason without calling Stripe", async () => { + await seedOrg({ credits: "100" }); + const tx = await seedTransaction(); + + const missing = await app.request( + `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({}), + }, + ); + expect(missing.status).toBe(400); + + const blank = await app.request( + `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({ reason: " " }), + }, + ); + expect(blank.status).toBe(400); + + expect(stripeMock.refunds.create).not.toHaveBeenCalled(); + expect( + await db.query.refundFeedback.findMany({ + where: { organizationId: { eq: ORG_ID } }, + }), + ).toHaveLength(0); }); test("refunding a dev plan resolves the invoice payment and issues the refund", async () => { @@ -727,7 +774,11 @@ describe("self-refund endpoints", () => { const response = await app.request( `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, - { method: "POST", headers: { Cookie: token } }, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({ reason: "Too expensive for my usage" }), + }, ); expect(response.status).toBe(200); @@ -739,6 +790,12 @@ describe("self-refund endpoints", () => { // charge.refunded webhook (handleChargeRefunded), covering every refund // source, not just this endpoint. expect(stripeMock.subscriptions.cancel).not.toHaveBeenCalled(); + + const feedback = await db.query.refundFeedback.findMany({ + where: { organizationId: { eq: ORG_ID } }, + }); + expect(feedback).toHaveLength(1); + expect(feedback[0]?.kind).toBe("devpass"); }); test("rejects ineligible transactions with 400 and does not call Stripe", async () => { @@ -747,7 +804,11 @@ describe("self-refund endpoints", () => { const response = await app.request( `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, - { method: "POST", headers: { Cookie: token } }, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({ reason: "Too expensive for my usage" }), + }, ); expect(response.status).toBe(400); @@ -764,7 +825,11 @@ describe("self-refund endpoints", () => { const response = await app.request( `/orgs/${ORG_ID}/transactions/${tx.id}/refund`, - { method: "POST", headers: { Cookie: token } }, + { + method: "POST", + headers: { Cookie: token, "Content-Type": "application/json" }, + body: JSON.stringify({ reason: "Too expensive for my usage" }), + }, ); expect(response.status).toBe(403); diff --git a/apps/api/src/lib/self-refund.ts b/apps/api/src/lib/self-refund.ts index 24465672ae..ac7e21e2e6 100644 --- a/apps/api/src/lib/self-refund.ts +++ b/apps/api/src/lib/self-refund.ts @@ -5,6 +5,7 @@ import { getStripe } from "@/routes/payments.js"; import { getPaymentIntentFromInvoicePayments } from "@/stripe.js"; import { logAuditEvent } from "@llmgateway/audit"; +import { db, tables } from "@llmgateway/db"; import { CHAT_PLAN_PRICES, DEV_PLAN_PRICES, @@ -13,7 +14,7 @@ import { type DevPlanTier, } from "@llmgateway/shared"; -import type { tables } from "@llmgateway/db"; +import type { RefundFeedbackKind } from "@llmgateway/db"; type OrganizationRow = typeof tables.organization.$inferSelect; type TransactionRow = typeof tables.transaction.$inferSelect; @@ -79,6 +80,24 @@ export function isSelfRefundCandidateType( return (SELF_REFUNDABLE_TYPES as readonly string[]).includes(type); } +const REFUND_FEEDBACK_KIND_BY_TYPE: Record< + SelfRefundableType, + RefundFeedbackKind +> = { + credit_topup: "credits", + dev_plan_start: "devpass", + dev_plan_renewal: "devpass", + dev_plan_reset_pass: "devpass", + chat_plan_start: "chat", + chat_plan_renewal: "chat", +}; + +export function refundFeedbackKindForType(type: string): RefundFeedbackKind { + return isSelfRefundCandidateType(type) + ? REFUND_FEEDBACK_KIND_BY_TYPE[type] + : "credits"; +} + function ineligible( reason: SelfRefundIneligibilityReason, ): SelfRefundEligibility { @@ -382,16 +401,36 @@ export function computeSelfRefundEligibility({ * the resulting customer.subscription.deleted resets the plan fields. Keeping * the cancellation in the webhook means it fires for every refund source, not * just this endpoint. + * + * `reason` is the freeform answer the user gave for why they are refunding; it + * is stored before the refund is issued so the feedback survives a Stripe + * failure. */ export async function executeSelfRefund({ organization, transaction, userId, + reason, }: { organization: OrganizationRow; transaction: TransactionRow; userId: string; + reason: string; }): Promise<{ stripeRefundId: string }> { + await db + .insert(tables.refundFeedback) + .values({ + organizationId: organization.id, + userId, + transactionId: transaction.id, + kind: refundFeedbackKindForType(transaction.type), + reason, + }) + .onConflictDoUpdate({ + target: tables.refundFeedback.transactionId, + set: { reason, userId }, + }); + const stripe = getStripe(); let paymentIntentId = transaction.stripePaymentIntentId; diff --git a/apps/api/src/routes/dev-plans.ts b/apps/api/src/routes/dev-plans.ts index a1f9abcf90..f2c4947301 100644 --- a/apps/api/src/routes/dev-plans.ts +++ b/apps/api/src/routes/dev-plans.ts @@ -56,6 +56,7 @@ import { getIncludedResetPassesRemaining, getRemainingPremiumWeeklyAllowance, isPremiumWeekExpired, + REFUND_REASON_MAX_LENGTH, type DevPlanCycle, type DevPlanTier, } from "@llmgateway/shared"; @@ -2372,6 +2373,22 @@ const selfRefundInvoice = createRoute({ params: z.object({ invoiceId: z.string(), }), + body: { + content: { + "application/json": { + schema: z.object({ + reason: z + .string() + .trim() + .min(1) + .max(REFUND_REASON_MAX_LENGTH) + .openapi({ + description: "Why the customer is requesting the refund", + }), + }), + }, + }, + }, }, responses: { 200: { @@ -2396,6 +2413,7 @@ devPlans.openapi(selfRefundInvoice, async (c) => { } const { invoiceId } = c.req.param(); + const { reason } = c.req.valid("json"); const personalOrg = await findPersonalOrg(user.id); if (!personalOrg) { @@ -2435,6 +2453,7 @@ devPlans.openapi(selfRefundInvoice, async (c) => { organization: personalOrg, transaction, userId: user.id, + reason, }); return c.json({ diff --git a/apps/api/src/routes/organization.ts b/apps/api/src/routes/organization.ts index 3d1f58aa0f..9aae383d56 100644 --- a/apps/api/src/routes/organization.ts +++ b/apps/api/src/routes/organization.ts @@ -34,7 +34,10 @@ import { projectHourlyStats, } from "@llmgateway/db"; import { getProviderCountries } from "@llmgateway/models"; -import { CREDIT_TOP_UP_MAX_AMOUNT } from "@llmgateway/shared"; +import { + CREDIT_TOP_UP_MAX_AMOUNT, + REFUND_REASON_MAX_LENGTH, +} from "@llmgateway/shared"; import type { ServerTypes } from "@/vars.js"; @@ -1046,6 +1049,22 @@ const selfRefundTransaction = createRoute({ id: z.string(), transactionId: z.string(), }), + body: { + content: { + "application/json": { + schema: z.object({ + reason: z + .string() + .trim() + .min(1) + .max(REFUND_REASON_MAX_LENGTH) + .openapi({ + description: "Why the customer is requesting the refund", + }), + }), + }, + }, + }, }, responses: { 200: { @@ -1072,6 +1091,7 @@ organization.openapi(selfRefundTransaction, async (c) => { } const { id, transactionId } = c.req.param(); + const { reason } = c.req.valid("json"); const userOrganization = await db.query.userOrganization.findFirst({ where: { @@ -1121,6 +1141,7 @@ organization.openapi(selfRefundTransaction, async (c) => { organization: userOrganization.organization, transaction, userId: user.id, + reason, }); return c.json({ diff --git a/apps/code/src/app/dashboard/components/DevPassInvoices.tsx b/apps/code/src/app/dashboard/components/DevPassInvoices.tsx index 315e7d3b3c..435111d49b 100644 --- a/apps/code/src/app/dashboard/components/DevPassInvoices.tsx +++ b/apps/code/src/app/dashboard/components/DevPassInvoices.tsx @@ -24,8 +24,12 @@ import { AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; import { useApi, useFetchClient } from "@/lib/fetch-client"; +import { REFUND_REASON_MAX_LENGTH } from "@llmgateway/shared"; + import type { paths } from "@/lib/api/v1"; import type { ReactNode } from "react"; @@ -138,12 +142,16 @@ function RefundButton({ invoice }: { invoice: Invoice }) { const api = useApi(); const queryClient = useQueryClient(); const isResetPass = invoice.type === "dev_plan_reset_pass"; + const [open, setOpen] = useState(false); + const [reason, setReason] = useState(""); const refundMutation = api.useMutation( "post", "/dev-plans/invoices/{invoiceId}/refund", { onSuccess: () => { + setOpen(false); + setReason(""); toast.success( isResetPass ? "Refund processing. The unused pass has been returned and the refund will arrive within a few business days." @@ -190,7 +198,7 @@ function RefundButton({ invoice }: { invoice: Invoice }) { } return ( - +