Skip to content

Custom item customers #855

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: dev
Choose a base branch
from
Open
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,15 @@
/*
Warnings:

- Added the required column `customerType` to the `ItemQuantityChange` table without a default value. This is not possible if the table is not empty.

*/
-- AlterEnum
ALTER TYPE "CustomerType" ADD VALUE 'CUSTOM';

-- AlterTable
ALTER TABLE "ItemQuantityChange" ADD COLUMN "customerType" "CustomerType" NOT NULL,
ALTER COLUMN "customerId" SET DATA TYPE TEXT;

-- AlterTable
ALTER TABLE "Subscription" ALTER COLUMN "customerId" SET DATA TYPE TEXT;
22 changes: 12 additions & 10 deletions apps/backend/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ model Project {
displayName String
description String @default("")
isProductionMode Boolean
ownerTeamId String? @db.Uuid
ownerTeamId String? @db.Uuid
logoUrl String?
fullLogoUrl String?

Expand Down Expand Up @@ -715,6 +715,7 @@ model ThreadMessage {
enum CustomerType {
USER
TEAM
CUSTOM
}

enum SubscriptionStatus {
Expand All @@ -731,7 +732,7 @@ enum SubscriptionStatus {
model Subscription {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerId String @db.Uuid
customerId String
customerType CustomerType
offer Json

Expand All @@ -749,14 +750,15 @@ model Subscription {
}

model ItemQuantityChange {
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerId String @db.Uuid
itemId String
quantity Int
description String?
expiresAt DateTime?
createdAt DateTime @default(now())
id String @default(uuid()) @db.Uuid
tenancyId String @db.Uuid
customerType CustomerType
customerId String
itemId String
quantity Int
description String?
expiresAt DateTime?
createdAt DateTime @default(now())

@@id([tenancyId, id])
@@index([tenancyId, customerId, expiresAt])
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { ensureItemCustomerTypeMatches, 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";


Expand All @@ -17,6 +17,7 @@ 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(),
}).defined(),
Expand All @@ -38,16 +39,23 @@ export const GET = createSmartRouteHandler({
if (!itemConfig) {
throw new KnownErrors.ItemNotFound(req.params.item_id);
}

await ensureItemCustomerTypeMatches(req.params.item_id, itemConfig.customerType, req.params.customer_id, tenancy);
if (req.params.customer_type !== itemConfig.customerType) {
throw new KnownErrors.ItemCustomerTypeDoesNotMatch(req.params.item_id, req.params.customer_id, itemConfig.customerType, req.params.customer_type);
}
const prisma = await getPrismaClientForTenancy(tenancy);
await ensureCustomerExists({
prisma,
tenancyId: tenancy.id,
customerType: req.params.customer_type,
customerId: req.params.customer_id,
});
const totalQuantity = await getItemQuantityForCustomer({
prisma,
tenancy,
itemId: req.params.item_id,
customerId: req.params.customer_id,
customerType: req.params.customer_type,
});

return {
statusCode: 200,
bodyType: "json",
Expand All @@ -59,3 +67,5 @@ export const GET = createSmartRouteHandler({
};
},
});


Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ensureItemCustomerTypeMatches, getItemQuantityForCustomer } from "@/lib/payments";
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: {
Expand All @@ -16,6 +17,7 @@ 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(),
}).defined(),
Expand Down Expand Up @@ -44,15 +46,24 @@ export const POST = createSmartRouteHandler({
throw new KnownErrors.ItemNotFound(req.params.item_id);
}

await ensureItemCustomerTypeMatches(req.params.item_id, itemConfig.customerType, req.params.customer_id, tenancy);
if (req.params.customer_type !== itemConfig.customerType) {
throw new KnownErrors.ItemCustomerTypeDoesNotMatch(req.params.item_id, req.params.customer_id, itemConfig.customerType, req.params.customer_type);
}
const prisma = await getPrismaClientForTenancy(tenancy);
await ensureCustomerExists({
prisma,
tenancyId: tenancy.id,
customerType: req.params.customer_type,
customerId: req.params.customer_id,
});

const changeId = await retryTransaction(prisma, async (tx) => {
const totalQuantity = await getItemQuantityForCustomer({
prisma: tx,
tenancy,
itemId: req.params.item_id,
customerId: req.params.customer_id,
customerType: req.params.customer_type,
});
if (!allowNegative && (totalQuantity + req.body.delta < 0)) {
throw new KnownErrors.ItemQuantityInsufficientAmount(req.params.item_id, req.params.customer_id, req.body.delta);
Expand All @@ -61,6 +72,7 @@ export const POST = createSmartRouteHandler({
data: {
tenancyId: tenancy.id,
customerId: req.params.customer_id,
customerType: typedToUppercase(req.params.customer_type),
itemId: req.params.item_id,
quantity: req.body.delta,
description: req.body.description,
Expand All @@ -77,3 +89,5 @@ export const POST = createSmartRouteHandler({
};
},
});


Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ensureOfferCustomerTypeMatches, ensureOfferIdOrInlineOffer } from "@/lib/payments";
import { adaptSchema, clientOrHigherAuthTypeSchema, inlineOfferSchema, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields";
import { ensureOfferIdOrInlineOffer } from "@/lib/payments";
import { getStripeForAccount } from "@/lib/stripe";
import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler";
import { adaptSchema, clientOrHigherAuthTypeSchema, inlineOfferSchema, 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";
import { CustomerType } from "@prisma/client";
import { KnownErrors } from "@stackframe/stack-shared/dist/known-errors";

export const POST = createSmartRouteHandler({
metadata: {
Expand All @@ -18,7 +19,8 @@ export const POST = createSmartRouteHandler({
tenancy: adaptSchema.defined(),
}).defined(),
body: yupObject({
customer_id: yupString().uuid().defined(),
customer_type: yupString().oneOf(["user", "team", "custom"]).defined(),
customer_id: yupString().defined(),
offer_id: yupString().optional(),
offer_inline: inlineOfferSchema.optional(),
}),
Expand All @@ -34,8 +36,10 @@ export const POST = createSmartRouteHandler({
const { tenancy } = req.auth;
const stripe = getStripeForAccount({ tenancy });
const offerConfig = await ensureOfferIdOrInlineOffer(tenancy, req.auth.type, req.body.offer_id, req.body.offer_inline);
await ensureOfferCustomerTypeMatches(req.body.offer_id, offerConfig.customerType, req.body.customer_id, tenancy);
const customerType = offerConfig.customerType ?? throwErr("Customer type not found");
if (req.body.customer_type !== customerType) {
throw new KnownErrors.OfferCustomerTypeDoesNotMatch(req.body.offer_id, req.body.customer_id, customerType, req.body.customer_type);
}

const stripeCustomerSearch = await stripe.customers.search({
query: `metadata['customerId']:'${req.body.customer_id}'`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export const teamInvitationCodeHandler = createVerificationCodeHandler({
tenancy,
customerId: data.team_id,
itemId: "dashboard_admins",
customerType: "team",
});
if (currentMemberCount + 1 > maxDashboardAdmins) {
throw new KnownErrors.ItemQuantityInsufficientAmount("dashboard_admins", data.team_id, -1);
Expand Down
115 changes: 47 additions & 68 deletions apps/backend/src/lib/payments.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { teamsCrudHandlers } from "@/app/api/latest/teams/crud";
import { usersCrudHandlers } from "@/app/api/latest/users/crud";
import { PrismaClientTransaction } from "@/prisma-client";
import { SubscriptionStatus } from "@prisma/client";
import { KnownErrors } from "@stackframe/stack-shared";
import { inlineOfferSchema, offerSchema } from "@stackframe/stack-shared/dist/schema-fields";
import { typedToUppercase } from "@stackframe/stack-shared/dist/utils/strings";
import { SUPPORTED_CURRENCIES } from "@stackframe/stack-shared/dist/utils/currencies";
import { StackAssertionError, StatusError } from "@stackframe/stack-shared/dist/utils/errors";
import { getOrUndefined, typedFromEntries } from "@stackframe/stack-shared/dist/utils/objects";
import * as yup from "yup";
import { Tenancy } from "./tenancies";
import { SUPPORTED_CURRENCIES } from "@stackframe/stack-shared/dist/utils/currencies";
import { SubscriptionStatus } from "@prisma/client";
import { PrismaClientTransaction } from "@/prisma-client";
import { isUuid } from "@stackframe/stack-shared/dist/utils/uuids";

export async function ensureOfferIdOrInlineOffer(
tenancy: Tenancy,
Expand Down Expand Up @@ -56,80 +56,19 @@ export async function ensureOfferIdOrInlineOffer(
}
}

export async function ensureItemCustomerTypeMatches(itemId: string, itemCustomerType: "user" | "team" | undefined, customerId: string, tenancy: Tenancy) {
const actualCustomerType = await getCustomerType(tenancy, customerId);
if (itemCustomerType !== actualCustomerType) {
throw new KnownErrors.ItemCustomerTypeDoesNotMatch(itemId, customerId, itemCustomerType, actualCustomerType);
}
}

export async function ensureOfferCustomerTypeMatches(offerId: string | undefined, offerCustomerType: "user" | "team" | undefined, customerId: string, tenancy: Tenancy) {
const actualCustomerType = await getCustomerType(tenancy, customerId);
if (offerCustomerType !== actualCustomerType) {
throw new KnownErrors.OfferCustomerTypeDoesNotMatch(offerId, customerId, offerCustomerType, actualCustomerType);
}
}

export async function getCustomerType(tenancy: Tenancy, customerId: string) {
let user;
try {
user = await usersCrudHandlers.adminRead(
{
user_id: customerId,
tenancy,
allowedErrorTypes: [
KnownErrors.UserNotFound,
],
}
);
} catch (e) {
if (KnownErrors.UserNotFound.isInstance(e)) {
user = null;
} else {
throw e;
}
}
let team;
try {
team = await teamsCrudHandlers.adminRead({
team_id: customerId,
tenancy,
allowedErrorTypes: [
KnownErrors.TeamNotFound,
],
});
} catch (e) {
if (KnownErrors.TeamNotFound.isInstance(e)) {
team = null;
} else {
throw e;
}
}

if (user && team) {
throw new StackAssertionError("Found a customer that is both user and team at the same time? This should never happen!", { customerId, user, team, tenancy });
}

if (user) {
return "user";
}
if (team) {
return "team";
}
throw new KnownErrors.CustomerDoesNotExist(customerId);
}

export async function getItemQuantityForCustomer(options: {
prisma: PrismaClientTransaction,
tenancy: Tenancy,
itemId: string,
customerId: string,
customerType: "user" | "team" | "custom",
}) {
const itemConfig = getOrUndefined(options.tenancy.config.payments.items, options.itemId);
const defaultQuantity = itemConfig?.default.quantity ?? 0;
const subscriptions = await options.prisma.subscription.findMany({
where: {
tenancyId: options.tenancy.id,
customerType: typedToUppercase(options.customerType),
customerId: options.customerId,
status: {
in: [SubscriptionStatus.active, SubscriptionStatus.trialing],
Expand All @@ -146,6 +85,7 @@ export async function getItemQuantityForCustomer(options: {
const { _sum } = await options.prisma.itemQuantityChange.aggregate({
where: {
tenancyId: options.tenancy.id,
customerType: typedToUppercase(options.customerType),
customerId: options.customerId,
itemId: options.itemId,
OR: [
Expand All @@ -159,3 +99,42 @@ export async function getItemQuantityForCustomer(options: {
});
return subscriptionQuantity + (_sum.quantity ?? 0) + defaultQuantity;
}

export async function ensureCustomerExists(options: {
prisma: PrismaClientTransaction,
tenancyId: string,
customerType: "user" | "team" | "custom",
customerId: string,
}) {
if (options.customerType === "user") {
if (!isUuid(options.customerId)) {
throw new KnownErrors.UserNotFound();
}
const user = await options.prisma.projectUser.findUnique({
where: {
tenancyId_projectUserId: {
tenancyId: options.tenancyId,
projectUserId: options.customerId,
},
},
});
if (!user) {
throw new KnownErrors.UserNotFound();
}
} else if (options.customerType === "team") {
if (!isUuid(options.customerId)) {
throw new KnownErrors.TeamNotFound(options.customerId);
}
const team = await options.prisma.team.findUnique({
where: {
tenancyId_teamId: {
tenancyId: options.tenancyId,
teamId: options.customerId,
},
},
});
if (!team) {
throw new KnownErrors.TeamNotFound(options.customerId);
}
}
}
Loading