Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 166 additions & 4 deletions apps/api/src/lib/self-refund.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,14 @@ 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",
comments: "A flat $10 tier would have worked",
}),
},
);

expect(response.status).toBe(200);
Expand All @@ -693,6 +700,134 @@ 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",
comments: "A flat $10 tier would have worked",
});
});

test("rejects a missing or unknown 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 unknown = await app.request(
`/orgs/${ORG_ID}/transactions/${tx.id}/refund`,
{
method: "POST",
headers: { Cookie: token, "Content-Type": "application/json" },
body: JSON.stringify({ reason: "just because" }),
},
);
expect(unknown.status).toBe(400);

expect(stripeMock.refunds.create).not.toHaveBeenCalled();
expect(
await db.query.refundFeedback.findMany({
where: { organizationId: { eq: ORG_ID } },
}),
).toHaveLength(0);
});

// "Something else" says nothing on its own, so the endpoint enforces the
// follow-up the dialog asks for rather than trusting the client gate.
test("rejects reason 'other' with no comments without calling Stripe", async () => {
await seedOrg({ credits: "100" });
const tx = await seedTransaction();

const response = await app.request(
`/orgs/${ORG_ID}/transactions/${tx.id}/refund`,
{
method: "POST",
headers: { Cookie: token, "Content-Type": "application/json" },
body: JSON.stringify({ reason: "other" }),
},
);
expect(response.status).toBe(400);

expect(stripeMock.refunds.create).not.toHaveBeenCalled();
expect(
await db.query.refundFeedback.findMany({
where: { organizationId: { eq: ORG_ID } },
}),
).toHaveLength(0);
});

// The category is required, the detail is not — a one-click answer must
// still go through.
test("accepts a reason with no comments", async () => {
await seedOrg({ credits: "100" });
const tx = await seedTransaction();

const response = await app.request(
`/orgs/${ORG_ID}/transactions/${tx.id}/refund`,
{
method: "POST",
headers: { Cookie: token, "Content-Type": "application/json" },
body: JSON.stringify({ reason: "bought_by_mistake" }),
},
);
expect(response.status).toBe(200);

const feedback = await db.query.refundFeedback.findMany({
where: { organizationId: { eq: ORG_ID } },
});
expect(feedback).toHaveLength(1);
expect(feedback[0]).toMatchObject({
reason: "bought_by_mistake",
comments: null,
});
});

// The whole point of writing feedback before calling Stripe: a refund that
// blows up at the payment provider must not also lose the answer, or the
// only people we hear from are the ones whose refunds worked.
test("keeps the feedback when Stripe rejects the refund", async () => {
await seedOrg({ credits: "100" });
const tx = await seedTransaction();
stripeMock.refunds.create.mockRejectedValueOnce(new Error("card_declined"));

const response = await app.request(
`/orgs/${ORG_ID}/transactions/${tx.id}/refund`,
{
method: "POST",
headers: { Cookie: token, "Content-Type": "application/json" },
body: JSON.stringify({
reason: "not_working",
comments: "Every request 500s on gpt-5.6",
}),
},
);
expect(response.status).toBe(500);

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: "not_working",
comments: "Every request 500s on gpt-5.6",
});
});

test("refunding a dev plan resolves the invoice payment and issues the refund", async () => {
Expand Down Expand Up @@ -727,7 +862,14 @@ 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",
comments: "A flat $10 tier would have worked",
}),
},
);

expect(response.status).toBe(200);
Expand All @@ -739,6 +881,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 () => {
Expand All @@ -747,7 +895,14 @@ 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",
comments: "A flat $10 tier would have worked",
}),
},
);

expect(response.status).toBe(400);
Expand All @@ -764,7 +919,14 @@ 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",
comments: "A flat $10 tier would have worked",
}),
},
);

expect(response.status).toBe(403);
Expand Down
74 changes: 73 additions & 1 deletion apps/api/src/lib/self-refund.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
import { z } from "@hono/zod-openapi";
import { Decimal } from "decimal.js";
import { HTTPException } from "hono/http-exception";

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,
DEV_PLAN_RESET_PASS_PRICES,
isRefundFeedbackComplete,
REFUND_COMMENTS_MAX_LENGTH,
REFUND_REASONS,
type ChatPlanTier,
type DevPlanTier,
} from "@llmgateway/shared";

import type { tables } from "@llmgateway/db";
import type { RefundFeedbackKind } from "@llmgateway/db";
import type { RefundReason } from "@llmgateway/shared";

type OrganizationRow = typeof tables.organization.$inferSelect;
type TransactionRow = typeof tables.transaction.$inferSelect;
Expand Down Expand Up @@ -79,6 +85,43 @@ 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";
}

/**
* Body both self-refund endpoints take: a required category so every refund
* yields comparable data, plus optional freeform detail.
*/
export const refundFeedbackBodySchema = z.object({
reason: z.enum(REFUND_REASONS).openapi({
description: "Closest category for why the customer wants a refund",
}),
comments: z
.string()
.trim()
.max(REFUND_COMMENTS_MAX_LENGTH)
.optional()
.openapi({
description:
"Freeform detail. Optional, except when reason is 'other' — that category carries no signal on its own.",
}),
});

function ineligible(
reason: SelfRefundIneligibilityReason,
): SelfRefundEligibility {
Expand Down Expand Up @@ -382,16 +425,45 @@ 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` and the optional `comments` are why the user says they are
* refunding; they are stored before the refund is issued so the feedback
* survives a Stripe failure.
*/
export async function executeSelfRefund({
organization,
transaction,
userId,
reason,
comments,
}: {
organization: OrganizationRow;
transaction: TransactionRow;
userId: string;
reason: RefundReason;
comments?: string;
}): Promise<{ stripeRefundId: string }> {
if (!isRefundFeedbackComplete(reason, comments)) {
throw new HTTPException(400, {
message: "Tell us what happened so we know what to fix.",
});
}

await db
.insert(tables.refundFeedback)
.values({
organizationId: organization.id,
userId,
transactionId: transaction.id,
kind: refundFeedbackKindForType(transaction.type),
reason,
comments: comments ?? null,
})
.onConflictDoUpdate({
target: tables.refundFeedback.transactionId,
set: { reason, comments: comments ?? null, userId },
});

const stripe = getStripe();

let paymentIntentId = transaction.stripePaymentIntentId;
Expand Down
11 changes: 11 additions & 0 deletions apps/api/src/routes/dev-plans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
computeSelfRefundEligibility,
executeSelfRefund,
isSelfRefundCandidateType,
refundFeedbackBodySchema,
} from "@/lib/self-refund.js";
import { posthog } from "@/posthog.js";
import {
Expand Down Expand Up @@ -2372,6 +2373,13 @@ const selfRefundInvoice = createRoute({
params: z.object({
invoiceId: z.string(),
}),
body: {
content: {
"application/json": {
schema: refundFeedbackBodySchema,
},
},
},
},
responses: {
200: {
Expand All @@ -2396,6 +2404,7 @@ devPlans.openapi(selfRefundInvoice, async (c) => {
}

const { invoiceId } = c.req.param();
const { reason, comments } = c.req.valid("json");

const personalOrg = await findPersonalOrg(user.id);
if (!personalOrg) {
Expand Down Expand Up @@ -2435,6 +2444,8 @@ devPlans.openapi(selfRefundInvoice, async (c) => {
organization: personalOrg,
transaction,
userId: user.id,
reason,
comments,
});

return c.json({
Expand Down
Loading
Loading