Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,9 +1,12 @@
import { describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "./rls-context.server.js";
import {
addTenantSubscriptionProduct,
adminGetTenantSubscriptionProductById,
cancelTenantSubscriptionProduct,
claimCheckoutSessionStatus,
correlateCheckoutSessionProviderInvoice,
createCheckoutSessionStatus,
createSubscriptionFeature,
createSubscriptionPrice,
@@ -21,7 +24,9 @@ import {
getEffectiveTenantEntitlementPlanId,
getAllSubscriptionFeatures,
getAllSubscriptionProducts,
getAllSubscriptionProductsStrict,
getAllSubscriptionProductsWithTenants,
getSubscriptionProductTenantUsageCounts,
getSubscriptionPrice,
getSubscriptionPriceByBillingProviderId,
getSubscriptionPrices,
@@ -38,6 +43,7 @@ import {
getCheckoutSessionStatus,
listTenantSubscriptionIds,
updateCheckoutSessionStatus,
transitionClaimedCheckoutSessionStatus,
updateSubscriptionPrice,
updateSubscriptionPriceBillingProviderId,
updateSubscriptionProduct,
@@ -48,6 +54,7 @@ import {
updateTenantSubscriptionProductFromBillingProvider,
type BillingProviderTenantSubscriptionProductClient,
type SubscriptionCatalogClient,
type SubscriptionProductUsageClient,
type TenantBillingClient,
type TenantSubscriptionReaderClient,
} from "./subscriptions.server.js";
@@ -122,9 +129,10 @@ function createTenantBillingClient(items: unknown[] = []): TenantBillingClient {
update: vi.fn().mockResolvedValue(items[0] ?? { id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }),
},
checkoutSessionStatus: {
findUnique: vi.fn().mockResolvedValue(items[0] ?? null),
findFirst: 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 }),
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
},
tenantSubscriptionUsageRecord: {
create: vi.fn().mockResolvedValue(items[0] ?? { id: "usage_1" }),
@@ -143,7 +151,6 @@ describe("subscription product reads", () => {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
@@ -160,7 +167,6 @@ describe("subscription product reads", () => {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
@@ -174,6 +180,60 @@ describe("subscription product reads", () => {
await expect(getAllSubscriptionProductsWithTenants(client)).resolves.toEqual([]);
});
it("propagates catalog read failures for strict bootstrap callers", async () => {
const client = createSubscriptionProductClient([]);
const error = new Error("database unavailable");
vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(error);
await expect(getAllSubscriptionProductsStrict(true, client)).rejects.toBe(error);
});
it("keeps the legacy empty-list fallback for non-bootstrap catalog callers", async () => {
const client = createSubscriptionProductClient([]);
vi.mocked(client.subscriptionProduct.findMany).mockRejectedValueOnce(new Error("database unavailable"));
await expect(getAllSubscriptionProducts(true, client)).resolves.toEqual([]);
});
it("aggregates catalog usage inside each tenant boundary for platform operators", async () => {
const client: SubscriptionProductUsageClient = {
adminUser: { findUnique: vi.fn().mockResolvedValue({ id: "operator_1" }) },
tenant: { findMany: vi.fn().mockResolvedValue([{ id: "tenant_a" }, { id: "tenant_b" }]) },
tenantSubscriptionProduct: {
findMany: vi.fn(async () => {
const tenantId = getRlsExecutionContext()?.tenantId;
if (tenantId === "tenant_a") return [{ subscriptionProductId: "plan_1" }, { subscriptionProductId: "plan_2" }];
if (tenantId === "tenant_b") return [{ subscriptionProductId: "plan_1" }];
throw new Error("tenant context missing");
}),
},
};
await expect(runWithRlsContext({ userId: "operator_1" }, () => getSubscriptionProductTenantUsageCounts(client))).resolves.toEqual({ plan_1: 2, plan_2: 1 });
expect(client.adminUser.findUnique).toHaveBeenCalledWith({
where: { id: "operator_1" },
select: { id: true },
});
expect(client.tenantSubscriptionProduct.findMany).toHaveBeenCalledTimes(2);
});
it("rejects catalog usage aggregation outside a root platform-operator context", async () => {
const client: SubscriptionProductUsageClient = {
adminUser: { findUnique: vi.fn().mockResolvedValue(null) },
tenant: { findMany: vi.fn() },
tenantSubscriptionProduct: { findMany: vi.fn() },
};
await expect(getSubscriptionProductTenantUsageCounts(client)).rejects.toThrow("root platform-operator context");
await expect(runWithRlsContext({ userId: "member_1" }, () => getSubscriptionProductTenantUsageCounts(client))).rejects.toThrow(
"requires a platform operator"
);
await expect(runWithRlsContext({ userId: "operator_1", tenantId: "tenant_a" }, () => getSubscriptionProductTenantUsageCounts(client))).rejects.toThrow(
"root platform-operator context"
);
expect(client.tenant.findMany).not.toHaveBeenCalled();
});
it("fetches selected products by id without swallowing errors", async () => {
const client = createSubscriptionProductClient([]);
@@ -184,7 +244,6 @@ describe("subscription product reads", () => {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
orderBy: { order: "asc" },
@@ -202,7 +261,6 @@ describe("subscription product reads", () => {
tenantProducts: true,
usageBasedPrices: { include: { tiers: { orderBy: { from: "asc" } } } },
prices: true,
assignsTenantTypes: true,
features: { orderBy: { order: "asc" } },
},
});
@@ -304,16 +362,20 @@ describe("subscription catalog helpers", () => {
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);
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 });
@@ -397,6 +459,7 @@ describe("tenant subscription reads", () => {
products: {
include: {
subscriptionProduct: { include: { features: true } },
acquisition: true,
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
@@ -414,6 +477,7 @@ describe("tenant subscription reads", () => {
products: {
include: {
subscriptionProduct: { include: { features: true } },
acquisition: true,
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
@@ -437,6 +501,7 @@ describe("tenant billing boundary", () => {
products: {
include: {
subscriptionProduct: { include: { features: true } },
acquisition: true,
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
},
orderBy: { subscriptionProduct: { order: "desc" } },
@@ -458,7 +523,7 @@ describe("tenant billing boundary", () => {
{ tenantId: "tenant_1", subscriptionProductId: "plan_1", status: "active-not-cancelled" },
{ page: 2, pageSize: 25 },
client,
now,
now
);
const where = {
@@ -473,6 +538,7 @@ describe("tenant billing boundary", () => {
where,
include: {
subscriptionProduct: { include: { features: true } },
acquisition: true,
prices: { include: { subscriptionPrice: true, subscriptionUsageBasedPrice: { include: { tiers: true } } } },
tenantSubscription: {
include: {
@@ -508,13 +574,13 @@ describe("tenant billing boundary", () => {
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 } }),
}),
})
);
});
@@ -527,12 +593,21 @@ describe("tenant billing boundary", () => {
await expect(getTenantSubscriptionProductById({ id: "tenant_product_1", tenantId: "tenant_1" }, client)).resolves.toBe(item);
await expect(getTenantSubscriptionProductByBillingProviderSubscriptionId("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.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: { billingProviderSubscriptionId: "sub_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: { billingProviderSubscriptionId: "sub_1" } })
);
});
it("uses the billing product id when no custom entitlement override exists", () => {
@@ -540,7 +615,7 @@ describe("tenant billing boundary", () => {
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: null,
}),
})
).toBe("plan_standard");
});
@@ -549,7 +624,7 @@ describe("tenant billing boundary", () => {
getEffectiveTenantEntitlementPlanId({
subscriptionProductId: "plan_standard",
customEntitlementPlanId: "entitlements_enterprise_override",
}),
})
).toBe("entitlements_enterprise_override");
});
@@ -565,15 +640,15 @@ describe("tenant billing boundary", () => {
fromCheckoutSessionId: "cs_1",
prices: [{ subscriptionPriceId: "price_1" }, { subscriptionUsageBasedPriceId: "usage_price_1" }],
},
client,
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,
),
client
)
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.create).toHaveBeenCalledWith({
@@ -609,8 +684,8 @@ describe("tenant billing boundary", () => {
updateTenantSubscriptionProductCustomEntitlementPlan(
{ id: "tenant_product_1", tenantId: "tenant_1" },
{ customEntitlementPlanId: "entitlements_scale_override" },
client,
),
client
)
).resolves.toEqual({ tenantId: "tenant_1" });
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
@@ -632,26 +707,33 @@ describe("tenant billing boundary", () => {
vi.mocked(client.tenantSubscriptionProduct.update).mockRejectedValueOnce(error);
await expect(
updateTenantSubscriptionProductCustomEntitlementPlan({ id: "tenant_product_1", tenantId: "tenant_1" }, { customEntitlementPlanId: null }, client),
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);
vi.mocked(client.checkoutSessionStatus.findFirst).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return 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);
await expect(getCheckoutSessionStatus({ id: "cs_missing", tenantId: "tenant_1" }, client)).resolves.toBeNull();
await createCheckoutSessionStatus({ id: "cs_1", tenantId: "tenant_1", email: "user@example.com", fromUrl: "/subscribe/acme" }, client);
await updateCheckoutSessionStatus({ id: "cs_1", tenantId: "tenant_1" }, { pending: false, createdUserId: "user_1" }, client);
expect(client.checkoutSessionStatus.findFirst).toHaveBeenCalledWith({
where: { id: "cs_missing", tenantId: "tenant_1" },
});
expect(client.checkoutSessionStatus.create).toHaveBeenCalledWith({
data: expect.objectContaining({
id: "cs_1",
tenantId: "tenant_1",
pending: true,
email: "user@example.com",
fromUrl: "/subscribe/acme",
fromUserId: null,
fromTenantId: null,
provider: null,
providerPaymentId: null,
quantity: 1,
@@ -659,11 +741,132 @@ describe("tenant billing boundary", () => {
}),
});
expect(client.checkoutSessionStatus.update).toHaveBeenCalledWith({
where: { id: "cs_1" },
where: { id: "cs_1", tenantId: "tenant_1" },
data: expect.objectContaining({ pending: false, createdUserId: "user_1", createdTenantId: null }),
});
});
it("claims a checkout provider lease with an atomic tenant, status, pending, and stale-time compare-and-swap", async () => {
const staleBefore = new Date("2026-07-15T10:00:00.000Z");
const claimed = { id: "cs_1", tenantId: "tenant_1", pending: true, status: "provider_claimed_unique" };
const client = createTenantBillingClient([claimed]);
await expect(
claimCheckoutSessionStatus(
{
id: "cs_1",
tenantId: "tenant_1",
expectedStatus: "provider_claimed_stale",
claimedStatus: "provider_claimed_unique",
updatedBefore: staleBefore,
},
client
)
).resolves.toEqual(claimed);
expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({
where: {
id: "cs_1",
tenantId: "tenant_1",
pending: true,
status: "provider_claimed_stale",
updatedAt: { lte: staleBefore },
},
data: { status: "provider_claimed_unique" },
});
});
it("lets only one checkout taker win and never reads a row after a lost claim", async () => {
const client = createTenantBillingClient([]);
vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 });
await expect(
claimCheckoutSessionStatus(
{
id: "cs_1",
tenantId: "tenant_1",
expectedStatus: "provider_recovery_pending",
claimedStatus: "provider_claimed_loser",
},
client
)
).resolves.toBeNull();
expect(client.checkoutSessionStatus.findFirst).not.toHaveBeenCalled();
});
it("finalizes only the matching claim token so a late failure cannot overwrite a paid or open checkout", async () => {
const client = createTenantBillingClient([]);
vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 });
await expect(
transitionClaimedCheckoutSessionStatus(
{
id: "cs_1",
tenantId: "tenant_1",
claimedStatus: "provider_claimed_late",
data: { pending: true, status: "provider_recovery_pending", providerPaymentId: "tr_1" },
},
client
)
).resolves.toBeNull();
expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({
where: { id: "cs_1", tenantId: "tenant_1", pending: true, status: "provider_claimed_late" },
data: expect.objectContaining({ pending: true, status: "provider_recovery_pending", providerPaymentId: "tr_1" }),
});
expect(client.checkoutSessionStatus.findFirst).not.toHaveBeenCalled();
});
it("persists the exact provider invoice on the matching checkout ledger row and accepts an idempotent replay", async () => {
const correlated = {
id: "cs_1",
tenantId: "tenant_1",
providerPaymentId: "tr_1",
lagoSubscriptionId: "cs_1",
invoiceExternalId: "invoice_lago_1",
};
const client = createTenantBillingClient([correlated]);
await correlateCheckoutSessionProviderInvoice(
{
id: "cs_1",
tenantId: "tenant_1",
providerPaymentId: "tr_1",
lagoSubscriptionId: "cs_1",
sourceInvoiceExternalId: "cs_1",
providerInvoiceExternalId: "invoice_lago_1",
},
client
);
expect(client.checkoutSessionStatus.updateMany).toHaveBeenCalledWith({
where: {
id: "cs_1",
tenantId: "tenant_1",
providerPaymentId: "tr_1",
lagoSubscriptionId: "cs_1",
invoiceExternalId: "cs_1",
},
data: { invoiceExternalId: "invoice_lago_1" },
});
vi.mocked(client.checkoutSessionStatus.updateMany).mockResolvedValueOnce({ count: 0 });
vi.mocked(client.checkoutSessionStatus.findFirst).mockResolvedValueOnce(correlated as never);
await expect(
correlateCheckoutSessionProviderInvoice(
{
id: "cs_1",
tenantId: "tenant_1",
providerPaymentId: "tr_1",
lagoSubscriptionId: "cs_1",
sourceInvoiceExternalId: "cs_1",
providerInvoiceExternalId: "invoice_lago_1",
},
client
)
).resolves.toBeUndefined();
});
it("creates usage records and propagates write rejections", async () => {
const client = createTenantBillingClient([{ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }]);
const usageData = {