Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { globalPrismaClient } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { CustomerType } from "@prisma/client";
import { KnownErrors } from "@stackframe/stack-shared/dist/known-errors";
import { adaptSchema, clientOrHigherAuthTypeSchema, inlineOfferSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { adaptSchema, clientOrHigherAuthTypeSchema, inlineOfferSchema, urlSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env";
import { throwErr } from "@stackframe/stack-shared/dist/utils/errors";
import { purchaseUrlVerificationCodeHandler } from "../verification-code-handler";
Expand All @@ -24,6 +24,7 @@ export const POST = createSmartRouteHandler({
customer_id: yupString().defined(),
offer_id: yupString().optional(),
offer_inline: inlineOfferSchema.optional(),
return_url: urlSchema.optional(),
}),
}),
response: yupObject({
Expand Down Expand Up @@ -77,6 +78,9 @@ export const POST = createSmartRouteHandler({

const fullCode = `${tenancy.id}_${code}`;
const url = new URL(`/purchase/${fullCode}`, getEnvVariable("NEXT_PUBLIC_STACK_DASHBOARD_URL"));
if (req.body.return_url) {
url.searchParams.set("return_url", req.body.return_url);
}

return {
statusCode: 200,
Expand Down
124 changes: 123 additions & 1 deletion apps/backend/src/lib/payments.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { PrismaClientTransaction } from '@/prisma-client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getItemQuantityForCustomer, validatePurchaseSession } from './payments';
import { getItemQuantityForCustomer, getSubscriptions, validatePurchaseSession } from './payments';
import type { Tenancy } from './tenancies';

function createMockPrisma(overrides: Partial<PrismaClientTransaction> = {}): PrismaClientTransaction {
Expand Down Expand Up @@ -717,6 +717,38 @@ describe('getItemQuantityForCustomer - subscriptions', () => {
expect(qty).toBe(8);
vi.useRealTimers();
});

it('ungrouped include-by-default provides item quantity without db subscription', async () => {
const now = new Date('2025-02-10T00:00:00.000Z');
vi.setSystemTime(now);
const itemId = 'defaultItemUngrouped';

const tenancy = createMockTenancy({
items: { [itemId]: { displayName: 'UDF', customerType: 'user' } },
groups: {},
offers: {
offFreeUngrouped: {
displayName: 'Free Ungrouped',
groupId: undefined,
customerType: 'user',
freeTrial: undefined,
serverOnly: false,
stackable: false,
prices: 'include-by-default',
includedItems: { [itemId]: { quantity: 5, repeat: 'never', expires: 'when-purchase-expires' } },
isAddOnTo: false,
},
},
});

const prisma = createMockPrisma({
subscription: { findMany: async () => [] },
} as any);

const qty = await getItemQuantityForCustomer({ prisma, tenancy, itemId, customerId: 'u1', customerType: 'user' });
expect(qty).toBe(5);
vi.useRealTimers();
});
});


Expand Down Expand Up @@ -933,3 +965,93 @@ describe('combined sources - one-time purchases + manual changes + subscriptions
});
});


describe('getSubscriptions - defaults behavior', () => {
it('includes ungrouped include-by-default offers in subscriptions', async () => {
const tenancy = createMockTenancy({
items: {},
groups: {},
offers: {
freeUngrouped: {
displayName: 'Free',
groupId: undefined,
customerType: 'custom',
freeTrial: undefined,
serverOnly: false,
stackable: false,
prices: 'include-by-default',
includedItems: {},
isAddOnTo: false,
},
paidUngrouped: {
displayName: 'Paid',
groupId: undefined,
customerType: 'custom',
freeTrial: undefined,
serverOnly: false,
stackable: false,
prices: {},
includedItems: {},
isAddOnTo: false,
},
},
});

const prisma = createMockPrisma({
subscription: { findMany: async () => [] },
} as any);

const subs = await getSubscriptions({
prisma,
tenancy,
customerType: 'custom',
customerId: 'c-1',
});

const ids = subs.map(s => s.offerId);
expect(ids).toContain('freeUngrouped');
});

it('throws error when multiple include-by-default offers exist in same group', async () => {
const tenancy = createMockTenancy({
items: {},
groups: { g1: { displayName: 'G1' } },
offers: {
g1FreeA: {
displayName: 'Free A',
groupId: 'g1',
customerType: 'custom',
freeTrial: undefined,
serverOnly: false,
stackable: false,
prices: 'include-by-default',
includedItems: {},
isAddOnTo: false,
},
g1FreeB: {
displayName: 'Free B',
groupId: 'g1',
customerType: 'custom',
freeTrial: undefined,
serverOnly: false,
stackable: false,
prices: 'include-by-default',
includedItems: {},
isAddOnTo: false,
},
},
});

const prisma = createMockPrisma({
subscription: { findMany: async () => [] },
} as any);

await expect(getSubscriptions({
prisma,
tenancy,
customerType: 'custom',
customerId: 'c-1',
})).rejects.toThrowError('Multiple include-by-default offers configured in the same group');
});
});

32 changes: 28 additions & 4 deletions apps/backend/src/lib/payments.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -301,12 +301,19 @@ export async function getSubscriptions(options: {
for (const groupId of Object.keys(groups)) {
if (groupsWithDbSubscriptions.has(groupId)) continue;
const offersInGroup = typedEntries(offers).filter(([_, offer]) => offer.groupId === groupId);
const defaultGroupOffer = offersInGroup.find(([_, offer]) => offer.prices === "include-by-default");
if (defaultGroupOffer) {
const defaultGroupOffers = offersInGroup.filter(([_, offer]) => offer.prices === "include-by-default");
if (defaultGroupOffers.length > 1) {
throw new StackAssertionError(
"Multiple include-by-default offers configured in the same group",
{ groupId, offerIds: defaultGroupOffers.map(([id]) => id) },
);
}
if (defaultGroupOffers.length === 1) {
const [offerId, offer] = defaultGroupOffers[0];
subscriptions.push({
id: null,
offerId: defaultGroupOffer[0],
offer: defaultGroupOffer[1],
offerId,
offer,
quantity: 1,
currentPeriodStart: DEFAULT_OFFER_START_DATE,
currentPeriodEnd: null,
Expand All @@ -317,6 +324,23 @@ export async function getSubscriptions(options: {
}
}

const ungroupedDefaults = typedEntries(offers).filter(([id, offer]) => (
offer.groupId === undefined && offer.prices === "include-by-default" && !subscriptions.some((s) => s.offerId === id)
));
Comment thread
BilalG1 marked this conversation as resolved.
Outdated
for (const [offerId, offer] of ungroupedDefaults) {
subscriptions.push({
id: null,
offerId,
offer,
quantity: 1,
currentPeriodStart: DEFAULT_OFFER_START_DATE,
currentPeriodEnd: null,
status: SubscriptionStatus.active,
createdAt: DEFAULT_OFFER_START_DATE,
stripeSubscriptionId: null,
});
}

return subscriptions;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,11 @@ function TeamAddUserDialog(props: {
const onSubmit = async (values: yup.InferType<typeof inviteFormSchema>) => {
if (users.length + 1 > quantity) {
alert("You have reached the maximum number of dashboard admins. Please upgrade your plan to add more admins.");
const checkoutUrl = await props.team.createCheckoutUrl({ offerId: "team" });
window.open(checkoutUrl, "_blank", "noopener");
const checkoutUrl = await props.team.createCheckoutUrl({
offerId: "team",
returnUrl: window.location.href,
});
window.location.assign(checkoutUrl);
return "prevent-close-and-prevent-reset";
}
await props.onSubmit(values.email);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { typedEntries } from "@stackframe/stack-shared/dist/utils/objects";
import { runAsynchronouslyWithAlert } from "@stackframe/stack-shared/dist/utils/promises";
import { Alert, AlertDescription, AlertTitle, Button, Card, CardContent, Input, Skeleton, Typography } from "@stackframe/stack-ui";
import { ArrowRight, Minus, Plus } from "lucide-react";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import * as yup from "yup";

Expand All @@ -30,8 +31,10 @@ export default function PageClient({ code }: { code: string }) {
const [error, setError] = useState<string | null>(null);
const [selectedPriceId, setSelectedPriceId] = useState<string | null>(null);
const [quantityInput, setQuantityInput] = useState<string>("1");
const searchParams = useSearchParams();
const user = useUser({ projectIdMustMatch: "internal" });
const [adminApp, setAdminApp] = useState<StackAdminApp>();
const returnUrl = searchParams.get("return_url");

useEffect(() => {
if (!user || !data) return;
Expand Down Expand Up @@ -138,8 +141,11 @@ export default function PageClient({ code }: { code: string }) {
const url = new URL(`/purchase/return`, window.location.origin);
url.searchParams.set("bypass", "1");
url.searchParams.set("purchase_full_code", code);
if (returnUrl) {
url.searchParams.set("return_url", returnUrl);
}
window.location.assign(url.toString());
}, [code, adminApp, selectedPriceId, quantityNumber, isTooLarge]);
}, [code, adminApp, selectedPriceId, quantityNumber, isTooLarge, returnUrl]);

return (
<div className="flex flex-row">
Expand Down Expand Up @@ -281,6 +287,7 @@ export default function PageClient({ code }: { code: string }) {
fullCode={code}
stripeAccountId={data.stripe_account_id}
setupSubscription={setupSubscription}
returnUrl={returnUrl ?? undefined}
disabled={quantityNumber < 1 || isTooLarge || data.already_bought_non_stackable === true}
/>
</StripeElementsProvider>
Expand Down
21 changes: 18 additions & 3 deletions apps/dashboard/src/app/(main)/purchase/return/page-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { runAsynchronously } from "@stackframe/stack-shared/dist/utils/promises"
import { Typography } from "@stackframe/stack-ui";
import { loadStripe } from "@stripe/stripe-js";
import { useCallback, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";

type Props = {
redirectStatus?: string,
Expand All @@ -25,11 +26,19 @@ const stripePublicKey = getPublicEnvVar("NEXT_PUBLIC_STACK_STRIPE_PUBLISHABLE_KE

export default function ReturnClient({ clientSecret, stripeAccountId, purchaseFullCode, bypass }: Props) {
const [state, setState] = useState<ViewState>({ kind: "loading" });
const searchParams = useSearchParams();
const returnUrl = searchParams.get("return_url");

const updateViewState = useCallback(async (): Promise<void> => {
try {
if (bypass === "1") {
setState({ kind: "success", message: "Bypassed in test mode. No payment processed." });
if (returnUrl) {
window.location.assign(returnUrl);
}
const message = returnUrl
? "Bypassed in test mode. No payment processed. You will be redirected shortly."
: "Bypassed in test mode. No payment processed.";
setState({ kind: "success", message });
return;
}
const stripe = await loadStripe(stripePublicKey, { stripeAccount: stripeAccountId });
Expand All @@ -40,7 +49,13 @@ export default function ReturnClient({ clientSecret, stripeAccountId, purchaseFu
const lastErrorMessage = result.paymentIntent?.last_payment_error?.message;

if (status === "succeeded") {
setState({ kind: "success", message: "Payment succeeded. You can close this page." });
if (returnUrl) {
window.location.assign(returnUrl);
}
const message = returnUrl
? "Payment succeeded. You will be redirected shortly."
: "Payment succeeded. You can close this page.";
setState({ kind: "success", message });
return;
}
if (status === "processing") {
Expand All @@ -64,7 +79,7 @@ export default function ReturnClient({ clientSecret, stripeAccountId, purchaseFu
const message = e instanceof Error ? e.message : "Unexpected error retrieving payment.";
setState({ kind: "error", message });
}
}, [clientSecret, stripeAccountId, bypass]);
}, [clientSecret, stripeAccountId, bypass, returnUrl]);

useEffect(() => {
runAsynchronously(updateViewState());
Expand Down
14 changes: 9 additions & 5 deletions apps/dashboard/src/components/payments/checkout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ type Props = {
setupSubscription: () => Promise<string>,
stripeAccountId: string,
fullCode: string,
returnUrl?: string,
disabled?: boolean,
};

export function CheckoutForm({ setupSubscription, stripeAccountId, fullCode, disabled }: Props) {
export function CheckoutForm({ setupSubscription, stripeAccountId, fullCode, returnUrl, disabled }: Props) {
const stripe = useStripe();
const elements = useElements();
const [message, setMessage] = useState<string | null>(null);
Expand All @@ -39,15 +40,18 @@ export function CheckoutForm({ setupSubscription, stripeAccountId, fullCode, dis
}

const clientSecret = await setupSubscription();
const returnUrl = new URL(`/purchase/return`, window.location.origin);
returnUrl.searchParams.set("stripe_account_id", stripeAccountId);
returnUrl.searchParams.set("purchase_full_code", fullCode);
const stripeReturnUrl = new URL(`/purchase/return`, window.location.origin);
stripeReturnUrl.searchParams.set("stripe_account_id", stripeAccountId);
stripeReturnUrl.searchParams.set("purchase_full_code", fullCode);
if (returnUrl) {
stripeReturnUrl.searchParams.set("return_url", returnUrl);
}

const { error } = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {
return_url: returnUrl.toString(),
return_url: stripeReturnUrl.toString(),
},
}) as { error?: StripeError };

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { it } from "../../../../../helpers";
import { Auth, Project, User, niceBackendFetch, Payments } from "../../../../backend-helpers";
import { generateUuid } from "@stackframe/stack-shared/dist/utils/uuids";
import { it } from "../../../../../helpers";
import { Auth, niceBackendFetch, Payments, Project, User } from "../../../../backend-helpers";

it("should not be able to create purchase URL without offer_id or offer_inline", async ({ expect }) => {
await Project.createAndSwitch();
Expand Down Expand Up @@ -309,9 +309,13 @@ it("should allow valid offer_id", async ({ expect }) => {
customer_type: "user",
customer_id: userId,
offer_id: "test-offer",
return_url: "http://stack-test.localhost/after-purchase",
},
});
expect(response.status).toBe(200);
const body = response.body as { url: string };
expect(body.url).toMatch(/^https?:\/\/localhost:8101\/purchase\/[a-z0-9-_]+$/);
expect(body.url).toMatch(/^https?:\/\/localhost:8101\/purchase\/[a-z0-9-_]+\?return_url=/);
const urlObj = new URL(body.url);
const returnUrl = urlObj.searchParams.get("return_url");
expect(returnUrl).toBe("http://stack-test.localhost/after-purchase");
});
Loading