import { beforeEach, describe, expect, it, vi } from "vitest"; vi.mock("../../db.server", () => ({ db: {} })); vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() })); vi.mock("../../db/subscriptionProducts.db.server", () => ({ getAllSubscriptionFeatures: vi.fn() })); vi.mock("@hivegrid/db/subscriptions.server", () => ({ createTenantSubscriptionUsageRecord: vi.fn(), listTenantSubscriptionIds: vi.fn(), updateTenantSubscriptionProduct: vi.fn(), })); vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn(), getTenantSubscriptions: vi.fn() })); vi.mock("~/modules/emails/services/EmailService", () => ({ sendEmail: vi.fn() })); vi.mock("../../helpers/ApiKeyHelper", () => ({ apiKeyCreditableStatusCodes: [], apiKeyIgnoreEndpoints: [] })); vi.mock("../../url.server", () => ({ getBaseURL: vi.fn() })); vi.mock("./pricingService", () => ({ getAcquiredItemsFromCheckoutSession: vi.fn() })); vi.mock("../../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn(), clearCacheKeyPrefix: vi.fn() })); // Stable invalidate spy so tests can assert the cross-replica publish path. const subscriptionCacheInvalidateMock = vi.fn().mockResolvedValue(undefined); vi.mock("./subscriptionCache.server", () => ({ getSubscriptionCache: () => ({ invalidate: subscriptionCacheInvalidateMock, get: vi.fn(), set: vi.fn(), subscribe: vi.fn(), flushLocal: vi.fn(), deleteLocal: vi.fn(), }), })); vi.mock("~/utils/db/subscriptions/tenantSubscriptionProducts.db.server", () => ({ cancelTenantSubscriptionProduct: vi.fn(), getTenantSubscriptionProductById: vi.fn(), })); vi.mock("~/services/billing/product-acquisition.server", () => { class ProductAcquisitionError extends Error { constructor(readonly code: string) { super(code); } } return { ProductAcquisitionError, cancelRecurringProductAcquisition: vi.fn(), }; }); vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } })); vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn() })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() })); vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: {} })); vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() })); import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache } from "./subscriptionService"; import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server"; import { getTenant } from "~/utils/db/tenants.db.server"; import { getUser } from "~/utils/db/users.db.server"; import { clearCacheKey } from "../../cache.server"; import { listTenantSubscriptionIds } from "@hivegrid/db/subscriptions.server"; import { cancelRecurringProductAcquisition, ProductAcquisitionError } from "~/services/billing/product-acquisition.server"; function subscriptionProduct( overrides: { kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override"; acquisition?: { productKind: "recurring_add_on"; status: string; lagoSubscriptionId: string | null } | null; } = {} ): Awaited> { return { id: "tenant-sub-product-id", subscriptionProductId: "product-id", billingProviderSubscriptionId: null, subscriptionProduct: { id: "product-id", title: "Product", kind: overrides.kind ?? "recurring_add_on" }, acquisition: overrides.acquisition === undefined ? { productKind: "recurring_add_on", status: "active", lagoSubscriptionId: "lago_subscription_1" } : overrides.acquisition, } as Awaited>; } describe("cancelTenantSubscription", () => { beforeEach(() => { vi.mocked(getTenantSubscriptionProductById).mockReset(); vi.mocked(getUser).mockReset(); vi.mocked(getTenant).mockReset(); vi.mocked(cancelRecurringProductAcquisition).mockReset(); vi.mocked(cancelTenantSubscriptionProduct).mockReset(); vi.mocked(clearCacheKey).mockClear(); subscriptionCacheInvalidateMock.mockClear(); }); it.each(["base_plan", "one_time_setup"] as const)("never cancels a %s product", async (kind) => { vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct({ kind, acquisition: null })); await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({ code: "PRODUCT_KIND_INVALID", }); expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled(); expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled(); expect(getUser).not.toHaveBeenCalled(); }); it("fails closed when a recurring add-on has no acquisition", async () => { vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct({ acquisition: null })); await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({ code: "ACQUISITION_NOT_FOUND", }); expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled(); expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled(); }); it("fails closed when a recurring acquisition has no Lago subscription reference", async () => { vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce( subscriptionProduct({ acquisition: { productKind: "recurring_add_on", status: "active", lagoSubscriptionId: null } }) ); await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT", }); expect(cancelRecurringProductAcquisition).not.toHaveBeenCalled(); expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled(); }); it("delegates an acquisition-backed recurring add-on to the atomic provider cancellation path", async () => { vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct()); vi.mocked(getUser).mockResolvedValueOnce({ id: "user-id", email: "owner@example.test" } as Awaited>); vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited>); vi.mocked(cancelRecurringProductAcquisition).mockResolvedValueOnce({} as Awaited>); await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" }); expect(cancelRecurringProductAcquisition).toHaveBeenCalledWith({ tenantId: "tenant-id", actorUserId: "user-id", tenantSubscriptionProductId: "tenant-sub-product-id", eventData: { user: { id: "user-id", email: "owner@example.test" }, tenant: { id: "tenant-id", name: "Tenant" }, subscription: { product: { id: "product-id", title: "Product" } }, }, }); expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled(); expect(clearCacheKey).toHaveBeenCalledWith("tenantSubscription:tenant-id"); }); it("propagates an acquisition lookup failure without locally revoking the entitlement", async () => { vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce(subscriptionProduct()); vi.mocked(getUser).mockResolvedValueOnce({ id: "user-id", email: "owner@example.test" } as Awaited>); vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited>); vi.mocked(cancelRecurringProductAcquisition).mockRejectedValueOnce(new ProductAcquisitionError("ACQUISITION_NOT_FOUND")); await expect(cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" })).rejects.toMatchObject({ code: "ACQUISITION_NOT_FOUND", }); expect(cancelTenantSubscriptionProduct).not.toHaveBeenCalled(); expect(clearCacheKey).not.toHaveBeenCalledWith("tenantSubscription:tenant-id"); }); }); describe("subscription cache invalidation", () => { it("clearTenantSubscriptionCache only invalidates the affected tenant key", () => { const clearCacheKeyMock = vi.mocked(clearCacheKey); clearCacheKeyMock.mockClear(); clearTenantSubscriptionCache("tenant-a"); expect(clearCacheKeyMock).toHaveBeenCalledTimes(1); expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-a"); }); it("clearTenantSubscriptionCache does not enumerate other tenants (no global thrash)", () => { const clearCacheKeyMock = vi.mocked(clearCacheKey); const listMock = vi.mocked(listTenantSubscriptionIds); clearCacheKeyMock.mockClear(); listMock.mockClear(); clearTenantSubscriptionCache("tenant-x"); expect(listMock).not.toHaveBeenCalled(); }); it("clearTenantSubscriptionCache publishes a cross-replica invalidation for the tenant", () => { subscriptionCacheInvalidateMock.mockClear(); clearTenantSubscriptionCache("tenant-b"); // Peer web replicas must drop their L1 too — not just this process. expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1); expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith("tenant-b"); }); it("clearAllSubscriptionsCache broadcasts a wildcard cross-replica invalidation", async () => { subscriptionCacheInvalidateMock.mockClear(); vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce([] as Awaited>); await clearAllSubscriptionsCache(); // No key argument == wildcard flush across every replica's L1. expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1); expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith(); }); it("clearAllSubscriptionsCache invalidates every cached tenant subscription", async () => { const clearCacheKeyMock = vi.mocked(clearCacheKey); const listMock = vi.mocked(listTenantSubscriptionIds); clearCacheKeyMock.mockClear(); listMock.mockReset(); listMock.mockResolvedValueOnce([ { id: "sub-1", tenantId: "tenant-1" }, { id: "sub-2", tenantId: "tenant-2" }, { id: "sub-3", tenantId: "tenant-3" }, ] as Awaited>); await clearAllSubscriptionsCache(); expect(clearCacheKeyMock).toHaveBeenCalledTimes(3); expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-1"); expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-2"); expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-3"); }); });