Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,730 @@
import { describe, expect, it, vi } from "vitest";
import {
addTenantSubscriptionProduct,
adminGetTenantSubscriptionProductById,
cancelTenantSubscriptionProduct,
createCheckoutSessionStatus,
createSubscriptionFeature,
createSubscriptionPrice,
createSubscriptionProduct,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
createTenantSubscription,
createTenantSubscriptionUsageRecord,
deleteSubscriptionFeatures,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
deleteSubscriptionUsageBasedPrice,
deleteSubscriptionUsageBasedTier,
findTenantSubscriptionProductByStripeSubscriptionId,
getEffectiveTenantEntitlementPlanId,
getAllSubscriptionFeatures,
getAllSubscriptionProducts,
getAllSubscriptionProductsWithTenants,
getSubscriptionPrice,
getSubscriptionPriceByStripeId,
getSubscriptionPrices,
getSubscriptionProduct,
getSubscriptionProductByStripeId,
getSubscriptionProductsInIds,
getSubscriptionUsageBasedPriceByStripeId,
getTenantSubscription,
getTenantSubscriptionProduct,
getTenantSubscriptionProductById,
getTenantSubscriptionProductByStripeSubscriptionId,
getTenantSubscriptions,
getAllTenantSubscriptionProducts,
getCheckoutSessionStatus,
listTenantSubscriptionIds,
updateCheckoutSessionStatus,
updateSubscriptionPrice,
updateSubscriptionPriceStripeId,
updateSubscriptionProduct,
updateSubscriptionProductStripeId,
updateTenantSubscriptionCustomerId,
updateTenantSubscriptionProduct,
updateTenantSubscriptionProductCustomEntitlementPlan,
updateTenantSubscriptionProductFromStripe,
type StripeTenantSubscriptionProductClient,
type SubscriptionCatalogClient,
type TenantBillingClient,
type TenantSubscriptionReaderClient,
} from "./subscriptions.server.js";
function createSubscriptionProductClient(items: unknown[] = []): SubscriptionCatalogClient {
return {
subscriptionProduct: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "plan_1" }),
},
subscriptionPrice: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "price_1" }),
},
subscriptionUsageBasedPrice: {
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_price_1" }),
},
subscriptionUsageBasedTier: {
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }),
delete: vi.fn().mockResolvedValue(items[0] ?? { id: "tier_1" }),
},
subscriptionFeature: {
findMany: vi.fn().mockResolvedValue(items),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "feature_1" }),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
},
} as unknown as SubscriptionCatalogClient;
}
function createTenantSubscriptionClient(items: unknown[] = []): TenantSubscriptionReaderClient {
return {
tenantSubscription: {
findMany: vi.fn().mockResolvedValue(items),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
},
} as unknown as TenantSubscriptionReaderClient;
}
function createStripeTenantSubscriptionProductClient(item: unknown = null): StripeTenantSubscriptionProductClient {
return {
tenantSubscriptionProduct: {
findFirst: vi.fn().mockResolvedValue(item),
update: vi.fn().mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }),
},
} as unknown as StripeTenantSubscriptionProductClient;
}
function createTenantBillingClient(items: unknown[] = []): TenantBillingClient {
return {
tenantSubscription: {
findMany: vi.fn().mockResolvedValue(items.length > 0 ? items : [{ tenantId: "tenant_1" }]),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", products: [] }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_sub_1", tenantId: "tenant_1", stripeCustomerId: "cus_1" }),
},
tenantSubscriptionProduct: {
findMany: vi.fn().mockResolvedValue(items),
count: vi.fn().mockResolvedValue(items.length),
findFirst: vi.fn().mockResolvedValue(items[0] ?? null),
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }),
},
checkoutSessionStatus: {
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
create: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: true }),
update: vi.fn().mockResolvedValue(items[0] ?? { id: "cs_1", pending: false }),
},
tenantSubscriptionUsageRecord: {
create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_1" }),
},
} as unknown as TenantBillingClient;
}
describe("subscription product reads", () => {
it("fetches public active products with details", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionProducts(true, client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { active: true, public: true },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("fetches all active products when public-only is not requested", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionProducts(false, client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { active: true },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("preserves legacy empty-list behavior when broad product reads fail", async () => {
const client = createSubscriptionProductClient([]);
vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(new Error("database unavailable"));
await expect(getAllSubscriptionProductsWithTenants(client)).resolves.toEqual([]);
});
it("fetches selected products by id without swallowing errors", async () => {
const client = createSubscriptionProductClient([]);
await expect(getSubscriptionProductsInIds(["plan_a", "plan_b"], client)).resolves.toEqual([]);
expect(client.subscriptionProduct.findMany).toHaveBeenCalledWith({
where: { id: { in: ["plan_a", "plan_b"] } },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
});
});
it("fetches one product by id", async () => {
const product = { id: "plan_a" };
const client = createSubscriptionProductClient([product]);
await expect(getSubscriptionProduct("plan_a", client)).resolves.toBe(product);
expect(client.subscriptionProduct.findUnique).toHaveBeenCalledWith({
where: { id: "plan_a" },
include: {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
});
});
it("fetches subscription feature summaries", async () => {
const client = createSubscriptionProductClient([]);
await expect(getAllSubscriptionFeatures(client)).resolves.toEqual([]);
expect(client.subscriptionFeature.findMany).toHaveBeenCalledWith({
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
});
});
});
describe("subscription catalog helpers", () => {
it("fetches a product by Stripe id", async () => {
const product = { id: "plan_a", stripeId: "prod_123" };
const client = createSubscriptionProductClient([product]);
await expect(getSubscriptionProductByStripeId("prod_123", client)).resolves.toBe(product);
expect(client.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeId: "prod_123" },
});
});
it("fetches prices with products in admin ordering", async () => {
const client = createSubscriptionProductClient([]);
await expect(getSubscriptionPrices(client)).resolves.toEqual([]);
expect(client.subscriptionPrice.findMany).toHaveBeenCalledWith({
include: { subscriptionProduct: true },
orderBy: [{ subscriptionProduct: { order: "asc" } }, { price: "asc" }],
});
});
it("keeps legacy null and empty read behavior for price lookup failures", async () => {
const client = createSubscriptionProductClient([]);
vi.mocked(client.subscriptionPrice.findMany).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionPrice.findUnique).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionPrice.findFirst).mockRejectedValueOnce(new Error("read failed"));
vi.mocked(client.subscriptionUsageBasedPrice.findFirst).mockRejectedValueOnce(new Error("read failed"));
await expect(getSubscriptionPrices(client)).resolves.toEqual([]);
await expect(getSubscriptionPrice("price_1", client)).resolves.toBeNull();
await expect(getSubscriptionPriceByStripeId("price_stripe_1", client)).resolves.toBeNull();
await expect(getSubscriptionUsageBasedPriceByStripeId("metered_stripe_1", client)).resolves.toBeNull();
});
it("creates catalog rows without coercing decimal-compatible values", async () => {
const client = createSubscriptionProductClient([]);
const productData = {
stripeId: "prod_123",
order: 1,
title: "Pro",
model: 1,
description: null,
badge: null,
groupTitle: null,
groupDescription: null,
active: true,
public: true,
billingAddressCollection: "auto",
hasQuantity: false,
canBuyAgain: false,
};
const priceData = {
subscriptionProductId: "plan_a",
stripeId: "price_123",
type: 1,
billingPeriod: 1,
price: "19.99",
currency: "usd",
trialDays: 0,
active: true,
};
const usagePriceData = {
subscriptionProductId: "plan_a",
stripeId: "metered_123",
currency: "usd",
billingPeriod: 1,
unit: "api_call",
unitTitle: "API call",
unitTitlePlural: "API calls",
usageType: "metered",
aggregateUsage: "sum",
tiersMode: "graduated",
billingScheme: "tiered",
};
const tierData = {
subscriptionUsageBasedPriceId: "usage_price_1",
from: 1,
to: null,
perUnitPrice: "0.10",
flatFeePrice: null,
};
await createSubscriptionProduct(productData, client);
await createSubscriptionPrice(priceData, client);
await createSubscriptionUsageBasedPrice(usagePriceData, client);
await createSubscriptionUsageBasedTier(tierData, client);
await createSubscriptionFeature("plan_a", {
order: 1,
title: "Seats",
name: "seats",
type: 1,
value: 5,
href: null,
badge: null,
accumulate: false,
}, client);
expect(client.subscriptionProduct.create).toHaveBeenCalledWith({ data: productData });
expect(client.subscriptionPrice.create).toHaveBeenCalledWith({ data: priceData });
expect(client.subscriptionUsageBasedPrice.create).toHaveBeenCalledWith({ data: usagePriceData });
expect(client.subscriptionUsageBasedTier.create).toHaveBeenCalledWith({ data: tierData });
expect(client.subscriptionFeature.create).toHaveBeenCalledWith({
data: {
subscriptionProductId: "plan_a",
order: 1,
title: "Seats",
name: "seats",
type: 1,
value: 5,
href: null,
badge: null,
accumulate: false,
},
});
});
it("updates product and price catalog rows", async () => {
const client = createSubscriptionProductClient([]);
await updateSubscriptionProduct("plan_a", { title: "Business", public: false }, client);
await updateSubscriptionProductStripeId("plan_a", { stripeId: "prod_new" }, client);
await updateSubscriptionPrice("price_a", { price: "29.99", active: false }, client);
await updateSubscriptionPriceStripeId("price_a", { stripeId: "price_new" }, client);
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(1, {
where: { id: "plan_a" },
data: { title: "Business", public: false },
});
expect(client.subscriptionProduct.update).toHaveBeenNthCalledWith(2, {
where: { id: "plan_a" },
data: { stripeId: "prod_new" },
});
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(1, {
where: { id: "price_a" },
data: { price: "29.99", active: false },
});
expect(client.subscriptionPrice.update).toHaveBeenNthCalledWith(2, {
where: { id: "price_a" },
data: { stripeId: "price_new" },
});
});
it("deletes catalog rows with direct ids and product-scoped features", async () => {
const client = createSubscriptionProductClient([]);
await deleteSubscriptionProduct("plan_a", client);
await deleteSubscriptionPrice("price_a", client);
await deleteSubscriptionUsageBasedTier("tier_a", client);
await deleteSubscriptionUsageBasedPrice("usage_price_a", client);
await deleteSubscriptionFeatures("plan_a", client);
expect(client.subscriptionProduct.delete).toHaveBeenCalledWith({ where: { id: "plan_a" } });
expect(client.subscriptionPrice.delete).toHaveBeenCalledWith({ where: { id: "price_a" } });
expect(client.subscriptionUsageBasedTier.delete).toHaveBeenCalledWith({ where: { id: "tier_a" } });
expect(client.subscriptionUsageBasedPrice.delete).toHaveBeenCalledWith({ where: { id: "usage_price_a" } });
expect(client.subscriptionFeature.deleteMany).toHaveBeenCalledWith({ where: { subscriptionProductId: "plan_a" } });
});
it("propagates mutation failures instead of hiding failed Stripe sync", async () => {
const client = createSubscriptionProductClient([]);
const error = new Error("write failed");
vi.mocked(client.subscriptionPrice.update).mockRejectedValueOnce(error);
await expect(updateSubscriptionPrice("price_a", { active: false }, client)).rejects.toBe(error);
});
});
describe("tenant subscription reads", () => {
it("fetches a tenant subscription with product details", async () => {
const subscription = { id: "sub_1" };
const client = createTenantSubscriptionClient([subscription]);
await expect(getTenantSubscription("tenant_1", client)).resolves.toBe(subscription);
expect(client.tenantSubscription.findUnique).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
});
it("fetches all tenant subscriptions with product details", async () => {
const client = createTenantSubscriptionClient([]);
await expect(getTenantSubscriptions(client)).resolves.toEqual([]);
expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
});
});
describe("tenant billing boundary", () => {
it("creates and updates tenant subscriptions", async () => {
const client = createTenantBillingClient([]);
await createTenantSubscription({ tenantId: "tenant_1", stripeCustomerId: "cus_1" }, client);
await updateTenantSubscriptionCustomerId("tenant_1", { stripeCustomerId: "cus_2" }, client);
await expect(listTenantSubscriptionIds(client)).resolves.toEqual([{ tenantId: "tenant_1" }]);
expect(client.tenantSubscription.create).toHaveBeenCalledWith({
data: { tenantId: "tenant_1", stripeCustomerId: "cus_1" },
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
},
},
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { stripeCustomerId: "cus_2" },
});
expect(client.tenantSubscription.findMany).toHaveBeenCalledWith({ select: { tenantId: true } });
});
it("maps tenant product filters and pagination for admin lists", async () => {
const now = new Date("2026-05-06T12:00:00.000Z");
const client = createTenantBillingClient([]);
await getAllTenantSubscriptionProducts(
{ tenantId: "tenant_1", subscriptionProductId: "plan_1", status: "active-not-cancelled" },
{ page: 2, pageSize: 25 },
client,
now,
);
const where = {
subscriptionProductId: { equals: "plan_1" },
tenantSubscription: { tenantId: { equals: "tenant_1" } },
OR: [{ endsAt: { gte: now } }, { endsAt: null }],
cancelledAt: null,
};
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenCalledWith({
skip: 25,
take: 25,
where,
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
tenantSubscription: {
include: {
tenant: {
select: {
id: true,
name: true,
slug: true,
icon: true,
logo: true,
deactivatedReason: true,
active: true,
theme: true,
themeConfig: true,
},
},
},
},
},
orderBy: { createdAt: "desc" },
});
expect(client.tenantSubscriptionProduct.count).toHaveBeenCalledWith({ where });
});
it("maps ended and active-cancelled tenant product filters", async () => {
const now = new Date("2026-05-06T12:00:00.000Z");
const client = createTenantBillingClient([]);
await getAllTenantSubscriptionProducts({ status: "ended" }, undefined, client, now);
await getAllTenantSubscriptionProducts({ status: "active-cancelled" }, undefined, client, now);
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
where: expect.objectContaining({ endsAt: { lt: now, not: null } }),
}),
);
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
where: expect.objectContaining({ OR: [{ endsAt: { gte: now } }, { endsAt: null }], cancelledAt: { not: null } }),
}),
);
});
it("looks up tenant products by tenant/product, id, and Stripe subscription id", async () => {
const item = { id: "tenant_product_1" };
const client = createTenantBillingClient([item]);
await expect(getTenantSubscriptionProduct("tenant_1", "plan_1", client)).resolves.toBe(item);
await expect(adminGetTenantSubscriptionProductById("tenant_product_1", client)).resolves.toBe(item);
await expect(getTenantSubscriptionProductById({ id: "tenant_product_1", tenantId: "tenant_1" }, client)).resolves.toBe(item);
await expect(getTenantSubscriptionProductByStripeSubscriptionId("sub_1", client)).resolves.toBe(item);
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(1, expect.objectContaining({
where: { tenantSubscription: { tenantId: "tenant_1" }, subscriptionProductId: "plan_1" },
}));
expect(client.tenantSubscriptionProduct.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "tenant_product_1" } }));
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } } }));
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenNthCalledWith(3, expect.objectContaining({ where: { stripeSubscriptionId: "sub_1" } }));
});
it("uses the billing product id when no custom entitlement override exists", () => {
expect(
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: null,
}),
).toBe("plan_standard");
});
it("uses the custom entitlement override ahead of the billing product id", () => {
expect(
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: "entitlements_enterprise_override",
}),
).toBe("entitlements_enterprise_override");
});
it("adds, updates, and cancels tenant products while returning tenant ids for cache invalidation", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
await addTenantSubscriptionProduct(
{
tenantSubscriptionId: "tenant_sub_1",
subscriptionProductId: "plan_1",
stripeSubscriptionId: "sub_1",
quantity: 2,
fromCheckoutSessionId: "cs_1",
prices: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }],
},
client,
);
await updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 3, endsAt: null }, client);
await expect(
cancelTenantSubscriptionProduct(
{ id: "tenant_product_1", tenantId: "tenant_1" },
{ cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") },
client,
),
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.create).toHaveBeenCalledWith({
data: {
tenantSubscriptionId: "tenant_sub_1",
subscriptionProductId: "plan_1",
stripeSubscriptionId: "sub_1",
quantity: 2,
fromCheckoutSessionId: "cs_1",
customEntitlementPlanId: undefined,
endsAt: null,
cancelledAt: null,
prices: { create: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }] },
},
include: { tenantSubscription: true },
});
expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(1, {
where: { id: "tenant_product_1" },
data: { quantity: 3, endsAt: null },
include: { tenantSubscription: true },
});
expect(client.tenantSubscriptionProduct.update).toHaveBeenNthCalledWith(2, {
where: { id: "tenant_product_1" },
data: { cancelledAt: new Date("2026-05-06T00:00:00.000Z"), endsAt: new Date("2026-06-06T00:00:00.000Z") },
include: { tenantSubscription: true },
});
});
it("updates only the custom entitlement plan override and returns tenant id", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
await expect(
updateTenantSubscriptionProductCustomEntitlementPlan(
{ id: "tenant_product_1", tenantId: "tenant_1" },
{ customEntitlementPlanId: "entitlements_scale_override" },
client,
),
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data: { customEntitlementPlanId: "entitlements_scale_override" },
select: {
tenantSubscription: {
select: {
tenantId: true,
},
},
},
});
});
it("propagates custom entitlement override update rejections", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
const error = new Error("write rejected");
vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error);
await expect(
updateTenantSubscriptionProductCustomEntitlementPlan({ id: "tenant_product_1", tenantId: "tenant_1" }, { customEntitlementPlanId: null }, client),
).rejects.toBe(error);
});
it("handles checkout status idempotency reads, creates, updates, and missing status", async () => {
const client = createTenantBillingClient([]);
vi.mocked(client.checkoutSessionStatus.findUnique).mockResolvedValueOnce(null);
await expect(getCheckoutSessionStatus("cs_missing", client)).resolves.toBeNull();
await createCheckoutSessionStatus({ id: "cs_1", email: "user@example.com", fromUrl: "/subscribe/acme" }, client);
await updateCheckoutSessionStatus("cs_1", { pending: false, createdUserId: "user_1" }, client);
expect(client.checkoutSessionStatus.create).toHaveBeenCalledWith({
data: { id: "cs_1", pending: true, email: "user@example.com", fromUrl: "/subscribe/acme", fromUserId: null, fromTenantId: null },
});
expect(client.checkoutSessionStatus.update).toHaveBeenCalledWith({
where: { id: "cs_1" },
data: { pending: false, createdUserId: "user_1", createdTenantId: null },
});
});
it("creates usage records and propagates write rejections", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
const usageData = {
tenantSubscriptionProductPriceId: "tenant_price_1",
timestamp: 1_777_777,
quantity: 1,
stripeSubscriptionItemId: "si_1",
};
await createTenantSubscriptionUsageRecord(usageData, client);
expect(client.tenantSubscriptionUsageRecord.create).toHaveBeenCalledWith({ data: usageData });
const error = new Error("write rejected");
vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error);
await expect(updateTenantSubscriptionProduct({ id: "tenant_product_1", tenantId: "tenant_1" }, { quantity: 4 }, client)).rejects.toBe(error);
});
});
describe("stripe tenant subscription products", () => {
it("fetches the tenant subscription product needed by Stripe webhooks", async () => {
const item = { id: "tenant_product_1" };
const client = createStripeTenantSubscriptionProductClient(item);
await expect(findTenantSubscriptionProductByStripeSubscriptionId("sub_123", client)).resolves.toBe(item);
expect(client.tenantSubscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeSubscriptionId: "sub_123" },
select: {
id: true,
endsAt: true,
cancelledAt: true,
customEntitlementPlanId: true,
tenantSubscription: {
select: {
tenantId: true,
tenant: {
select: {
id: true,
name: true,
},
},
},
},
subscriptionProduct: {
select: {
id: true,
title: true,
},
},
},
});
});
it("updates Stripe subscription dates and returns the owning tenant id", async () => {
const client = createStripeTenantSubscriptionProductClient();
const data = {
cancelledAt: new Date("2026-05-01T00:00:00.000Z"),
currentPeriodStart: new Date("2026-05-01T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-06-01T00:00:00.000Z"),
endsAt: null,
};
await expect(updateTenantSubscriptionProductFromStripe("tenant_product_1", data, client)).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data,
select: {
tenantSubscription: {
select: {
tenantId: true,
},
},
},
});
});
});