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
103 changes: 103 additions & 0 deletions app/(authenticated)/checkout/actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* @jest-environment node
*/
import { checkoutDonation } from "./actions";

const createSession = jest.fn();
const retrieveProduct = jest.fn();
const retrievePrice = jest.fn();
const getUser = jest.fn();
const getOrCreateStripeCustomer = jest.fn();
const headersGet = jest.fn();

jest.mock("@/lib/stripe", () => ({
stripe: {
checkout: { sessions: { create: (...args: unknown[]) => createSession(...args) } },
products: { retrieve: (...args: unknown[]) => retrieveProduct(...args) },
prices: { retrieve: (...args: unknown[]) => retrievePrice(...args) },
},
getOrCreateStripeCustomer: (...args: unknown[]) =>
getOrCreateStripeCustomer(...args),
}));

jest.mock("@/utils/supabase/server", () => ({
createClient: async () => ({ auth: { getUser } }),
}));

jest.mock("next/headers", () => ({
headers: async () => ({ get: (...args: unknown[]) => headersGet(...args) }),
}));

const authedUser = {
data: { user: { id: "user-1", email: "donor@test.com" } },
};

beforeEach(() => {
jest.clearAllMocks();
process.env.STRIPE_DONATION_PRODUCT_ID = "prod_test123";
getUser.mockResolvedValue(authedUser);
getOrCreateStripeCustomer.mockResolvedValue("cus_123");
retrieveProduct.mockResolvedValue({ default_price: "price_donation" });
retrievePrice.mockResolvedValue({ custom_unit_amount: { preset: 1000 } });
createSession.mockResolvedValue({ url: "https://stripe.test/session" });
headersGet.mockReturnValue("https://app.test");
});

describe("checkoutDonation", () => {
it("requires an authenticated user", async () => {
getUser.mockResolvedValue({ data: { user: null } });
const result = await checkoutDonation();
expect(result).toEqual({ error: "Not authenticated" });
expect(createSession).not.toHaveBeenCalled();
});

it("returns an error when the donation product env var is not set", async () => {
delete process.env.STRIPE_DONATION_PRODUCT_ID;
const result = await checkoutDonation();
expect(result).toEqual({ error: "Donation product not configured" });
expect(createSession).not.toHaveBeenCalled();
});

it("creates a checkout session using the donation product's default price", async () => {
const result = await checkoutDonation();

expect(retrieveProduct).toHaveBeenCalledWith("prod_test123");
expect(getOrCreateStripeCustomer).toHaveBeenCalledWith(
"user-1",
"donor@test.com",
);
expect(createSession).toHaveBeenCalledWith(
expect.objectContaining({
customer: "cus_123",
mode: "payment",
metadata: { type: "donation" },
line_items: [{ price: "price_donation", quantity: 1 }],
}),
);
expect(result).toEqual({ url: "https://stripe.test/session" });
});

it("derives success/cancel URLs from the request origin", async () => {
await checkoutDonation();
expect(createSession).toHaveBeenCalledWith(
expect.objectContaining({
success_url: "https://app.test/checkout/success",
cancel_url: "https://app.test/checkout/cancel",
}),
);
});

it("returns an error when Stripe omits the checkout URL", async () => {
createSession.mockResolvedValue({ url: null });
const result = await checkoutDonation();
expect(result).toEqual({ error: "Stripe did not return a checkout URL" });
});

it("throws when the request origin is missing", async () => {
headersGet.mockReturnValue(null);
await expect(checkoutDonation()).rejects.toThrow(
"Missing request origin",
);
expect(createSession).not.toHaveBeenCalled();
});
});
34 changes: 34 additions & 0 deletions app/(authenticated)/checkout/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,40 @@ export async function checkoutServiceBooking({
return { url: result.session.url! };
}

export async function checkoutDonation(): Promise<CheckoutResult> {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: "Not authenticated" };

// This product can have a variable price, adjusted by Stripe Checkout
const donationProductId = process.env.STRIPE_DONATION_PRODUCT_ID;
Comment thread
martin0024 marked this conversation as resolved.
if (!donationProductId) return { error: "Donation product not configured" };

const product = await stripe.products.retrieve(donationProductId);
const priceId = product.default_price;

if (!priceId || typeof priceId !== "string") {
return { error: "Donation product has no default price" };
}

const price = await stripe.prices.retrieve(priceId);
if (!price.custom_unit_amount) {
return { error: "Donation price is not configured for customer chosen amounts" };
}

const result = await createStripeCheckoutSession({
userId: user.id,
email: user.email!,
stripeProductId: donationProductId,
metadata: { type: "donation" },
});
if ("error" in result) return { error: result.error };

return { url: result.session.url! };
}

export async function checkoutCoachingSession({
coachingSessionId,
}: {
Expand Down
3 changes: 3 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ const createJestConfig = nextJest({
/** @type {import('jest').Config} */
const customJestConfig = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/$1",
},
testEnvironment: "jest-environment-jsdom",
modulePathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
testMatch: ["**/*.test.[jt]s?(x)"],
Expand Down
Loading