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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "PurchaseCreationSource" ADD VALUE 'API_GRANT';
1 change: 1 addition & 0 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,7 @@ enum SubscriptionStatus {
enum PurchaseCreationSource {
PURCHASE_PAGE
TEST_MODE
API_GRANT
}

model Subscription {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import { purchaseUrlVerificationCodeHandler } from "@/app/api/latest/payments/purchases/verification-code-handler";
import { validatePurchaseSession } from "@/lib/payments";
import { grantProductToCustomer } from "@/lib/payments";
import { getTenancy } from "@/lib/tenancies";
import { getStripeForAccount } from "@/lib/stripe";
import { getPrismaClientForTenancy } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { SubscriptionStatus } from "@prisma/client";
import { yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { addInterval } from "@stackframe/stack-shared/dist/utils/dates";
import { StackAssertionError, StatusError } from "@stackframe/stack-shared/dist/utils/errors";
import { typedToUppercase } from "@stackframe/stack-shared/dist/utils/strings";

export const POST = createSmartRouteHandler({
metadata: {
Expand Down Expand Up @@ -38,67 +35,17 @@ export const POST = createSmartRouteHandler({
}
const prisma = await getPrismaClientForTenancy(tenancy);

const { selectedPrice, conflictingCatalogSubscriptions } = await validatePurchaseSession({
await grantProductToCustomer({
prisma,
tenancy,
codeData: data,
customerType: data.product.customerType,
customerId: data.customerId,
product: data.product,
productId: data.productId,
priceId: price_id,
quantity,
creationSource: "TEST_MODE",
});
if (!selectedPrice) {
throw new StackAssertionError("Price not resolved for test mode purchase session");
}

if (!selectedPrice.interval) {
await prisma.oneTimePurchase.create({
data: {
tenancyId: tenancy.id,
customerId: data.customerId,
customerType: typedToUppercase(data.product.customerType),
productId: data.productId,
priceId: price_id,
product: data.product,
quantity,
creationSource: "TEST_MODE",
},
});
} else {
// Cancel conflicting subscriptions for TEST_MODE as well, then create new TEST_MODE subscription
if (conflictingCatalogSubscriptions.length > 0) {
const conflicting = conflictingCatalogSubscriptions[0];
if (conflicting.stripeSubscriptionId) {
const stripe = await getStripeForAccount({ tenancy });
await stripe.subscriptions.cancel(conflicting.stripeSubscriptionId);
} else if (conflicting.id) {
await prisma.subscription.update({
where: {
tenancyId_id: {
tenancyId: tenancy.id,
id: conflicting.id,
},
},
data: { status: SubscriptionStatus.canceled },
});
}
}

await prisma.subscription.create({
data: {
tenancyId: tenancy.id,
customerId: data.customerId,
customerType: typedToUppercase(data.product.customerType),
status: "active",
productId: data.productId,
priceId: price_id,
product: data.product,
quantity,
currentPeriodStart: new Date(),
currentPeriodEnd: addInterval(new Date(), selectedPrice.interval!),
cancelAtPeriodEnd: false,
creationSource: "TEST_MODE",
},
});
}
await purchaseUrlVerificationCodeHandler.revokeCode({
tenancy,
id: codeId,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { ensureProductIdOrInlineProduct, getOwnedProductsForCustomer, grantProductToCustomer, productToInlineProduct } from "@/lib/payments";
import { getPrismaClientForTenancy } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { adaptSchema, clientOrHigherAuthTypeSchema, inlineProductSchema, serverOrHigherAuthTypeSchema, yupBoolean, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { KnownErrors } from "@stackframe/stack-shared";
import { StatusError } from "@stackframe/stack-shared/dist/utils/errors";
import { customerProductsListResponseSchema } from "@stackframe/stack-shared/dist/interface/crud/products";

export const GET = createSmartRouteHandler({
metadata: {
summary: "List products owned by a customer",
hidden: true,
},
request: yupObject({
auth: yupObject({
type: clientOrHigherAuthTypeSchema.defined(),
project: adaptSchema.defined(),
tenancy: adaptSchema.defined(),
}).defined(),
params: yupObject({
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
}).defined(),
query: yupObject({
cursor: yupString().optional(),
limit: yupString().optional(),
}).default(() => ({})).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: customerProductsListResponseSchema,
}),
handler: async ({ auth, params, query }) => {
const prisma = await getPrismaClientForTenancy(auth.tenancy);
const ownedProducts = await getOwnedProductsForCustomer({
prisma,
tenancy: auth.tenancy,
customerType: params.customer_type,
customerId: params.customer_id,
});

const visibleProducts =
auth.type === "client"
? ownedProducts.filter(({ product }) => !product.serverOnly)
: ownedProducts;

const sorted = visibleProducts
.slice()
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.map((product) => ({
cursor: product.sourceId,
item: {
id: product.id,
quantity: product.quantity,
product: productToInlineProduct(product.product),
},
}));

let startIndex = 0;
if (query.cursor) {
startIndex = sorted.findIndex((entry) => entry.cursor === query.cursor);
if (startIndex === -1) {
throw new StatusError(400, "Invalid cursor");
}
}

const limit = yupNumber().min(1).max(100).optional().default(10).validateSync(query.limit);
const pageEntries = sorted.slice(startIndex, startIndex + limit);
const nextCursor = startIndex + limit < sorted.length ? sorted[startIndex + limit].cursor : null;

return {
statusCode: 200,
bodyType: "json",
body: {
items: pageEntries.map((entry) => entry.item),
is_paginated: true,
pagination: {
next_cursor: nextCursor,
},
},
};
},
});

export const POST = createSmartRouteHandler({
metadata: {
summary: "Grant a product to a customer",
hidden: true,
},
request: yupObject({
auth: yupObject({
type: serverOrHigherAuthTypeSchema.defined(),
project: adaptSchema.defined(),
tenancy: adaptSchema.defined(),
}).defined(),
params: yupObject({
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
}).defined(),
body: yupObject({
product_id: yupString().optional(),
product_inline: inlineProductSchema.optional(),
quantity: yupNumber().integer().min(1).default(1),
}).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
success: yupBoolean().oneOf([true]).defined(),
}).defined(),
}),
handler: async ({ auth, params, body }) => {
const { tenancy } = auth;
const prisma = await getPrismaClientForTenancy(tenancy);
const product = await ensureProductIdOrInlineProduct(
tenancy,
auth.type,
body.product_id,
body.product_inline,
);

if (params.customer_type !== product.customerType) {
throw new KnownErrors.ProductCustomerTypeDoesNotMatch(
body.product_id,
params.customer_id,
product.customerType,
params.customer_type,
);
}

await grantProductToCustomer({
prisma,
tenancy,
customerType: params.customer_type,
customerId: params.customer_id,
product,
productId: body.product_id,
priceId: undefined,
quantity: body.quantity,
creationSource: "API_GRANT",
});

return {
statusCode: 200,
bodyType: "json",
body: {
success: true,
},
};
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const POST = createSmartRouteHandler({
productId: req.body.product_id,
});
if (alreadyOwnsProduct) {
throw new StatusError(400, "Customer already has purchased this product; this product is not stackable");
throw new KnownErrors.ProductAlreadyGranted(req.body.product_id, req.body.customer_id);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
import { getSubscriptions, isActiveSubscription } from "@/lib/payments";
import { getSubscriptions, isActiveSubscription, productToInlineProduct } from "@/lib/payments";
import { validateRedirectUrl } from "@/lib/redirect-urls";
import { getTenancy } from "@/lib/tenancies";
import { getPrismaClientForTenancy } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { KnownErrors } from "@stackframe/stack-shared";
import { inlineProductSchema, urlSchema, yupArray, yupBoolean, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { SUPPORTED_CURRENCIES } from "@stackframe/stack-shared/dist/utils/currency-constants";
import { StackAssertionError } from "@stackframe/stack-shared/dist/utils/errors";
import { filterUndefined, getOrUndefined, typedEntries, typedFromEntries } from "@stackframe/stack-shared/dist/utils/objects";
import * as yup from "yup";
import { purchaseUrlVerificationCodeHandler } from "../verification-code-handler";

const productDataSchema = inlineProductSchema
.omit(["server_only", "included_items"])
.concat(yupObject({
stackable: yupBoolean().defined(),
}));

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
Expand All @@ -31,7 +22,7 @@ export const POST = createSmartRouteHandler({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
product: productDataSchema,
product: inlineProductSchema,
stripe_account_id: yupString().defined(),
project_id: yupString().defined(),
already_bought_non_stackable: yupBoolean().defined(),
Expand All @@ -52,16 +43,6 @@ export const POST = createSmartRouteHandler({
throw new KnownErrors.RedirectUrlNotWhitelisted();
}
const product = verificationCode.data.product;
const productData: yup.InferType<typeof productDataSchema> = {
display_name: product.displayName ?? "Product",
customer_type: product.customerType,
stackable: product.stackable === true,
prices: product.prices === "include-by-default" ? {} : typedFromEntries(typedEntries(product.prices).map(([key, value]) => [key, filterUndefined({
...typedFromEntries(SUPPORTED_CURRENCIES.map(c => [c.code, getOrUndefined(value, c.code)])),
interval: value.interval,
free_trial: value.freeTrial,
})])),
};

// Compute purchase context info
const prisma = await getPrismaClientForTenancy(tenancy);
Expand Down Expand Up @@ -98,7 +79,7 @@ export const POST = createSmartRouteHandler({
statusCode: 200,
bodyType: "json",
body: {
product: productData,
product: productToInlineProduct(product),
stripe_account_id: verificationCode.data.stripeAccountId,
project_id: tenancy.project.id,
already_bought_non_stackable: alreadyBoughtNonStackable,
Expand Down
6 changes: 3 additions & 3 deletions apps/backend/src/lib/payments.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { PrismaClientTransaction } from '@/prisma-client';
import { KnownErrors } from '@stackframe/stack-shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { getItemQuantityForCustomer, getSubscriptions, validatePurchaseSession } from './payments';
import type { Tenancy } from './tenancies';
Expand Down Expand Up @@ -842,7 +843,7 @@ describe('validatePurchaseSession - one-time purchase rules', () => {
},
priceId: 'price-any',
quantity: 1,
})).rejects.toThrowError('Customer already has purchased this product; this product is not stackable');
})).rejects.toThrowError(new KnownErrors.ProductAlreadyGranted('product-dup', 'cust-1'));
});

it('blocks one-time purchase when another one exists in the same group', async () => {
Expand Down Expand Up @@ -1003,7 +1004,7 @@ describe('validatePurchaseSession - one-time purchase rules', () => {
},
priceId: 'price-any',
quantity: 1,
})).rejects.toThrowError('Customer already has purchased this product; this product is not stackable');
})).rejects.toThrowError(new KnownErrors.ProductAlreadyGranted('product-sub', 'cust-1'));
});

it('allows when subscription for same product exists and product is stackable', async () => {
Expand Down Expand Up @@ -1205,4 +1206,3 @@ describe('getSubscriptions - defaults behavior', () => {
})).rejects.toThrowError('Multiple include-by-default products configured in the same catalog');
});
});

Loading
Loading