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
@@ -1,14 +1,17 @@
import { ensureCustomerExists, getItemQuantityForCustomer } from "@/lib/payments";
import { getPrismaClientForTenancy } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { KnownErrors } from "@stackframe/stack-shared";
import { adaptSchema, clientOrHigherAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { ensureCustomerExists, getItemQuantityForCustomer } from "@/lib/payments";
import { getOrUndefined } from "@stackframe/stack-shared/dist/utils/objects";


export const GET = createSmartRouteHandler({
metadata: {
hidden: true,
hidden: false,
summary: "Get Item",
description: "Retrieves information about a specific item (credits, quotas, etc.) for a customer.",
tags: ["Payments"],
},
request: yupObject({
auth: yupObject({
Expand All @@ -17,18 +20,48 @@ export const GET = createSmartRouteHandler({
tenancy: adaptSchema.defined(),
}).defined(),
params: yupObject({
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
item_id: yupString().defined(),
customer_type: yupString().oneOf(["user", "team", "custom"]).defined().meta({
openapiField: {
description: "The type of customer",
exampleValue: "user"
}
}),
customer_id: yupString().defined().meta({
openapiField: {
description: "The ID of the customer",
exampleValue: "user_1234567890abcdef"
}
}),
item_id: yupString().defined().meta({
openapiField: {
description: "The ID of the item to retrieve",
exampleValue: "credits"
}
}),
}).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
id: yupString().defined(),
display_name: yupString().defined(),
quantity: yupNumber().defined(),
id: yupString().defined().meta({
openapiField: {
description: "The ID of the item",
exampleValue: "credits"
}
}),
display_name: yupString().defined().meta({
openapiField: {
description: "The human-readable name of the item",
exampleValue: "API Credits"
}
}),
quantity: yupNumber().defined().meta({
openapiField: {
description: "The current quantity of the item (can be negative)",
exampleValue: 1000
}
}),
}).defined(),
}),
handler: async (req) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { adaptSchema, serverOrHigherAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { ensureCustomerExists, getItemQuantityForCustomer } from "@/lib/payments";
import { getPrismaClientForTenancy, retryTransaction } from "@/prisma-client";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { KnownErrors } from "@stackframe/stack-shared";
import { adaptSchema, serverOrHigherAuthTypeSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { getOrUndefined } from "@stackframe/stack-shared/dist/utils/objects";
import { typedToUppercase } from "@stackframe/stack-shared/dist/utils/strings";

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
hidden: false,
summary: "Update Item Quantity",
description: "Updates the quantity of an item for a customer. Can increase or decrease quantities, with optional expiration and negative balance control.",
tags: ["Payments"],
},
request: yupObject({
auth: yupObject({
Expand All @@ -17,25 +20,58 @@ export const POST = createSmartRouteHandler({
tenancy: adaptSchema.defined(),
}).defined(),
params: yupObject({
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
item_id: yupString().defined(),
customer_type: yupString().oneOf(["user", "team", "custom"]).defined().meta({
openapiField: {
description: "The type of customer",
exampleValue: "user"
}
}),
customer_id: yupString().defined().meta({
openapiField: {
description: "The ID of the customer",
exampleValue: "user_1234567890abcdef"
}
}),
item_id: yupString().defined().meta({
openapiField: {
description: "The ID of the item to update",
exampleValue: "credits"
}
}),
}).defined(),
query: yupObject({
allow_negative: yupString().oneOf(["true", "false"]).defined(),
allow_negative: yupString().oneOf(["true", "false"]).defined().meta({
openapiField: {
description: "Whether to allow the quantity to go negative",
exampleValue: "false"
}
}),
}).defined(),
body: yupObject({
delta: yupNumber().integer().defined(),
expires_at: yupString().optional(),
description: yupString().optional(),
delta: yupNumber().integer().defined().meta({
openapiField: {
description: "The amount to change the quantity by (positive to increase, negative to decrease)",
exampleValue: 100
}
}),
expires_at: yupString().optional().meta({
openapiField: {
description: "Optional expiration date for this quantity change (ISO 8601 format)",
exampleValue: "2024-12-31T23:59:59Z"
}
}),
description: yupString().optional().meta({
openapiField: {
description: "Optional description for this quantity change",
exampleValue: "Monthly subscription renewal"
}
}),
}).defined(),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
id: yupString().defined(),
}).defined(),
body: yupObject({}).defined(),
}),
handler: async (req) => {
const { tenancy } = req.auth;
Expand All @@ -57,7 +93,7 @@ export const POST = createSmartRouteHandler({
customerId: req.params.customer_id,
});

const changeId = await retryTransaction(prisma, async (tx) => {
await retryTransaction(prisma, async (tx) => {
const totalQuantity = await getItemQuantityForCustomer({
prisma: tx,
tenancy,
Expand All @@ -68,7 +104,7 @@ export const POST = createSmartRouteHandler({
if (!allowNegative && (totalQuantity + req.body.delta < 0)) {
throw new KnownErrors.ItemQuantityInsufficientAmount(req.params.item_id, req.params.customer_id, req.body.delta);
}
const change = await tx.itemQuantityChange.create({
await tx.itemQuantityChange.create({
data: {
tenancyId: tenancy.id,
customerId: req.params.customer_id,
Expand All @@ -79,13 +115,12 @@ export const POST = createSmartRouteHandler({
expiresAt: req.body.expires_at ? new Date(req.body.expires_at) : null,
},
});
return change.id;
});

return {
statusCode: 200,
bodyType: "json",
body: { id: changeId },
body: {},
};
},
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import { purchaseUrlVerificationCodeHandler } from "../verification-code-handler

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
hidden: false,
summary: "Create Purchase URL",
description: "Creates a secure checkout URL for purchasing a product.",
tags: ["Payments"],
},
request: yupObject({
auth: yupObject({
Expand All @@ -21,18 +24,46 @@ export const POST = createSmartRouteHandler({
tenancy: adaptSchema.defined(),
}).defined(),
body: yupObject({
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
product_id: yupString().optional(),
product_inline: inlineProductSchema.optional(),
return_url: urlSchema.optional(),
customer_type: yupString().oneOf(["user", "team", "custom"]).defined().meta({
openapiField: {
description: "The type of customer making the purchase",
exampleValue: "user"
}
}),
customer_id: yupString().defined().meta({
openapiField: {
description: "The ID of the customer (user ID, team ID, or custom customer ID)",
exampleValue: "user_1234567890abcdef"
}
}),
product_id: yupString().optional().meta({
openapiField: {
description: "The ID of the product to purchase. Either this or product_inline should be given.",
exampleValue: "prod_premium_monthly"
}
}),
product_inline: inlineProductSchema.optional().meta({
openapiField: {
description: "Inline product definition. Either this or product_id should be given."
}
}),
return_url: urlSchema.optional().meta({
openapiField: {
description: "URL to redirect to after purchase completion. Must be configured as a trusted domain in the project configuration.",
exampleValue: "https://myapp.com/purchase-success"
}
}),
}),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
url: yupString().defined(),
url: yupString().defined().meta({
openapiField: {
description: "The secure checkout URL for completing the purchase"
}
}),
}).defined(),
}),
handler: async (req) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,43 @@ import { purchaseUrlVerificationCodeHandler } from "../verification-code-handler

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
hidden: false,
summary: "Create Purchase Session",
description: "Creates a purchase session for completing a purchase.",
tags: ["Payments"],
},
request: yupObject({
body: yupObject({
full_code: yupString().defined(),
price_id: yupString().defined(),
quantity: yupNumber().integer().min(1).default(1),
full_code: yupString().defined().meta({
openapiField: {
description: "The verification code, given as a query parameter in the purchase URL",
exampleValue: "proj_abc123_def456ghi789"
}
}),
price_id: yupString().defined().meta({
openapiField: {
description: "The Stripe price ID to purchase",
exampleValue: "price_1234567890abcdef"
}
}),
quantity: yupNumber().integer().min(1).default(1).meta({
openapiField: {
description: "The quantity to purchase",
exampleValue: 1
}
}),
}),
}),
response: yupObject({
statusCode: yupNumber().oneOf([200]).defined(),
bodyType: yupString().oneOf(["json"]).defined(),
body: yupObject({
client_secret: yupString().defined(),
client_secret: yupString().defined().meta({
openapiField: {
description: "The Stripe client secret for completing the payment",
exampleValue: "1234567890abcdef_secret_xyz123"
}
}),
}),
}),
async handler({ body }) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,25 @@ import { purchaseUrlVerificationCodeHandler } from "../verification-code-handler

export const POST = createSmartRouteHandler({
metadata: {
hidden: true,
hidden: false,
summary: "Validate Purchase Code",
description: "Validates a purchase verification code and returns purchase details including available prices.",
tags: ["Payments"],
},
request: yupObject({
body: yupObject({
full_code: yupString().defined(),
return_url: urlSchema.optional(),
full_code: yupString().defined().meta({
openapiField: {
description: "The verification code, given as a query parameter in the purchase URL",
exampleValue: "proj_abc123_def456ghi789"
}
}),
return_url: urlSchema.optional().meta({
openapiField: {
description: "URL to redirect to after purchase completion",
exampleValue: "https://myapp.com/purchase-success"
}
}),
}),
}),
response: yupObject({
Expand Down
11 changes: 11 additions & 0 deletions apps/backend/src/lib/openapi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ function getFieldSchema(field: yup.SchemaFieldDescription, crudOperation?: Capit
case 'array': {
return { type: 'array', items: getFieldSchema((field as any).innerType, crudOperation), ...openapiFieldExtra };
}
case 'tuple': {
// For OpenAPI, treat tuples as arrays since OpenAPI doesn't have native tuple support
// This is commonly used for headers which are arrays of strings
const tupleField = field as any;
if (tupleField.innerType && tupleField.innerType.length > 0) {
// Use the first element's schema as the array item type
return { type: 'array', items: getFieldSchema(tupleField.innerType[0], crudOperation), ...openapiFieldExtra };
}
// Fallback to string array if no inner type
return { type: 'array', items: { type: 'string' }, ...openapiFieldExtra };
}
default: {
throw new Error(`Unsupported field type: ${field.type}`);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ it("should return ItemCustomerTypeDoesNotMatch error for user accessing team ite
`);
});

it("creates an item quantity change and returns id", async ({ expect }) => {
it("creates an item quantity change successfully", async ({ expect }) => {
await Project.createAndSwitch();
await updateConfig({
payments: {
Expand All @@ -162,7 +162,7 @@ it("creates an item quantity change and returns id", async ({ expect }) => {
});

expect(response.status).toBe(200);
expect(response.body).toMatchObject({ id: expect.any(String) });
expect(response.body).toMatchObject({});
});

it("aggregates item quantity changes in item quantity", async ({ expect }) => {
Expand Down Expand Up @@ -415,7 +415,7 @@ it("should allow negative quantity changes when allow_negative is true", async (
expect(response).toMatchInlineSnapshot(`
NiceResponse {
"status": 200,
"body": { "id": "<stripped UUID>" },
"body": {},
"headers": Headers { <some fields may have been hidden> },
}
`);
Expand Down
6 changes: 6 additions & 0 deletions docs/docs-platform.yml
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,12 @@ pages:
- path: sdk/types/email.mdx
platforms: ["next", "react", "js"] # No Python

- path: sdk/types/customer.mdx
platforms: ["next", "react", "js"] # No Python

- path: sdk/types/item.mdx
platforms: ["next", "react", "js"] # No Python

# SDK Hooks (React-like only)
- path: sdk/hooks/use-stack-app.mdx
platforms: ["next", "react"] # No JS or Python
Expand Down
Loading
Loading