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

@@ -0,0 +1,461 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
db: {
onboarding: { findUnique: vi.fn() },
onboardingSession: { findFirst: vi.fn(), findUnique: vi.fn(), update: vi.fn() },
onboardingSessionStep: { findMany: vi.fn(), updateMany: vi.fn() },
user: { findUnique: vi.fn() },
tenantUser: { count: vi.fn() },
tenantUserInvitation: { count: vi.fn() },
kontakt: { count: vi.fn(), create: vi.fn() },
projekt: { count: vi.fn(), create: vi.fn() },
task: { create: vi.fn(), deleteMany: vi.fn() },
tenantSubscription: { findUnique: vi.fn() },
onboardingDemoProvisioning: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
$transaction: vi.fn(),
},
ensureDefaultSalesPipeline: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
vi.mock("~/utils/integrations/projects/projectService.server", () => ({ ensureDefaultSalesPipeline: mocks.ensureDefaultSalesPipeline }));
import { getFirstStepsChecklist, updateFirstStepsChecklist } from "./akP20OnboardingService";
import { SHK_FIRST_STEPS, SHK_FIRST_STEPS_CHECKLIST_CODE, SHK_FIRST_STEPS_CHECKLIST_ID } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
function canonicalCatalog() {
return {
id: SHK_FIRST_STEPS_CHECKLIST_ID,
title: SHK_FIRST_STEPS_CHECKLIST_CODE,
type: "page",
realtime: false,
active: true,
canBeDismissed: true,
height: null,
steps: SHK_FIRST_STEPS.map((step) => ({ ...step })),
};
}
function sessionStep(index: number, id = `session_step_${index + 1}`) {
return {
id,
completedAt: null,
step: { ...SHK_FIRST_STEPS[index]! },
};
}
function legacyCatalogSteps() {
return SHK_FIRST_STEPS.map((step, index) => ({ ...step, id: `legacy_step_${index + 1}` }));
}
function legacySession(status = "active") {
return {
id: "legacy_session_1",
status,
onboarding: { steps: legacyCatalogSteps() },
};
}
const mutationSpies = [mocks.db.onboardingSession.update, mocks.db.onboardingSessionStep.updateMany, mocks.ensureDefaultSalesPipeline];
function expectNoChecklistWrites() {
for (const mutation of mutationSpies) {
expect(mutation).not.toHaveBeenCalled();
}
}
describe("getFirstStepsChecklist read path", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.db.onboarding.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(null);
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([]);
mocks.db.user.findUnique.mockResolvedValue(null);
mocks.db.tenantUser.count.mockResolvedValue(1);
mocks.db.tenantUserInvitation.count.mockResolvedValue(0);
mocks.db.kontakt.count.mockResolvedValue(0);
mocks.db.projekt.count.mockResolvedValue(0);
mocks.db.tenantSubscription.findUnique.mockResolvedValue(null);
});
it("returns an empty checklist without provisioning when no definition exists", async () => {
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(checklist).toEqual({
id: "",
status: "active",
dismissed: false,
completedCount: 0,
totalCount: 0,
percentComplete: 0,
items: [],
});
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findFirst).toHaveBeenCalledWith({
where: {
userId: "user_1",
tenantId: "tenant_1",
onboardingId: { not: SHK_FIRST_STEPS_CHECKLIST_ID },
onboarding: { title: SHK_FIRST_STEPS_CHECKLIST_CODE },
},
select: {
id: true,
status: true,
onboarding: {
select: {
steps: { select: { id: true, order: true, block: true } },
},
},
},
orderBy: { createdAt: "asc" },
});
expectNoChecklistWrites();
});
it("derives auto-completion in memory without persisting session or step updates", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1", status: "active" });
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([sessionStep(0), sessionStep(1)]);
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
mocks.db.kontakt.count.mockResolvedValue(1);
const checklist = await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(checklist).toMatchObject({ id: "session_1", status: "active", completedCount: 2, totalCount: 3, percentComplete: 67 });
expect(checklist.items).toEqual([
expect.objectContaining({ id: "session_step_1", block: "profile", completed: true }),
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", completed: false, canComplete: false }),
expect.objectContaining({ id: "session_step_2", block: "contacts", completed: true }),
]);
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
where: {
onboardingSessionId: "session_1",
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
expect(mocks.db.tenantUserInvitation.count).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
pending: true,
status: "pending",
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: expect.any(Date) } }],
},
});
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("keeps an existing legacy checklist session readable without migrating it", async () => {
const legacySteps = legacyCatalogSteps();
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSessionStep.findMany.mockResolvedValue([
{ id: "legacy_session_step_1", completedAt: null, step: legacySteps[0] },
{ id: "legacy_session_step_2", completedAt: null, step: legacySteps[1] },
]);
mocks.db.user.findUnique.mockResolvedValue({ firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" });
const checklist = await getFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1" });
expect(checklist).toMatchObject({ id: "legacy_session_1", completedCount: 1, totalCount: 3, percentComplete: 33 });
expect(checklist.items).toEqual([
expect.objectContaining({ id: "legacy_session_step_1", block: "profile", titleKey: "onboarding.firstSteps.profile" }),
expect.objectContaining({ id: "shk-first-steps-team-detection-v1", block: "team", titleKey: "onboarding.firstSteps.team" }),
expect.objectContaining({ id: "legacy_session_step_2", block: "contacts", titleKey: "onboarding.firstSteps.contacts" }),
]);
expect(mocks.db.onboardingSessionStep.findMany).toHaveBeenCalledWith({
where: {
onboardingSessionId: "legacy_session_1",
stepId: { in: legacySteps.map((step) => step.id) },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
expectNoChecklistWrites();
});
it("binds every checklist read to the requested tenant and user", async () => {
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
const observeContext = () => contexts.push(getRlsExecutionContext());
mocks.db.onboarding.findUnique.mockImplementation(async () => {
observeContext();
return canonicalCatalog();
});
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
observeContext();
return { id: "session_1", status: "active" };
});
mocks.db.onboardingSessionStep.findMany.mockImplementation(async () => {
observeContext();
return [sessionStep(0)];
});
mocks.db.user.findUnique.mockImplementation(async () => {
observeContext();
return { firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" };
});
mocks.db.tenantUser.count.mockImplementation(async () => {
observeContext();
return 1;
});
mocks.db.tenantUserInvitation.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.kontakt.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.projekt.count.mockImplementation(async () => {
observeContext();
return 0;
});
mocks.db.tenantSubscription.findUnique.mockImplementation(async () => {
observeContext();
return null;
});
await getFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1" });
expect(contexts).toHaveLength(9);
for (const context of contexts) {
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
}
});
it("updates only the existing session and never re-provisions tenant defaults", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "dismissed" });
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
expect(mocks.db.onboarding.findUnique).toHaveBeenCalledWith({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "session_1" },
data: { status: "dismissed", dismissedAt: expect.any(Date) },
});
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
});
it("reactivates a dismissed session on the show action", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSession.update.mockResolvedValue({ id: "session_1", status: "active" });
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "show" });
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "session_1" },
data: { status: "active", dismissedAt: null },
});
});
it("updates an existing legacy session without replacing or provisioning it", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSession.update.mockResolvedValue({ id: "legacy_session_1", status: "dismissed" });
await updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" });
expect(mocks.db.onboardingSession.update).toHaveBeenCalledWith({
where: { id: "legacy_session_1" },
data: { status: "dismissed", dismissedAt: expect.any(Date) },
});
expect(mocks.ensureDefaultSalesPipeline).not.toHaveBeenCalled();
});
it("completes only a semantic checklist step from an existing legacy session", async () => {
const legacySteps = legacyCatalogSteps();
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue(legacySession());
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
await expect(
updateFirstStepsChecklist({
tenantId: "legacy_tenant",
userId: "user_1",
action: "complete",
sessionStepId: "legacy_session_step_1",
})
).resolves.toEqual({ count: 1 });
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
where: {
id: "legacy_session_step_1",
onboardingSessionId: "legacy_session_1",
stepId: { in: legacySteps.map((step) => step.id) },
},
data: { completedAt: expect.any(Date) },
});
});
it("does not use a malformed legacy catalog as a compatibility fallback", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(null);
mocks.db.onboardingSession.findFirst.mockResolvedValue({
...legacySession(),
onboarding: { steps: legacyCatalogSteps().slice(0, 3) },
});
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expectNoChecklistWrites();
});
it("isolates checklist reads and writes from a previously bound tenant transaction", async () => {
const oldTransaction = {};
const contexts: Array<ReturnType<typeof getRlsExecutionContext>> = [];
const observeContext = () => contexts.push(getRlsExecutionContext());
mocks.db.onboarding.findUnique.mockImplementation(async () => {
observeContext();
return canonicalCatalog();
});
mocks.db.onboardingSession.findUnique.mockImplementation(async () => {
observeContext();
return { id: "session_1" };
});
mocks.db.onboardingSession.update.mockImplementation(async () => {
observeContext();
return { id: "session_1", status: "dismissed" };
});
await runWithRlsContext({ tenantId: "tenant_old", userId: "user_1" }, () =>
runWithRlsTransaction(oldTransaction, async () => {
await updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" });
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_old", userId: "user_1", transaction: oldTransaction });
})
);
expect(contexts).toHaveLength(3);
for (const context of contexts) {
expect(context).toMatchObject({ tenantId: "tenant_1", userId: "user_1" });
expect(context?.transaction).toBeUndefined();
}
});
it("fails closed before any query when a caller tries to replace the authenticated RLS user", async () => {
await runWithRlsContext({ tenantId: "tenant_1", userId: "authenticated_user" }, async () => {
await expect(getFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user" })).rejects.toMatchObject({
code: "foundation.not_found",
});
await expect(
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "other_user", action: "hide" })
).rejects.toMatchObject({ code: "foundation.not_found" });
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1", userId: "authenticated_user" });
});
expect(mocks.db.onboarding.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expect(mocks.db.onboardingSession.findFirst).not.toHaveBeenCalled();
expect(mocks.db.onboardingSessionStep.findMany).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("fails closed instead of creating defaults for a tenant without a bootstrap session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue(null);
await expect(updateFirstStepsChecklist({ tenantId: "legacy_tenant", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expectNoChecklistWrites();
});
it("fails closed for a catalog with generated or duplicated step identities", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue({
...canonicalCatalog(),
steps: SHK_FIRST_STEPS.map((step, index) => (index === 0 ? { ...step, id: "generated-step" } : { ...step })),
});
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it.each([
["type", "modal"],
["realtime", true],
["canBeDismissed", false],
["height", "md"],
] as const)("fails closed when the canonical catalog %s drifts", async (field, value) => {
mocks.db.onboarding.findUnique.mockResolvedValue({
...canonicalCatalog(),
[field]: value,
});
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "hide" })).rejects.toMatchObject({
code: "foundation.not_found",
});
expect(mocks.db.onboardingSession.findUnique).not.toHaveBeenCalled();
expectNoChecklistWrites();
});
it("completes only a canonical step belonging to the selected SHK session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 1 });
await expect(updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "session_step_1" })).resolves.toEqual({
count: 1,
});
expect(mocks.db.onboardingSessionStep.updateMany).toHaveBeenCalledWith({
where: {
id: "session_step_1",
onboardingSessionId: "session_1",
stepId: { in: SHK_FIRST_STEPS.map((step) => step.id) },
},
data: { completedAt: expect.any(Date) },
});
});
it("returns not found when a submitted session step is outside the canonical SHK session", async () => {
mocks.db.onboarding.findUnique.mockResolvedValue(canonicalCatalog());
mocks.db.onboardingSession.findUnique.mockResolvedValue({ id: "session_1" });
mocks.db.onboardingSessionStep.updateMany.mockResolvedValue({ count: 0 });
await expect(
updateFirstStepsChecklist({ tenantId: "tenant_1", userId: "user_1", action: "complete", sessionStepId: "foreign_step" })
).rejects.toMatchObject({ code: "foundation.not_found" });
});
});
@@ -1,129 +1,95 @@
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import {
hasExactShkFirstSteps,
SHK_FIRST_STEPS,
SHK_FIRST_STEPS_CHECKLIST_CODE,
SHK_FIRST_STEPS_CHECKLIST_ID,
} from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
import { db } from "~/utils/db.server";
import { seedShkRolesForTenant } from "../shkRoles.server";
import { seedShkFormTemplates, type FormTemplateTranslationFn } from "~/modules/forms/services/shkFormTemplates.server";
import { seedShkCustomFieldTemplate } from "~/utils/integrations/crm/customFieldService.server";
import { ensureDefaultAcceptanceFormTemplate, ensureDefaultProjectTemplate } from "~/utils/integrations/projects/auftragService.server";
import { ensureDefaultSalesPipeline } from "~/utils/integrations/projects/projectService.server";
const SHK_CHECKLIST_CODE = "shk-first-steps";
const SHK_DEMO_TEMPLATE_CODE = "shk-demo-v1";
const checklistSteps = [
{ order: 10, block: "profile", titleKey: "onboarding.firstSteps.profile", href: "settings/profile" },
{ order: 20, block: "contacts", titleKey: "onboarding.firstSteps.contacts", href: "contacts" },
{ order: 30, block: "projects", titleKey: "onboarding.firstSteps.projects", href: "projects" },
{ order: 40, block: "billing", titleKey: "onboarding.firstSteps.billing", href: "settings/subscription" },
{ ...SHK_FIRST_STEPS[0], titleKey: "onboarding.firstSteps.profile", href: "settings/profile" },
{ ...SHK_FIRST_STEPS[1], titleKey: "onboarding.firstSteps.contacts", href: "contacts" },
{ ...SHK_FIRST_STEPS[2], titleKey: "onboarding.firstSteps.projects", href: "projects" },
{ ...SHK_FIRST_STEPS[3], titleKey: "onboarding.firstSteps.billing", href: "settings/billing" },
] as const;
const TEAM_CHECKLIST_ITEM = {
id: "shk-first-steps-team-detection-v1",
block: "team",
titleKey: "onboarding.firstSteps.team",
href: "settings/team/members/new",
canComplete: false,
} as const;
type DemoEntityMap = Record<string, string[]>;
type FirstStepsBlock = (typeof checklistSteps)[number]["block"];
async function getOrCreateChecklistOnboarding() {
const existing = await db.onboarding.findFirst({ where: { title: SHK_CHECKLIST_CODE } });
if (existing) {
return existing;
}
return await db.onboarding.create({
data: {
title: SHK_CHECKLIST_CODE,
type: "page",
active: true,
canBeDismissed: true,
steps: {
create: checklistSteps.map((step) => ({
order: step.order,
block: step.block,
})),
},
},
});
}
export async function provisionShkTenantDefaults(input: { tenantId: string; userId: string; t?: FormTemplateTranslationFn }) {
await seedShkRolesForTenant(input.tenantId);
await Promise.all([
ensureDefaultSalesPipeline({ tenantId: input.tenantId, userId: input.userId }),
seedShkCustomFieldTemplate({ tenantId: input.tenantId }),
ensureDefaultAcceptanceFormTemplate({ tenantId: input.tenantId, userId: input.userId }),
ensureDefaultProjectTemplate({ tenantId: input.tenantId }),
input.t ? seedShkFormTemplates({ tenantId: input.tenantId, userId: input.userId, t: input.t }) : Promise.resolve({ upserted: 0 }),
]);
const onboarding = await getOrCreateChecklistOnboarding();
const session = await db.onboardingSession.upsert({
where: {
onboardingId_userId_tenantId: {
onboardingId: onboarding.id,
userId: input.userId,
tenantId: input.tenantId,
},
},
create: {
onboardingId: onboarding.id,
userId: input.userId,
tenantId: input.tenantId,
status: "active",
startedAt: new Date(),
},
update: {},
});
const steps = await db.onboardingStep.findMany({ where: { onboardingId: onboarding.id } });
const existingSessionSteps = await db.onboardingSessionStep.findMany({
where: { onboardingSessionId: session.id },
select: { stepId: true },
});
const existingStepIds = new Set(existingSessionSteps.map((step) => step.stepId));
await db.onboardingSessionStep.createMany({
data: steps
.filter((step) => !existingStepIds.has(step.id))
.map((step) => ({
onboardingSessionId: session.id,
stepId: step.id,
})),
skipDuplicates: true,
});
return session;
}
type FirstStepsBlock = (typeof checklistSteps)[number]["block"] | typeof TEAM_CHECKLIST_ITEM.block;
type FirstStepsCatalogStep = { id: string; order: number; block: string };
type ResolvedFirstStepsSession = {
id: string;
status: string;
stepIds: string[];
};
export async function getFirstStepsChecklist(input: { tenantId: string; userId: string }) {
const session = await provisionShkTenantDefaults(input);
return await withChecklistRlsContext(input, () => getFirstStepsChecklistInContext(input));
}
async function getFirstStepsChecklistInContext(input: { tenantId: string; userId: string }) {
const session = await findFirstStepsSession(input);
if (!session) {
return emptyFirstStepsChecklist();
}
const rows = await db.onboardingSessionStep.findMany({
where: { onboardingSessionId: session.id },
where: {
onboardingSessionId: session.id,
stepId: { in: session.stepIds },
},
include: { step: true },
orderBy: { step: { order: "asc" } },
});
const autoCompletedBlocks = await detectFirstStepsCompletion(input);
const now = new Date();
const autoCompletedRows = rows.filter((row) => !row.completedAt && autoCompletedBlocks.has(row.step.block as FirstStepsBlock));
if (autoCompletedRows.length > 0) {
await db.onboardingSessionStep.updateMany({
where: { id: { in: autoCompletedRows.map((row) => row.id) }, onboardingSessionId: session.id },
data: { completedAt: now },
});
if (rows.length === 0) {
return emptyFirstStepsChecklist();
}
const autoCompletedBlocks = await detectFirstStepsCompletion(input);
const dismissed = session.status === "dismissed";
const items = rows.map((row) => {
const config = checklistSteps.find((step) => step.block === row.step.block);
const items: Array<{
id: string;
block: string;
titleKey: string;
href: string;
completed: boolean;
hidden: boolean;
canComplete?: boolean;
}> = rows.flatMap((row) => {
const config = checklistSteps.find((step) => step.order === row.step.order && step.block === row.step.block);
if (!config) return [];
const completed = Boolean(row.completedAt) || autoCompletedBlocks.has(row.step.block as FirstStepsBlock);
return {
id: row.id,
block: row.step.block,
titleKey: config?.titleKey ?? "onboarding.firstSteps.item",
href: config?.href ?? "dashboard",
completed,
hidden: dismissed,
};
return [
{
id: row.id,
block: row.step.block,
titleKey: config.titleKey,
href: config.href,
completed,
hidden: dismissed,
},
];
});
if (items.length !== rows.length) return emptyFirstStepsChecklist();
items.splice(1, 0, {
...TEAM_CHECKLIST_ITEM,
completed: autoCompletedBlocks.has(TEAM_CHECKLIST_ITEM.block),
hidden: dismissed,
});
const completedCount = items.filter((item) => item.completed).length;
if (!dismissed && items.length > 0 && completedCount === items.length && session.status !== "completed") {
await db.onboardingSession.update({
where: { id: session.id },
data: { status: "completed", completedAt: now },
});
}
return {
id: session.id,
@@ -136,15 +102,39 @@ export async function getFirstStepsChecklist(input: { tenantId: string; userId:
};
}
function emptyFirstStepsChecklist() {
return {
id: "",
status: "active",
dismissed: false,
completedCount: 0,
totalCount: 0,
percentComplete: 0,
items: [],
};
}
async function detectFirstStepsCompletion(input: { tenantId: string; userId: string }): Promise<Set<FirstStepsBlock>> {
const [user, contactCount, projectCount, subscription] = await Promise.all([
const now = new Date();
const [user, memberCount, pendingInvitationCount, contactCount, projectCount, subscription] = await Promise.all([
db.user.findUnique({ where: { id: input.userId }, select: { firstName: true, lastName: true, email: true } }),
db.tenantUser.count({ where: { tenantId: input.tenantId } }),
db.tenantUserInvitation.count({
where: {
tenantId: input.tenantId,
pending: true,
status: "pending",
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
},
}),
db.kontakt.count({ where: { tenantId: input.tenantId, isDemoData: false } }),
db.projekt.count({ where: { tenantId: input.tenantId, isDemoData: false } }),
db.tenantSubscription.findUnique({ where: { tenantId: input.tenantId }, select: { status: true } }),
]);
const completed = new Set<FirstStepsBlock>();
if (user?.firstName && user.lastName && user.email) completed.add("profile");
if (memberCount > 1 || pendingInvitationCount > 0) completed.add("team");
if (contactCount > 0) completed.add("contacts");
if (projectCount > 0) completed.add("projects");
if (subscription?.status === "trial" || subscription?.status === "active") completed.add("billing");
@@ -155,28 +145,148 @@ export async function updateFirstStepsChecklist(input: {
tenantId: string;
userId: string;
sessionStepId?: string | null;
action: "complete" | "hide";
action: "complete" | "hide" | "show";
}) {
const session = await provisionShkTenantDefaults(input);
return await withChecklistRlsContext(input, () => updateFirstStepsChecklistInContext(input));
}
async function updateFirstStepsChecklistInContext(input: {
tenantId: string;
userId: string;
sessionStepId?: string | null;
action: "complete" | "hide" | "show";
}) {
const session = await findFirstStepsSession(input);
if (!session) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" });
}
if (input.action === "hide") {
return await db.onboardingSession.update({
where: { id: session.id },
data: { status: "dismissed", dismissedAt: new Date() },
});
}
if (!input.sessionStepId) {
throw new Error("Missing checklist step id");
if (input.action === "show") {
return await db.onboardingSession.update({
where: { id: session.id },
data: { status: "active", dismissedAt: null },
});
}
return await db.onboardingSessionStep.updateMany({
if (!input.sessionStepId) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" });
}
const result = await db.onboardingSessionStep.updateMany({
where: {
id: input.sessionStepId,
onboardingSession: {
tenantId: input.tenantId,
userId: input.userId,
},
onboardingSessionId: session.id,
stepId: { in: session.stepIds },
},
data: { completedAt: new Date() },
});
if (result.count !== 1) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-step" });
}
return result;
}
async function findFirstStepsSession(input: { tenantId: string; userId: string }): Promise<ResolvedFirstStepsSession | null> {
const canonicalCatalog = await findCanonicalFirstStepsCatalog();
if (canonicalCatalog) {
const canonicalSession = await db.onboardingSession.findUnique({
where: {
onboardingId_userId_tenantId: {
onboardingId: canonicalCatalog.id,
userId: input.userId,
tenantId: input.tenantId,
},
},
});
if (canonicalSession) {
return {
id: canonicalSession.id,
status: canonicalSession.status,
stepIds: SHK_FIRST_STEPS.map((step) => step.id),
};
}
}
const legacySession = await db.onboardingSession.findFirst({
where: {
userId: input.userId,
tenantId: input.tenantId,
onboardingId: { not: SHK_FIRST_STEPS_CHECKLIST_ID },
onboarding: { title: SHK_FIRST_STEPS_CHECKLIST_CODE },
},
select: {
id: true,
status: true,
onboarding: {
select: {
steps: { select: { id: true, order: true, block: true } },
},
},
},
orderBy: { createdAt: "asc" },
});
if (!legacySession || !hasExactLegacyFirstSteps(legacySession.onboarding.steps)) {
return null;
}
return {
id: legacySession.id,
status: legacySession.status,
stepIds: legacySession.onboarding.steps.map((step) => step.id),
};
}
function hasExactLegacyFirstSteps(steps: ReadonlyArray<FirstStepsCatalogStep>): boolean {
return (
steps.length === checklistSteps.length &&
checklistSteps.every((expected) => steps.some((actual) => actual.order === expected.order && actual.block === expected.block))
);
}
async function findCanonicalFirstStepsCatalog() {
const onboarding = await db.onboarding.findUnique({
where: { id: SHK_FIRST_STEPS_CHECKLIST_ID },
select: {
id: true,
title: true,
type: true,
realtime: true,
active: true,
canBeDismissed: true,
height: true,
steps: { select: { id: true, order: true, block: true } },
},
});
if (
!onboarding ||
onboarding.title !== SHK_FIRST_STEPS_CHECKLIST_CODE ||
onboarding.type !== "page" ||
onboarding.realtime !== false ||
!onboarding.active ||
onboarding.canBeDismissed !== true ||
onboarding.height !== null ||
!hasExactShkFirstSteps(onboarding.steps)
) {
return null;
}
return onboarding;
}
function withChecklistRlsContext<T>(input: { tenantId: string; userId: string }, operation: () => T): T {
const current = getRlsExecutionContext();
if (current?.userId && current.userId !== input.userId) {
throw new CatalogError(foundationErrors.notFound, { resource: "shk-first-steps-session" });
}
const bindTarget = () => runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, operation);
if (current?.userId === input.userId && (current.transaction || (current.tenantId && current.tenantId !== input.tenantId))) {
return runWithIsolatedUserRlsContext(input.userId, bindTarget);
}
return bindTarget();
}
export async function getDemoDataStatus(tenantId: string) {
@@ -1,211 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
applyBillingDunningCycle,
billingStatusFromStripeSubscription,
createBillingDunningNotification,
evaluateBillingDunning,
processStripeBillingEvent,
} from "./billingDunningService";
vi.mock("~/utils/db.server", () => ({
db: {},
}));
const clearTenantSubscriptionCache = vi.fn();
const createNotificationDelivery = vi.fn();
vi.mock("./subscriptionService", () => ({
clearTenantSubscriptionCache: (...args: unknown[]) => clearTenantSubscriptionCache(...args),
}));
vi.mock("@hivegrid/db/notifications.server", () => ({
createNotificationDelivery: (...args: unknown[]) => createNotificationDelivery(...args),
}));
function createClient() {
return {
tenantSubscription: {
findUnique: vi.fn(),
findMany: vi.fn(),
update: vi.fn(),
},
tenantSubscriptionProduct: {
findFirst: vi.fn(),
update: vi.fn(),
},
stripeWebhookLog: {
findUnique: vi.fn(),
upsert: vi.fn(),
update: vi.fn(),
},
};
}
function stripeEvent(type: string, object: Record<string, unknown>) {
return {
id: `evt_${type.replaceAll(".", "_")}`,
type,
data: { object },
} as never;
}
describe("billingDunningService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("evaluates the day 1/3/7 dunning schedule before freezing", () => {
const now = new Date("2026-07-10T00:00:00.000Z");
expect(evaluateBillingDunning({ status: "active", pastDueSince: now, dunningAttemptCount: 0 }, now)).toEqual({ kind: "noop" });
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-09T00:00:00.000Z", dunningAttemptCount: 0 }, now)).toEqual({
kind: "send_dunning",
attempt: 1,
thresholdDays: 1,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-07T00:00:00.000Z", dunningAttemptCount: 1 }, now)).toEqual({
kind: "send_dunning",
attempt: 2,
thresholdDays: 3,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 2 }, now)).toEqual({
kind: "send_dunning",
attempt: 3,
thresholdDays: 7,
});
expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 3 }, now)).toEqual({
kind: "freeze",
thresholdDays: 7,
});
});
it("applies due dunning notices and freezes exhausted subscriptions", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
const sendDunningNotice = vi.fn();
client.tenantSubscription.findMany.mockResolvedValue([
{ tenantId: "tenant_notice", status: "past_due", pastDueSince: new Date("2026-07-09T00:00:00.000Z"), dunningAttemptCount: 0 },
{ tenantId: "tenant_freeze", status: "past_due", pastDueSince: new Date("2026-07-03T00:00:00.000Z"), dunningAttemptCount: 3 },
]);
const result = await applyBillingDunningCycle({ client, now, sendDunningNotice });
expect(result).toHaveLength(2);
expect(sendDunningNotice).toHaveBeenCalledWith({ tenantId: "tenant_notice", attempt: 1, thresholdDays: 1 });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_notice" },
data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now },
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_freeze" },
data: { status: "frozen", frozenAt: now },
});
expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_notice");
expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_freeze");
});
it("maps Billing provider subscription statuses to tenant billing statuses", () => {
expect(billingStatusFromStripeSubscription("trialing")).toBe("trial");
expect(billingStatusFromStripeSubscription("active")).toBe("active");
expect(billingStatusFromStripeSubscription("past_due")).toBe("past_due");
expect(billingStatusFromStripeSubscription("unpaid")).toBe("past_due");
expect(billingStatusFromStripeSubscription("canceled")).toBe("cancelled");
});
it("creates dunning email notifications through the notification delivery boundary", async () => {
await createBillingDunningNotification({ tenantId: "tenant_1", attempt: 2, thresholdDays: 3 });
expect(createNotificationDelivery).toHaveBeenCalledWith({
tenantId: "tenant_1",
channel: "EMAIL",
category: "billing",
messageKey: "billing.notify.dunning.attempt2",
sourceKey: "billing-dunning:tenant_1:attempt:2",
payloadMetadata: {
attempt: 2,
thresholdDays: 3,
},
});
});
it("processes Stripe invoice failures idempotently", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } });
client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince: null });
const result = await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now });
expect(result).toEqual({ replayed: false, relatedTenantId: "tenant_1" });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { status: "past_due", pastDueSince: now, frozenAt: null },
});
expect(client.stripeWebhookLog.update).toHaveBeenCalledWith({
where: { stripeEventId: "evt_invoice_payment_failed" },
data: { processedAt: now, relatedTenantId: "tenant_1", error: null },
});
client.stripeWebhookLog.findUnique.mockResolvedValueOnce({ processedAt: now, relatedTenantId: "tenant_1" });
await expect(processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now })).resolves.toEqual({
replayed: true,
relatedTenantId: "tenant_1",
});
});
it("keeps the original past-due timestamp on repeated Stripe failures", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
const pastDueSince = new Date("2026-07-08T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } });
client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince });
await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now });
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: { status: "past_due", pastDueSince, frozenAt: null },
});
});
it("syncs Billing provider subscription period fields and clears dunning state when active", async () => {
const client = createClient();
const now = new Date("2026-07-10T00:00:00.000Z");
client.stripeWebhookLog.findUnique.mockResolvedValue(null);
client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } });
await processStripeBillingEvent(
stripeEvent("customer.subscription.updated", {
id: "sub_1",
status: "active",
current_period_start: 1783296000,
current_period_end: 1785974400,
}),
{ client, now }
);
expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({
where: { id: "tenant_product_1" },
data: {
currentPeriodStart: new Date(1783296000 * 1000),
currentPeriodEnd: new Date(1785974400 * 1000),
endsAt: null,
cancelledAt: null,
},
});
expect(client.tenantSubscription.update).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
data: {
status: "active",
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
dunningAttemptCount: 0,
lastDunningSentAt: null,
},
});
});
});
@@ -1,247 +0,0 @@
import type Stripe from "stripe";
import { createNotificationDelivery } from "@hivegrid/db/notifications.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
export const BILLING_DUNNING_DAY_MARKS = [1, 3, 7] as const;
const DAY_MS = 24 * 60 * 60 * 1000;
const UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE = "billing.stripeWebhook.unknownError";
export type BillingDunningDecision =
| { kind: "noop" }
| { kind: "send_dunning"; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }
| { kind: "freeze"; thresholdDays: 7 };
export type BillingDunningSubscription = {
status: string | null;
pastDueSince: Date | string | null;
dunningAttemptCount: number | null;
};
type BillingDunningDeps = {
now?: Date;
sendDunningNotice?: (input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }) => Promise<void>;
client?: Pick<typeof db, "tenantSubscription" | "tenantSubscriptionProduct" | "stripeWebhookLog">;
};
type StripeSubscriptionLike = {
id: string;
status?: string | null;
current_period_start?: number | null;
current_period_end?: number | null;
cancel_at?: number | null;
canceled_at?: number | null;
};
function asDate(value: Date | string | null | undefined): Date | null {
if (!value) return null;
const date = value instanceof Date ? value : new Date(value);
return Number.isNaN(date.getTime()) ? null : date;
}
function fromUnix(value: number | null | undefined): Date | null {
return typeof value === "number" && Number.isFinite(value) ? new Date(value * 1000) : null;
}
function daysSince(from: Date, now: Date): number {
return Math.floor((now.getTime() - from.getTime()) / DAY_MS);
}
export function evaluateBillingDunning(input: BillingDunningSubscription, now: Date = new Date()): BillingDunningDecision {
if (input.status !== "past_due") return { kind: "noop" };
const pastDueSince = asDate(input.pastDueSince);
if (!pastDueSince) return { kind: "noop" };
const elapsedDays = daysSince(pastDueSince, now);
const attempts = Math.max(0, input.dunningAttemptCount ?? 0);
if (attempts >= BILLING_DUNNING_DAY_MARKS.length) {
return elapsedDays >= 7 ? { kind: "freeze", thresholdDays: 7 } : { kind: "noop" };
}
const thresholdDays = BILLING_DUNNING_DAY_MARKS[attempts];
if (elapsedDays < thresholdDays) return { kind: "noop" };
return { kind: "send_dunning", attempt: (attempts + 1) as 1 | 2 | 3, thresholdDays };
}
export function billingStatusFromStripeSubscription(status: string | null | undefined): "trial" | "active" | "past_due" | "cancelled" {
if (status === "trialing") return "trial";
if (status === "active") return "active";
if (status === "canceled") return "cancelled";
if (status === "past_due" || status === "unpaid" || status === "incomplete" || status === "incomplete_expired") return "past_due";
return "active";
}
export async function createBillingDunningNotification(input: { tenantId: string; attempt: 1 | 2 | 3; thresholdDays: 1 | 3 | 7 }): Promise<void> {
await createNotificationDelivery({
tenantId: input.tenantId,
channel: "EMAIL",
category: "billing",
messageKey: `billing.notify.dunning.attempt${input.attempt}`,
sourceKey: `billing-dunning:${input.tenantId}:attempt:${input.attempt}`,
payloadMetadata: {
attempt: input.attempt,
thresholdDays: input.thresholdDays,
},
});
}
export async function applyBillingDunningCycle(deps: BillingDunningDeps = {}) {
const client = deps.client ?? db;
const now = deps.now ?? new Date();
const sendDunningNotice = deps.sendDunningNotice ?? createBillingDunningNotification;
const subscriptions = await client.tenantSubscription.findMany({
where: { status: "past_due", pastDueSince: { not: null } },
select: { tenantId: true, status: true, pastDueSince: true, dunningAttemptCount: true },
});
const results: { tenantId: string; decision: BillingDunningDecision }[] = [];
for (const subscription of subscriptions) {
const decision = evaluateBillingDunning(subscription, now);
if (decision.kind === "send_dunning") {
await sendDunningNotice({ tenantId: subscription.tenantId, attempt: decision.attempt, thresholdDays: decision.thresholdDays });
await client.tenantSubscription.update({
where: { tenantId: subscription.tenantId },
data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now },
});
clearTenantSubscriptionCache(subscription.tenantId);
} else if (decision.kind === "freeze") {
await client.tenantSubscription.update({
where: { tenantId: subscription.tenantId },
data: { status: "frozen", frozenAt: now },
});
clearTenantSubscriptionCache(subscription.tenantId);
}
results.push({ tenantId: subscription.tenantId, decision });
}
return results;
}
async function setBillingStatusForTenant(
tenantId: string,
status: "trial" | "active" | "past_due" | "cancelled" | "frozen",
now: Date,
client: BillingDunningDeps["client"] = db,
) {
if (status === "past_due") {
const existingSubscription = await client.tenantSubscription.findUnique({
where: { tenantId },
select: { pastDueSince: true },
});
await client.tenantSubscription.update({
where: { tenantId },
data: {
status,
pastDueSince: existingSubscription?.pastDueSince ?? now,
frozenAt: null,
},
});
clearTenantSubscriptionCache(tenantId);
return;
}
await client.tenantSubscription.update({
where: { tenantId },
data: {
status,
pastDueSince: null,
frozenAt: null,
cancelledAt: status === "cancelled" ? now : null,
dunningAttemptCount: 0,
lastDunningSentAt: null,
},
});
clearTenantSubscriptionCache(tenantId);
}
function subscriptionIdFromInvoice(invoice: Record<string, unknown>): string | null {
const direct = invoice.subscription;
if (typeof direct === "string") return direct;
if (direct && typeof direct === "object" && "id" in direct && typeof direct.id === "string") return direct.id;
const parent = invoice.parent as { subscription_details?: { subscription?: unknown } } | null | undefined;
const parentSubscription = parent?.subscription_details?.subscription;
if (typeof parentSubscription === "string") return parentSubscription;
if (parentSubscription && typeof parentSubscription === "object" && "id" in parentSubscription && typeof parentSubscription.id === "string") {
return parentSubscription.id;
}
return null;
}
async function syncSubscriptionStatusFromStripeSubscription(
subscription: StripeSubscriptionLike,
now: Date,
client: BillingDunningDeps["client"] = db,
): Promise<string | null> {
const tenantProduct = await client.tenantSubscriptionProduct.findFirst({
where: { billingProviderSubscriptionId: subscription.id },
select: { id: true, tenantSubscription: { select: { tenantId: true } } },
});
if (!tenantProduct) return null;
await client.tenantSubscriptionProduct.update({
where: { id: tenantProduct.id },
data: {
currentPeriodStart: fromUnix(subscription.current_period_start),
currentPeriodEnd: fromUnix(subscription.current_period_end),
endsAt: fromUnix(subscription.cancel_at),
cancelledAt: fromUnix(subscription.canceled_at),
},
});
await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, billingStatusFromStripeSubscription(subscription.status), now, client);
return tenantProduct.tenantSubscription.tenantId;
}
async function markInvoiceSubscriptionStatus(
invoice: Record<string, unknown>,
status: "active" | "past_due",
now: Date,
client: BillingDunningDeps["client"] = db,
): Promise<string | null> {
const subscriptionId = subscriptionIdFromInvoice(invoice);
if (!subscriptionId) return null;
const tenantProduct = await client.tenantSubscriptionProduct.findFirst({
where: { billingProviderSubscriptionId: subscriptionId },
select: { tenantSubscription: { select: { tenantId: true } } },
});
if (!tenantProduct) return null;
await setBillingStatusForTenant(tenantProduct.tenantSubscription.tenantId, status, now, client);
return tenantProduct.tenantSubscription.tenantId;
}
export async function processStripeBillingEvent(event: Stripe.Event, deps: BillingDunningDeps = {}) {
const client = deps.client ?? db;
const now = deps.now ?? new Date();
const existing = await client.stripeWebhookLog.findUnique({ where: { stripeEventId: event.id } });
if (existing?.processedAt) {
return { replayed: true, relatedTenantId: existing.relatedTenantId ?? null };
}
await client.stripeWebhookLog.upsert({
where: { stripeEventId: event.id },
create: { stripeEventId: event.id, eventType: event.type },
update: { eventType: event.type, error: null },
});
try {
let relatedTenantId: string | null = null;
if (event.type === "customer.subscription.updated" || event.type === "customer.subscription.deleted") {
relatedTenantId = await syncSubscriptionStatusFromStripeSubscription(event.data.object as StripeSubscriptionLike, now, client);
} else if (event.type === "invoice.payment_failed") {
relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record<string, unknown>, "past_due", now, client);
} else if (event.type === "invoice.paid" || event.type === "invoice.payment_succeeded") {
relatedTenantId = await markInvoiceSubscriptionStatus(event.data.object as unknown as Record<string, unknown>, "active", now, client);
}
await client.stripeWebhookLog.update({
where: { stripeEventId: event.id },
data: { processedAt: now, relatedTenantId, error: null },
});
return { replayed: false, relatedTenantId };
} catch (error) {
await client.stripeWebhookLog.update({
where: { stripeEventId: event.id },
data: { error: error instanceof Error ? error.message : UNKNOWN_STRIPE_WEBHOOK_ERROR_CODE },
});
throw error;
}
}
@@ -4,6 +4,15 @@ const billingDomainMock = vi.hoisted(() => ({
resolveTenantBillingState: vi.fn(),
}));
const rlsMock = vi.hoisted(() => ({
getDbClient: vi.fn(() => ({ marker: "rls-client" })),
runWithRlsContext: vi.fn((_context: unknown, callback: () => unknown) => callback()),
}));
const storageMock = vi.hoisted(() => ({
resolveTenantStorageUsage: vi.fn(),
}));
const dbMock = vi.hoisted(() => ({
tenantSubscription: {
findUnique: vi.fn(),
@@ -23,6 +32,18 @@ vi.mock("@hivegrid/db/billing-domain.server", () => ({
resolveTenantBillingState: billingDomainMock.resolveTenantBillingState,
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: rlsMock.getDbClient,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: rlsMock.runWithRlsContext,
}));
vi.mock("~/services/billing/storage-capacity.server", () => ({
resolveTenantStorageUsage: storageMock.resolveTenantStorageUsage,
}));
vi.mock("./subscriptionService", () => ({
clearTenantSubscriptionCache: vi.fn(),
}));
@@ -31,7 +52,6 @@ import {
assertBillingUsageWithinQuota,
BILLING_USAGE_METRICS,
BillingUsageQuotaExceededError,
buildBillingStatusBannerVm,
getBillingUsageSummary,
getTenantBillingReadOnlyState,
isTenantBillingReadOnly,
@@ -41,6 +61,7 @@ import {
describe("billingStatusService", () => {
beforeEach(() => {
vi.clearAllMocks();
storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "subscription_missing" });
});
it("marks past-due, frozen and cancelled subscriptions as read-only", () => {
@@ -51,16 +72,6 @@ describe("billingStatusService", () => {
expect(isTenantBillingReadOnly("cancelled")).toBe(true);
});
it("builds localized billing status banner keys", () => {
expect(buildBillingStatusBannerVm({ status: "active", tenantSlug: "acme" })).toEqual({ visible: false });
expect(buildBillingStatusBannerVm({ status: "frozen", tenantSlug: "acme" })).toMatchObject({
visible: true,
severity: "danger",
messageKey: "billing:status.frozen",
actionHref: "/acme/settings/subscription",
});
});
it("reads tenant billing status for action write guards", async () => {
billingDomainMock.resolveTenantBillingState.mockResolvedValue({ status: "frozen", readOnly: true });
@@ -86,6 +97,41 @@ describe("billingStatusService", () => {
},
]),
});
expect(rlsMock.runWithRlsContext).toHaveBeenCalledWith({ tenantId: "tenant_1" }, expect.any(Function));
});
it("projects stored and reserved bytes against the canonical commercial storage capacity", async () => {
const capacityBytes = 350 * 1024 ** 3;
dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10));
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]);
storageMock.resolveTenantStorageUsage.mockResolvedValue({
available: true,
capacityBytes,
storedBytes: 50,
reservedBytes: 25,
remainingBytes: capacityBytes - 75,
});
const summary = await getBillingUsageSummary("tenant_1", new Date("2026-07-12T00:00:00.000Z"));
expect(summary.storageUnavailableReason).toBeNull();
expect(summary.metrics).toContainEqual({
metricCode: BILLING_USAGE_METRICS.storageBytes,
quantity: 75,
quota: capacityBytes,
remaining: capacityBytes - 75,
exceeded: false,
percentUsed: 0,
});
expect(storageMock.resolveTenantStorageUsage).toHaveBeenCalledWith({ marker: "rls-client" }, "tenant_1", new Date("2026-07-12T00:00:00.000Z"));
});
it("reports unavailable storage without presenting it as an unlimited allowance", async () => {
dbMock.tenantSubscription.findUnique.mockResolvedValue(null);
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([]);
storageMock.resolveTenantStorageUsage.mockResolvedValue({ available: false, reason: "plan_unknown" });
await expect(getBillingUsageSummary("tenant_1")).resolves.toMatchObject({ storageUnavailableReason: "plan_unknown" });
});
it("throws a quota error before usage exceeds the current period limit", async () => {
@@ -95,6 +141,7 @@ describe("billingStatusService", () => {
await expect(assertBillingUsageWithinQuota({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 2 })).rejects.toBeInstanceOf(
BillingUsageQuotaExceededError
);
expect(storageMock.resolveTenantStorageUsage).not.toHaveBeenCalled();
});
it("records usage idempotently and does not double-count retries", async () => {
@@ -1,4 +1,8 @@
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { getDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTenantStorageUsage } from "~/services/billing/storage-capacity.server";
import type { TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
@@ -15,15 +19,6 @@ const SUBSCRIPTION_FEATURE_LIMIT_MONTHLY = 2;
const SUBSCRIPTION_FEATURE_LIMIT_MAX = 3;
const SUBSCRIPTION_FEATURE_LIMIT_UNLIMITED = 4;
export type BillingStatusBannerVm =
| { visible: false }
| {
visible: true;
severity: "info" | "warning" | "danger";
messageKey: string;
actionHref: string;
};
export class BillingUsageQuotaExceededError extends Error {
readonly messageKey = "billing:usage.limitExceeded";
readonly metricCode: BillingUsageMetric;
@@ -53,28 +48,6 @@ export function isTenantBillingReadOnly(status: string | null | undefined): bool
return normalized === "past_due" || normalized === "frozen" || normalized === "cancelled";
}
export function buildBillingStatusBannerVm(input: {
status: string | null | undefined;
tenantSlug: string;
trialEndsAt?: Date | string | null;
}): BillingStatusBannerVm {
const status = normalizeBillingStatus(input.status);
const actionHref = `/${input.tenantSlug}/settings/subscription`;
if (status === "trial" && input.trialEndsAt) {
return { visible: true, severity: "info", messageKey: "billing:status.trial", actionHref };
}
if (status === "past_due") {
return { visible: true, severity: "warning", messageKey: "billing:status.pastDue", actionHref };
}
if (status === "frozen") {
return { visible: true, severity: "danger", messageKey: "billing:status.frozen", actionHref };
}
if (status === "cancelled") {
return { visible: true, severity: "warning", messageKey: "billing:status.cancelled", actionHref };
}
return { visible: false };
}
export async function getTenantBillingStatus(tenantId: string) {
return await db.tenantSubscription.findUnique({
where: { tenantId },
@@ -290,44 +263,71 @@ export async function recordBillingUsage(input: {
});
}
export async function getBillingUsageSummary(tenantId: string, now: Date = new Date()) {
const { periodStart, periodEnd } = getPeriodBounds(now);
const subscription = await loadTenantSubscriptionForUsage(tenantId);
const rows = await db.tenantSubscriptionUsageRecord.groupBy({
by: ["metricCode"],
where: {
tenantId,
timestamp: {
gte: Math.floor(periodStart.getTime() / 1000),
lt: Math.floor(periodEnd.getTime() / 1000),
},
},
_sum: { quantity: true },
export async function getBillingUsageSummary(
tenantId: string,
now: Date = new Date(),
options: { readonly includeCanonicalStorage?: boolean } = {},
) {
return runWithRlsContext({ tenantId }, async () => {
const { periodStart, periodEnd } = getPeriodBounds(now);
const [subscription, rows, storageUsage] = await Promise.all([
loadTenantSubscriptionForUsage(tenantId),
db.tenantSubscriptionUsageRecord.groupBy({
by: ["metricCode"],
where: {
tenantId,
timestamp: {
gte: Math.floor(periodStart.getTime() / 1000),
lt: Math.floor(periodEnd.getTime() / 1000),
},
},
_sum: { quantity: true },
}),
options.includeCanonicalStorage === false
? Promise.resolve(null)
: resolveTenantStorageUsage(getDbClient() as unknown as TenantRlsClient, tenantId, now),
]);
const quantities = new Map(rows.map((row) => [row.metricCode, row._sum.quantity ?? 0]));
const metricCodes = new Set<string>([...Object.values(BILLING_USAGE_METRICS), ...quantities.keys()]);
return {
periodStart,
periodEnd,
storageUnavailableReason: storageUsage === null || storageUsage.available ? null : storageUsage.reason,
metrics: [...metricCodes].map((metricCode) => {
if (metricCode === BILLING_USAGE_METRICS.storageBytes && storageUsage?.available) {
const quantity = storageUsage.storedBytes + storageUsage.reservedBytes;
const quota = storageUsage.capacityBytes;
return {
metricCode,
quantity,
quota,
remaining: storageUsage.remainingBytes,
exceeded: quantity >= quota,
percentUsed: Math.min(100, Math.round((quantity / quota) * 100)),
};
}
const quantity = quantities.get(metricCode) ?? 0;
const quota = Object.values(BILLING_USAGE_METRICS).includes(metricCode as BillingUsageMetric)
? resolveMetricQuota(subscription, metricCode as BillingUsageMetric)
: null;
return {
metricCode,
quantity,
quota,
remaining: quota === null ? null : Math.max(0, quota - quantity),
exceeded: quota !== null && quantity >= quota,
percentUsed: quota === null ? null : Math.min(100, Math.round((quantity / quota) * 100)),
};
}),
};
});
const quantities = new Map(rows.map((row) => [row.metricCode, row._sum.quantity ?? 0]));
const metricCodes = new Set<string>([...Object.values(BILLING_USAGE_METRICS), ...quantities.keys()]);
return {
periodStart,
periodEnd,
metrics: [...metricCodes].map((metricCode) => {
const quantity = quantities.get(metricCode) ?? 0;
const quota = Object.values(BILLING_USAGE_METRICS).includes(metricCode as BillingUsageMetric)
? resolveMetricQuota(subscription, metricCode as BillingUsageMetric)
: null;
return {
metricCode,
quantity,
quota,
remaining: quota === null ? null : Math.max(0, quota - quantity),
exceeded: quota !== null && quantity >= quota,
percentUsed: quota === null ? null : Math.min(100, Math.round((quantity / quota) * 100)),
};
}),
};
}
export async function assertBillingUsageWithinQuota(input: { tenantId: string; metricCode: BillingUsageMetric; quantity: number; at?: Date }) {
const summary = await getBillingUsageSummary(input.tenantId, input.at);
const summary = await getBillingUsageSummary(input.tenantId, input.at, {
includeCanonicalStorage: input.metricCode === BILLING_USAGE_METRICS.storageBytes,
});
const metric = summary.metrics.find((item) => item.metricCode === input.metricCode);
if (!metric?.quota) return;
if (metric.quantity + input.quantity > metric.quota) {
@@ -0,0 +1,36 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { isDemoDataUiEnabled, isManagedNormalDataTenant } from "./demoDataUi.server";
describe("isDemoDataUiEnabled", () => {
it("is enabled outside production regardless of the staging flags", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "development" })).toBe(true);
expect(isDemoDataUiEnabled({ NODE_ENV: "test" })).toBe(true);
expect(isDemoDataUiEnabled({})).toBe(true);
});
it("is enabled on staging (NODE_ENV=production + both staging demo flags)", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "true", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(true);
});
it("is disabled on production (no or partial staging demo flags)", () => {
expect(isDemoDataUiEnabled({ NODE_ENV: "production" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "true" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(false);
expect(isDemoDataUiEnabled({ NODE_ENV: "production", SEED_DEMO_DATA: "false", ALLOW_STAGING_DEMO_SEED: "true" })).toBe(false);
});
it("is disabled for the managed normal-data tenant even on staging", () => {
const env = {
NODE_ENV: "production",
SEED_DEMO_DATA: "true",
ALLOW_STAGING_DEMO_SEED: "true",
SEED_DEMO_PRO_MANAGED: "true",
SEED_DEMO_PRO_EXPECTED_TENANT_ID: "tenant-normal-data",
};
expect(isManagedNormalDataTenant({ tenantId: "tenant-normal-data" }, env)).toBe(true);
expect(isManagedNormalDataTenant({ tenantSlug: "demo-pro-crm" }, env)).toBe(true);
expect(isDemoDataUiEnabled(env, { tenantId: "tenant-normal-data", tenantSlug: "demo-pro-crm" })).toBe(false);
expect(isDemoDataUiEnabled(env, { tenantId: "tenant-other", tenantSlug: "other" })).toBe(true);
});
});
@@ -0,0 +1,49 @@
// Demo data is a staging/dev-only affordance. Staging deploys set
// SEED_DEMO_DATA=true + ALLOW_STAGING_DEMO_SEED=true (see .gitea/workflows/
// deploy.yml); production resources must never set those flags (enforced by
// scripts/verify-gitea-deploy-workflow.mjs). When the demo UI is disabled the
// list loaders ignore the `demo=show` query param server-side and the list
// screens hide their "show demo data" checkbox entirely.
//
// Mirrors the guard pair used by SeedService.shouldSeedCrmDemoData and
// AuthService.isStagingDemoLoginAllowed: outside production the demo UI is
// always available (local dev provisions demo data via the settings page);
// in production it requires both staging flags.
import { loadWebConfig } from "@hivegrid/config";
type DemoDataUiEnvironment = {
NODE_ENV?: string;
SEED_DEMO_DATA?: string;
ALLOW_STAGING_DEMO_SEED?: string;
SEED_DEMO_PRO_MANAGED?: string;
SEED_DEMO_PRO_EXPECTED_TENANT_ID?: string;
};
type DemoDataTenantContext = {
tenantId?: string | null;
tenantSlug?: string | null;
};
const MANAGED_NORMAL_DATA_TENANT_SLUG = "demo-pro-crm";
export function isManagedNormalDataTenant(context: DemoDataTenantContext, env?: DemoDataUiEnvironment): boolean {
const demoEnv = env ?? (process.env as DemoDataUiEnvironment);
if (demoEnv.SEED_DEMO_PRO_MANAGED !== "true") return false;
const expectedTenantId = demoEnv.SEED_DEMO_PRO_EXPECTED_TENANT_ID?.trim();
if (expectedTenantId && context.tenantId === expectedTenantId) return true;
return context.tenantSlug === MANAGED_NORMAL_DATA_TENANT_SLUG;
}
export function isDemoDataUiEnabled(env?: DemoDataUiEnvironment, context?: DemoDataTenantContext): boolean {
const demoEnv = env ?? (process.env as DemoDataUiEnvironment);
if (context && isManagedNormalDataTenant(context, demoEnv)) return false;
// Injected env keeps tests hermetic; the runtime default resolves NODE_ENV
// through @hivegrid/config (runtime NODE_ENV boundary, enforced by
// apps/web/app/utils/runtime-node-env-boundary.test.ts).
const nodeEnv = env ? env.NODE_ENV : loadWebConfig().config.nodeEnv;
if (nodeEnv !== "production") {
return true;
}
return demoEnv.SEED_DEMO_DATA === "true" && demoEnv.ALLOW_STAGING_DEMO_SEED === "true";
}
@@ -59,7 +59,7 @@ function getTier(): TwoTierCache<EvaluateFlagResult> {
export function getFeatureFlagCache(): FlagEvalCache {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createFlagEvalCache(getTier());
cacheSingleton = createFlagEvalCache(getTier(), getSharedStore());
return cacheSingleton;
}
@@ -71,9 +71,8 @@ export function getFeatureFlagCache(): FlagEvalCache {
export async function subscribeFeatureFlagCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const tier = getTier();
subscribeDisposer = await tier.subscribe(() => {
// Any invalidation drops everything — see cache.ts comment.
tier.flushLocal();
subscribeDisposer = await tier.subscribe((token) => {
getFeatureFlagCache().handleInvalidation(token);
});
log.info({ namespace: "feature-flags", channel: FEATURE_FLAGS_INVALIDATION_CHANNEL }, "feature-flag cache subscriber started");
return subscribeDisposer;
@@ -43,7 +43,7 @@ const createLoader = (): FlagLoader => async (key: string) => {
// OR-lookup so dependency-resolution (which calls back with an id)
// works against the same loader.
const row = await db.featureFlag.findFirst({
where: { OR: [{ name: key }, { id: key }] },
where: { archivedAt: null, OR: [{ name: key }, { id: key }] },
});
return toStored(row);
};
@@ -18,7 +18,7 @@
import { Params } from "react-router";
import type { EvaluateFlagResult } from "@hivegrid/feature-flags";
import { evaluateFlagForContext, evaluateFlagsForContext } from "./featureFlagEvaluator.server";
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getFeatureFlagEvaluationNames } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
@@ -84,14 +84,11 @@ export async function isFeatureFlagEnabled(
* `enabled=true` boolean modulo v2 rule evaluation.
*/
export async function getCurrentEnabledFlagNames(input: RequestContextInput): Promise<string[]> {
const [tenantId, userInfo, flags] = await Promise.all([
const [tenantId, userInfo, names] = await Promise.all([
resolveTenantIdForFlags(input),
getUserInfo(input.request),
getAllFeatureFlags(),
getFeatureFlagEvaluationNames(),
]);
const names = flags
.map((f) => f.name ?? f.key ?? "")
.filter((n) => n.length > 0);
if (names.length === 0) return [];
const results = await evaluateFlagsForContext(names, {
flagName: "*",
@@ -0,0 +1,419 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
type Marker = {
requestHash: string;
responseStatus: number;
responseBody: unknown;
responseHeaders: Record<string, string> | null;
expiresAt: Date | null;
};
const mocks = vi.hoisted(() => ({
getTenant: vi.fn(),
getOrPersistTenantSubscription: vi.fn(),
getAllSubscriptionProducts: vi.fn(),
getAllSubscriptionProductsStrict: vi.fn(),
addTenantSubscriptionProduct: vi.fn(),
getUser: vi.fn(),
createEvent: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
clearTenantSubscriptionCache: vi.fn(),
completeSelfServiceCheckout: vi.fn(),
loggerError: vi.fn(),
dbTransaction: vi.fn(),
executeRaw: vi.fn(),
upsertTenantSubscription: vi.fn(),
markers: new Map<string, Marker>(),
events: new Set<string>(),
subscriptionWrites: [] as unknown[],
transactionClients: [] as unknown[],
transactionOpen: false,
failCommitOnce: false,
failMarkerUpdateOnce: false,
}));
vi.mock("../../db/tenants.db.server", () => ({ getTenant: mocks.getTenant }));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getOrPersistTenantSubscription: mocks.getOrPersistTenantSubscription }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({
getAllSubscriptionProducts: mocks.getAllSubscriptionProducts,
getAllSubscriptionProductsStrict: mocks.getAllSubscriptionProductsStrict,
}));
vi.mock("../../db/subscriptions/tenantSubscriptionProducts.db.server", () => ({
addTenantSubscriptionProduct: mocks.addTenantSubscriptionProduct,
}));
vi.mock("../../db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("../../../modules/events/services/.server/EventsService", () => ({
default: {
create: mocks.createEvent,
createIdempotentTenantEvent: mocks.createIdempotentTenantEvent,
},
}));
vi.mock("~/application/pricing/currencies", () => ({
default: [{ value: "EUR", default: true }],
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: mocks.loggerError }),
}));
vi.mock("~/utils/db.server", () => ({ db: { $transaction: mocks.dbTransaction } }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
vi.mock("./subscriptionService", () => ({
cancelTenantSubscription: vi.fn(),
clearAllSubscriptionsCache: vi.fn(),
clearTenantSubscriptionCache: mocks.clearTenantSubscriptionCache,
getActiveTenantSubscriptions: vi.fn(),
}));
vi.mock("~/services/billing/self-service-checkout.server", () => ({ completeSelfServiceCheckout: mocks.completeSelfServiceCheckout }));
vi.mock("../../api/.server/TenantTypesApi", () => ({ TenantTypesApi: { setTenantTypes: vi.fn() } }));
import { autosubscribeToTrialOrFreePlan } from "./pricingService";
const IDEMPOTENCY_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const IDEMPOTENCY_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function markerStorageKey({ partitionKey, scope, key }: { partitionKey: string; scope: string; key: string }): string {
return `${partitionKey}:${scope}:${key}`;
}
function expectedMarkerKey(): string {
return markerStorageKey({ partitionKey: "tenant:tenant_1", scope: IDEMPOTENCY_SCOPE, key: IDEMPOTENCY_KEY });
}
function idempotencyClient() {
return {
$executeRaw: mocks.executeRaw,
tenantSubscription: {
upsert: mocks.upsertTenantSubscription,
},
idempotencyKey: {
findUnique: vi.fn(
async ({ where }: { where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } } }) =>
mocks.markers.get(markerStorageKey(where.idempotency_key_partition_scope_key)) ?? null
),
create: vi.fn(async ({ data }: { data: Marker & { partitionKey: string; scope: string; key: string } }) => {
const storageKey = markerStorageKey(data);
if (mocks.markers.has(storageKey)) throw Object.assign(new Error("duplicate marker"), { code: "P2002" });
const marker: Marker = {
requestHash: data.requestHash,
responseStatus: data.responseStatus,
responseBody: data.responseBody ?? null,
responseHeaders: data.responseHeaders ?? null,
expiresAt: data.expiresAt ?? null,
};
mocks.markers.set(storageKey, marker);
return marker;
}),
update: vi.fn(
async ({
where,
data,
}: {
where: { idempotency_key_partition_scope_key: { partitionKey: string; scope: string; key: string } };
data: Partial<Marker>;
}) => {
if (mocks.failMarkerUpdateOnce) {
mocks.failMarkerUpdateOnce = false;
throw new Error("marker update failed");
}
const storageKey = markerStorageKey(where.idempotency_key_partition_scope_key);
const existing = mocks.markers.get(storageKey);
if (!existing) throw new Error("marker missing");
const marker = { ...existing, ...data };
mocks.markers.set(storageKey, marker);
return marker;
}
),
deleteMany: vi.fn(async ({ where }: { where: { partitionKey: string; scope: string; key: string } }) => {
mocks.markers.delete(markerStorageKey(where));
return { count: 1 };
}),
},
};
}
function args(overrides: Record<string, unknown> = {}) {
return {
request: new Request("https://app.example.test/new-account"),
t: (key: string) => key,
tenantId: "tenant_1",
userId: "user_1",
throwOnFailure: true,
idempotencyKey: IDEMPOTENCY_KEY,
...overrides,
};
}
describe("autosubscribeToTrialOrFreePlan post-commit idempotency", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.markers.clear();
mocks.events.clear();
mocks.subscriptionWrites.length = 0;
mocks.transactionClients.length = 0;
mocks.transactionOpen = false;
mocks.failCommitOnce = false;
mocks.failMarkerUpdateOnce = false;
mocks.getTenant.mockResolvedValue({ id: "tenant_1", name: "Acme", slug: "acme" });
mocks.getOrPersistTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(false);
return { id: "subscription_1" };
});
const catalog = [
{
id: "product_1",
title: "Pro",
prices: [
{
id: "price_1",
currency: "EUR",
price: 10,
trialDays: 14,
subscriptionProductId: "product_1",
subscriptionProduct: { title: "Pro" },
},
],
},
];
mocks.getAllSubscriptionProducts.mockResolvedValue(catalog);
mocks.getAllSubscriptionProductsStrict.mockResolvedValue(catalog);
mocks.getUser.mockResolvedValue({ id: "user_1", email: "owner@example.test" });
mocks.executeRaw.mockResolvedValue(1);
mocks.upsertTenantSubscription.mockImplementation(async () => {
expect(mocks.transactionOpen).toBe(true);
return { id: "subscription_1" };
});
mocks.addTenantSubscriptionProduct.mockImplementation(async (input, options) => {
expect(mocks.transactionOpen).toBe(true);
mocks.subscriptionWrites.push({ input, options });
return { id: "tenant_product_1" };
});
mocks.clearTenantSubscriptionCache.mockImplementation(() => {
expect(mocks.transactionOpen).toBe(false);
});
mocks.createIdempotentTenantEvent.mockImplementation(async ({ idempotencyKey }: { idempotencyKey: string }) => {
expect(mocks.transactionOpen).toBe(false);
mocks.events.add(idempotencyKey);
});
mocks.dbTransaction.mockImplementation(async (callback: (tx: ReturnType<typeof idempotencyClient>) => Promise<unknown>) => {
const markerSnapshot = new Map(mocks.markers);
const writeCount = mocks.subscriptionWrites.length;
const tx = idempotencyClient();
mocks.transactionClients.push(tx);
mocks.transactionOpen = true;
try {
const result = await callback(tx);
if (mocks.failCommitOnce) {
mocks.failCommitOnce = false;
throw new Error("transaction commit failed");
}
mocks.transactionOpen = false;
return result;
} catch (error) {
mocks.markers.clear();
for (const [key, marker] of markerSnapshot) mocks.markers.set(key, marker);
mocks.subscriptionWrites.splice(writeCount);
mocks.transactionOpen = false;
throw error;
}
});
});
it("commits the local trial marker before cache and event dispatch and never calls a billing gateway", async () => {
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledWith(
expect.objectContaining({
tenantSubscriptionId: "subscription_1",
subscriptionProductId: "product_1",
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
}),
{
invalidateCache: false,
client: mocks.transactionClients[0],
}
);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_1");
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
expect.objectContaining({
event: "subscription.subscribed",
idempotencyKey: `tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
})
);
expect(mocks.executeRaw).toHaveBeenCalledOnce();
expect(mocks.upsertTenantSubscription).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
create: { tenantId: "tenant_1", billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("replays without a duplicate subscription while safely retrying cache invalidation and the idempotent event", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.idempotencyKey)).toEqual([
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`,
]);
expect(mocks.events.size).toBe(1);
});
it("serializes parallel retries to one subscription product and one event identity", async () => {
await Promise.all([autosubscribeToTrialOrFreePlan(args() as never), autosubscribeToTrialOrFreePlan(args() as never)]);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.events).toEqual(new Set([`tenant-bootstrap:tenant_1:${IDEMPOTENCY_KEY}:trial-subscribed`]));
expect(mocks.executeRaw).toHaveBeenCalledTimes(2);
});
it("fails closed when the strict bootstrap catalog read fails", async () => {
const error = new Error("subscription catalog unavailable");
mocks.getAllSubscriptionProductsStrict.mockRejectedValueOnce(error);
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toBe(error);
expect(mocks.dbTransaction).toHaveBeenCalledOnce();
expect(mocks.getAllSubscriptionProducts).not.toHaveBeenCalled();
expect(mocks.addTenantSubscriptionProduct).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
it("rolls back the local write when marker completion fails and retries cleanly", async () => {
mocks.failMarkerUpdateOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("marker update failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).resolves.toBeUndefined();
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("does not dispatch cache or event effects when the marker transaction commit fails", async () => {
mocks.failCommitOnce = true;
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("transaction commit failed");
expect(mocks.subscriptionWrites).toHaveLength(0);
expect(mocks.markers.has(expectedMarkerKey())).toBe(false);
expect(mocks.clearTenantSubscriptionCache).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("keeps a committed local trial and retries only the idempotent event after event commit failure", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("event commit failed");
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.markers.get(expectedMarkerKey())?.responseStatus).toBe(201);
await autosubscribeToTrialOrFreePlan(args() as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.addTenantSubscriptionProduct).toHaveBeenCalledOnce();
expect(mocks.clearTenantSubscriptionCache).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
});
it("reuses the committed locale-invariant event payload when the catalog changes before a retry", async () => {
mocks.createIdempotentTenantEvent.mockRejectedValueOnce(new Error("event commit failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `de:${key}` }) as never)).rejects.toThrow("event commit failed");
mocks.getAllSubscriptionProductsStrict.mockResolvedValueOnce([
{
id: "product_2",
title: "Business",
prices: [
{
id: "price_2",
currency: "EUR",
price: 20,
trialDays: 7,
subscriptionProductId: "product_2",
subscriptionProduct: { title: "Business" },
},
],
},
]);
mocks.getTenant.mockResolvedValueOnce({ id: "tenant_1", name: "Renamed", slug: "renamed" });
mocks.getUser.mockResolvedValueOnce({ id: "user_1", email: "changed@example.test" });
await autosubscribeToTrialOrFreePlan(args({ t: (key: string) => `en:${key}` }) as never);
expect(mocks.subscriptionWrites).toHaveLength(1);
expect(mocks.getAllSubscriptionProductsStrict).toHaveBeenCalledOnce();
expect(mocks.getTenant).toHaveBeenCalledOnce();
expect(mocks.getUser).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
const eventPayloads = mocks.createIdempotentTenantEvent.mock.calls.map(([input]) => input.data);
expect(eventPayloads).toEqual([
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
{
user: { id: "user_1", email: "owner@example.test" },
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
subscription: { product: { id: "product_1", title: "Pro" } },
},
]);
});
it("fails closed when a committed trial marker contains an invalid event projection", async () => {
await autosubscribeToTrialOrFreePlan(args() as never);
const marker = mocks.markers.get(expectedMarkerKey());
expect(marker).toBeDefined();
if (marker) {
marker.responseBody = {
state: "subscribed",
subscriptionProductId: "product_1",
subscriptionPriceId: "price_1",
eventData: { tenant: { id: "tenant_other" } },
};
}
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Workspace trial idempotency marker is invalid");
expect(mocks.subscriptionWrites).toHaveLength(1);
});
it("keeps legacy callers fail-soft while allowing workspace creation to fail closed", async () => {
mocks.addTenantSubscriptionProduct.mockRejectedValue(new Error("subscription write failed"));
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined, throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args({ idempotencyKey: undefined }) as never)).rejects.toThrow("subscription write failed");
expect(mocks.loggerError).toHaveBeenCalledTimes(2);
expect(JSON.stringify(mocks.loggerError.mock.calls)).not.toContain("subscription write failed");
expect(mocks.createEvent).not.toHaveBeenCalled();
expect(mocks.completeSelfServiceCheckout).not.toHaveBeenCalled();
});
it("does not complete a marker when RLS cannot see the committed tenant", async () => {
mocks.getTenant.mockResolvedValue(null);
await expect(autosubscribeToTrialOrFreePlan(args({ throwOnFailure: false }) as never)).resolves.toBeUndefined();
await expect(autosubscribeToTrialOrFreePlan(args() as never)).rejects.toThrow("Tenant unavailable for auto-subscribe");
expect(mocks.getOrPersistTenantSubscription).not.toHaveBeenCalled();
expect(mocks.markers.size).toBe(0);
});
});
@@ -8,23 +8,20 @@ import {
createSubscriptionFeature,
updateSubscriptionProductBillingProviderId,
updateSubscriptionPriceBillingProviderId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
deleteSubscriptionFeatures,
deleteSubscriptionUsageBasedTier,
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionProduct,
getAllSubscriptionProducts,
getAllSubscriptionProductsStrict,
} from "../../db/subscriptionProducts.db.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@hivegrid/db/prisma-browser";
import { getOrPersistTenantSubscription } from "../../db/tenantSubscriptions.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
@@ -35,28 +32,85 @@ import currencies from "~/application/pricing/currencies";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createScopedLogger } from "~/utils/logger.server";
import { completeSelfServiceCheckout } from "~/services/billing/self-service-checkout.server";
import { db } from "~/utils/db.server";
import { withIdempotency, type IdempotencyClient } from "@hivegrid/foundation";
import type { TenantBillingClient } from "@hivegrid/db/subscriptions.server";
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
const pricingLogger = createScopedLogger("pricing");
const WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE = "tenant-bootstrap/workspace-trial-autosubscribe-v1";
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 72)}`;
type WorkspaceTrialMarkerBody =
| {
state: "subscribed";
subscriptionProductId: string;
subscriptionPriceId: string | null;
eventData: SubscriptionSubscribedDto;
}
| {
state: "not-subscribed";
tenantId: string;
reason: "default-currency-unavailable" | "no-eligible-plan";
};
type WorkspaceTrialTransactionClient = IdempotencyClient & {
$executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<unknown>;
tenantSubscription: {
upsert(args: {
where: { tenantId: string };
create: { tenantId: string; billingProviderCustomerId: string };
update: Record<string, never>;
select: { id: true };
}): Promise<{ id: string }>;
};
};
function readWorkspaceTrialMarkerBody(body: unknown): WorkspaceTrialMarkerBody {
if (!isRecord(body)) throw new Error("Workspace trial idempotency marker is invalid");
const candidate = body;
if (
candidate.state === "not-subscribed" &&
typeof candidate.tenantId === "string" &&
(candidate.reason === "default-currency-unavailable" || candidate.reason === "no-eligible-plan")
) {
return candidate as WorkspaceTrialMarkerBody;
}
const eventData = candidate.eventData;
const tenant = isRecord(eventData) ? eventData.tenant : null;
const subscription = isRecord(eventData) ? eventData.subscription : null;
const product = isRecord(subscription) ? subscription.product : null;
const user = isRecord(eventData) ? eventData.user : undefined;
if (
candidate.state !== "subscribed" ||
typeof candidate.subscriptionProductId !== "string" ||
!(typeof candidate.subscriptionPriceId === "string" || candidate.subscriptionPriceId === null) ||
!isRecord(eventData) ||
!isRecord(tenant) ||
typeof tenant.id !== "string" ||
typeof tenant.name !== "string" ||
typeof tenant.slug !== "string" ||
!isRecord(subscription) ||
!isRecord(product) ||
product.id !== candidate.subscriptionProductId ||
typeof product.title !== "string" ||
!(subscription.session === undefined || typeof subscription.session === "string") ||
!(user === null || (isRecord(user) && typeof user.id === "string" && typeof user.email === "string"))
) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return candidate as WorkspaceTrialMarkerBody;
}
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features,
plan.usageBasedPrices
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value && typeof value === "object" && !Array.isArray(value));
}
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed
.toLowerCase()
.replace(/[^a-z0-9]+/g, "_")
.replace(/^_+|_+$/g, "")
.slice(0, 72)}`;
}
export async function createPlan(
@@ -64,7 +118,7 @@ export async function createPlan(
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[],
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
_t?: TFunction
) {
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
const product = await createSubscriptionProduct({
@@ -78,6 +132,7 @@ export async function createPlan(
groupDescription: plan.groupDescription ?? null,
active: plan.active,
public: plan.public,
kind: plan.kind ?? "recurring_add_on",
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity ?? false,
canBuyAgain: plan.canBuyAgain ?? false,
@@ -117,13 +172,13 @@ export async function createPlan(
usageBasedPrices.map(async (usageBasedPrice) => {
pricingLogger.info(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
"Creating usage-based price"
);
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
billingProviderId: localBillingProviderId(
"usage",
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`
),
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
@@ -202,42 +257,14 @@ export async function updatePlan(plan: SubscriptionProductDto, features: Subscri
}
export async function deletePlan(plan: SubscriptionProductDto) {
if (!plan.id) throw new Error("Subscription product id is required for deletion");
// Catalog children use ON DELETE CASCADE. One product delete is therefore a
// single atomic statement; a tenant-product FK rejects the whole statement
// without leaving partially deleted prices, tiers, or features behind.
await deleteSubscriptionProduct(plan.id);
await clearAllSubscriptionsCache();
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
await Promise.all(
plan.prices
.map(async (price) => {
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
return null;
})
);
pricingLogger.info(
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
"Deleting usage-based prices",
);
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
})
);
await deleteSubscriptionUsageBasedPrice(price.id);
return null;
})
);
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
pricingLogger.info({ op: "deletePlan", planId: plan.id }, "Deleted subscription product atomically");
}
export type CheckoutSessionResponse = {
@@ -273,8 +300,8 @@ export async function addTenantProductsFromCheckoutSession({
tenantId,
user,
checkoutSession,
createdUserId,
createdTenantId,
createdUserId: _createdUserId,
createdTenantId: _createdTenantId,
t,
}: {
request: Request;
@@ -309,7 +336,7 @@ export async function addTenantProductsFromCheckoutSession({
hasSubscribed,
recurringCount: recurringSubscriptions.length,
},
"Cancelling existing subscriptions before new subscribe",
"Cancelling existing subscriptions before new subscribe"
);
if (hasSubscribed && recurringSubscriptions.length > 0) {
await Promise.all(
@@ -321,7 +348,7 @@ export async function addTenantProductsFromCheckoutSession({
subscriptionId: recurringSubscription.id,
productId: recurringSubscription.subscriptionProductId,
},
"Cancelling tenant subscription",
"Cancelling tenant subscription"
);
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
})
@@ -395,8 +422,6 @@ export async function addTenantProductsFromCheckoutSession({
},
} satisfies SubscriptionSubscribedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
}
})
);
@@ -405,52 +430,158 @@ export async function addTenantProductsFromCheckoutSession({
export async function autosubscribeToTrialOrFreePlan({
request,
t,
t: _t,
tenantId,
userId,
throwOnFailure = false,
idempotencyKey,
}: {
request: Request;
t: TFunction;
tenantId: string;
userId: string | null;
throwOnFailure?: boolean;
idempotencyKey?: string;
}) {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
const tenant = await getTenant(tenantId);
if (!tenant) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
}
const allProducts = await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
try {
if (idempotencyKey) {
const markerBody = await db.$transaction(async (tx) => {
const client = tx as unknown as WorkspaceTrialTransactionClient;
const lockKey = `${WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE}:${tenantId}:${idempotencyKey}`;
await client.$executeRaw`SELECT pg_advisory_xact_lock(hashtextextended(${lockKey}, 0))`;
const result = await withIdempotency(
{
tenantId,
scope: WORKSPACE_TRIAL_AUTOSUBSCRIBE_SCOPE,
key: idempotencyKey,
fingerprint: {
version: 1,
tenantId,
userId,
},
},
client,
async () => {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "default-currency-unavailable",
} satisfies WorkspaceTrialMarkerBody,
};
}
// Strict reads happen only for a new marker. A committed replay must
// remain dispatchable even if the mutable catalog changes later.
const allProducts = await getAllSubscriptionProductsStrict(true);
const candidate = allProducts
.flatMap((product) => product.prices.map((price) => ({ price, productTitle: product.title })))
.find(({ price }) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0));
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded"
);
if (!candidate) {
return {
status: 204,
body: {
state: "not-subscribed",
tenantId,
reason: "no-eligible-plan",
} satisfies WorkspaceTrialMarkerBody,
};
}
const tenantSubscription = await client.tenantSubscription.upsert({
where: { tenantId },
create: { tenantId, billingProviderCustomerId: "" },
update: {},
select: { id: true },
});
const { price, productTitle } = candidate;
const user = userId ? await getUser(userId) : null;
const currentMarkerBody: WorkspaceTrialMarkerBody = {
state: "subscribed",
subscriptionProductId: price.subscriptionProductId,
subscriptionPriceId: price.id ?? null,
eventData: {
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: productTitle,
},
},
},
};
await addTenantSubscriptionProduct(
{
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [{ subscriptionPriceId: price.id }],
},
{
invalidateCache: false,
client: tx as unknown as TenantBillingClient,
}
);
return { status: 201, body: currentMarkerBody };
}
);
const stored = readWorkspaceTrialMarkerBody(result.body);
const storedTenantId = stored.state === "subscribed" ? stored.eventData.tenant.id : stored.tenantId;
if (storedTenantId !== tenantId) {
throw new Error("Workspace trial idempotency marker is invalid");
}
return stored;
});
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded",
);
allProducts.forEach((product) => {
if (product.prices.length === 0) {
if (markerBody.state === "not-subscribed") {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId, reason: markerBody.reason }, "No auto-subscription product was selected");
return;
}
clearTenantSubscriptionCache(tenantId);
await EventsService.createIdempotentTenantEvent({
request,
event: "subscription.subscribed",
tenantId,
userId: markerBody.eventData.user?.id ?? null,
data: markerBody.eventData,
idempotencyKey: `tenant-bootstrap:${tenantId}:${idempotencyKey}:trial-subscribed`,
});
return;
}
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) {
productsFree.push(product.prices[0]);
}
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) {
productsWithTrialDays.push(firstPriceWithTrialDays);
}
});
try {
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant unavailable for auto-subscribe");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((item) => item.default)?.value;
if (!defaultCurrency) return;
const allProducts = throwOnFailure ? await getAllSubscriptionProductsStrict(true) : await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
allProducts.forEach((product) => {
if (product.prices.length === 0) return;
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) productsFree.push(product.prices[0]);
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) productsWithTrialDays.push(firstPriceWithTrialDays);
});
if (productsWithTrialDays.length > 0) {
pricingLogger.info(
{
@@ -459,23 +590,26 @@ export async function autosubscribeToTrialOrFreePlan({
productCount: productsWithTrialDays.length,
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
},
"Autosubscribing tenant to trial/free plan",
"Autosubscribing tenant to trial/free plan"
);
const price = productsWithTrialDays[0];
await addTenantSubscriptionProduct({
const subscriptionProductInput = {
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
billingProviderSubscriptionId: "",
// Workspace auto-trials are local entitlements only. Provider checkout
// and subscription creation remain exclusive to the explicit billing flow.
billingProviderSubscriptionId: null,
fromCheckoutSessionId: null,
prices: [
{
subscriptionPriceId: price.id,
},
],
});
};
await addTenantSubscriptionProduct(subscriptionProductInput);
const user = userId ? await getUser(userId) : null;
await EventsService.create({
const eventArgs = {
request,
event: "subscription.subscribed",
tenantId: tenant.id,
@@ -484,28 +618,26 @@ export async function autosubscribeToTrialOrFreePlan({
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
},
product: { id: price.subscriptionProductId, title: price.subscriptionProduct?.title ?? "" },
},
} satisfies SubscriptionSubscribedDto,
});
} as const;
await EventsService.create(eventArgs);
} else if (productsFree.length > 0) {
// TODO(pricing): implement free-plan auto-subscribe. Free plans are planned for
// HiveGrid, so this branch must mirror the trial path above (create the free
// subscription + emit "subscription.subscribed") instead of only logging.
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
"Free products available but auto-subscribe-free path not implemented yet",
"Free products available but auto-subscribe-free path not implemented yet"
);
} else {
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
"No auto-subscription products/plans found",
);
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.none", tenantId }, "No auto-subscription products/plans found");
}
} catch (e: any) {
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
pricingLogger.error({ ...toSafeErrorLog(e), op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
if (throwOnFailure) {
throw e;
}
}
}
@@ -20,6 +20,7 @@ vi.mock("~/shared-store.server", async () => {
const store = createSharedStore({ namespace: "web-test", adapter });
return {
getSharedStore: () => store,
getCrossAppCacheStore: () => store,
__setSharedStoreFactoryForTests: vi.fn(),
__resetSharedStoreForTests: vi.fn(),
};
@@ -1,13 +1,13 @@
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
import { getSharedStore } from "~/shared-store.server";
import { getCrossAppCacheStore } from "~/shared-store.server";
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
/**
* Subscription cache (two-tier). L1 = in-process Map, L2 = SharedStore;
* cross-replica purges via pub/sub on channel
* `shared-store:web:ch:cache:subscription:invalidate`.
* `shared-store:cross-app-cache:ch:cache:subscription:invalidate`.
*
* Bootstrap (idempotent): call `subscribeSubscriptionCache()` once during
* web boot so this replica listens for invalidation messages emitted by
@@ -37,7 +37,7 @@ function ttlSecondsFromEnv(): number {
export function getSubscriptionCache(): TwoTierCache<TenantSubscriptionWithDetails | null> {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createTwoTierCache<TenantSubscriptionWithDetails | null>({
store: getSharedStore(),
store: getCrossAppCacheStore(),
namespace: "subscription",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
@@ -0,0 +1,52 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
const mocks = vi.hoisted(() => ({
getTenantSubscription: vi.fn(),
getTenantSubscriptions: vi.fn(),
}));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({
getTenantSubscription: mocks.getTenantSubscription,
getTenantSubscriptions: mocks.getTenantSubscriptions,
}));
import { getMrr } from "./subscriptionService";
describe("getMrr tenant RLS aggregation", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("loads every tenant subscription only inside its matching tenant context", async () => {
mocks.getTenantSubscription.mockImplementation(async (tenantId: string) => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
return {
id: `subscription_${tenantId}`,
tenantId,
products: [
{
endsAt: tenantId === "tenant_2" ? new Date("2020-01-01T00:00:00.000Z") : null,
prices: [
{
subscriptionPrice: {
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
price: 199,
currency: "eur",
},
},
],
},
],
};
});
const result = await runWithRlsContext({ userId: "operator_1" }, () => getMrr("eur", ["tenant_1", "tenant_2"]));
expect(result).toEqual({ total: 199, count: 1 });
expect(mocks.getTenantSubscription).toHaveBeenCalledTimes(2);
expect(getRlsExecutionContext()).toBeNull();
});
});
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({ db: {} }));
vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() }));
@@ -30,34 +30,130 @@ 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 { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
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<ReturnType<typeof getTenantSubscriptionProductById>> {
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<ReturnType<typeof getTenantSubscriptionProductById>>;
}
describe("cancelTenantSubscription", () => {
it("returns without logging when the product is not subscribed", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce({
id: "tenant-sub-product-id",
billingProviderSubscriptionId: null,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
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<ReturnType<typeof getUser>>);
vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited<ReturnType<typeof getTenant>>);
vi.mocked(cancelRecurringProductAcquisition).mockResolvedValueOnce({} as Awaited<ReturnType<typeof cancelRecurringProductAcquisition>>);
await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" });
expect(consoleLog).not.toHaveBeenCalled();
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");
});
consoleLog.mockRestore();
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<ReturnType<typeof getUser>>);
vi.mocked(getTenant).mockResolvedValueOnce({ id: "tenant-id", name: "Tenant" } as Awaited<ReturnType<typeof getTenant>>);
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");
});
});
@@ -95,9 +191,7 @@ describe("subscription cache invalidation", () => {
it("clearAllSubscriptionsCache broadcasts a wildcard cross-replica invalidation", async () => {
subscriptionCacheInvalidateMock.mockClear();
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce(
[] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>,
);
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce([] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>);
await clearAllSubscriptionsCache();
@@ -14,25 +14,30 @@ import {
type TenantSubscriptionWithDetails,
} from "@hivegrid/db/subscriptions.server";
import { getTenantSubscription, getTenantSubscriptions } from "../../db/tenantSubscriptions.db.server";
import { sendEmail } from "~/modules/emails/services/EmailService";
import { apiKeyCreditableStatusCodes, apiKeyIgnoreEndpoints } from "../../helpers/ApiKeyHelper";
import { getBaseURL } from "../../url.server";
import { cachified, clearCacheKey } from "../../cache.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import DateUtils from "~/utils/shared/DateUtils";
import { TFunction } from "i18next";
import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { SubscriptionCancelledDto } from "~/modules/events/dtos/SubscriptionCancelledDto";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { cancelRecurringProductAcquisition, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
const ADMIN_MRR_TENANT_QUERY_BATCH_SIZE = 10;
function getActiveTenantSubscriptionProducts(subscription: TenantSubscriptionWithDetails | null): TenantSubscriptionWithDetails["products"] {
const now = Date.now();
return subscription?.products.filter((product) => !product.endsAt || new Date(product.endsAt).getTime() > now) ?? [];
return (
subscription?.products.filter(
(product) =>
!product.cancelledAt &&
(!product.currentPeriodStart || new Date(product.currentPeriodStart).getTime() <= now) &&
(!product.endsAt || new Date(product.endsAt).getTime() > now)
) ?? []
);
}
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
@@ -44,8 +49,15 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; code?: string | null; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
const features: {
name: string;
code?: string | null;
order: number;
title: string;
type: SubscriptionFeatureLimitType;
value: number;
accumulate: boolean;
}[] = await getAllSubscriptionFeatures();
features
.filter((f) => (f.code || f.name) && (f.code || f.name) !== DefaultFeatures.Credits)
.forEach((feature) => {
@@ -314,57 +326,62 @@ async function getSpentCredits(where: Prisma.CreditWhereInput): Promise<number>
// }
export async function getActiveTenantSubscriptions(tenantId: string) {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
// This service is also called outside the app route middleware. Bind the
// tenant here so forced RLS never turns a valid subscription into a silent
// null result on staging/production while preserving an inherited user id.
return await runWithRlsContext({ tenantId }, async () => {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const updatedItem = await updateTenantSubscriptionProduct(
{ id: item.id, tenantId: mySubscription.tenantId },
{
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
);
// Cross-replica purge: billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
mySubscription.products = mySubscription.products.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
return mySubscription;
})
);
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
}
return mySubscription;
});
}
export async function getActiveTenantsSubscriptions() {
const subscriptions = await getTenantSubscriptions();
return await Promise.all(
subscriptions.map(async (mySubscription) => {
await Promise.all(
mySubscription.products.map(async () => undefined)
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
await Promise.all(mySubscription.products.map(async () => undefined));
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
return mySubscription;
})
);
@@ -401,23 +418,28 @@ export async function persistCheckoutSessionStatus({
id,
fromUrl,
fromUserId,
fromTenantId,
tenantId,
}: {
request: Request;
id: string;
fromUrl: string;
fromUserId?: string | null;
fromTenantId?: string | null;
tenantId: string;
}) {
void request;
void id;
void fromUrl;
void fromUserId;
void fromTenantId;
void tenantId;
}
export async function getMrr(currency: string) {
const activeSubscriptions = await getActiveTenantsSubscriptions();
export async function getMrr(currency: string, tenantIds: string[]) {
const activeSubscriptions = (await getTenantSubscriptionsInRlsBatches(tenantIds))
.filter((subscription): subscription is TenantSubscriptionWithDetails => subscription !== null)
.map((subscription) => ({
...subscription,
products: subscription.products.filter((product) => !product.endsAt || new Date(product.endsAt) > new Date()),
}));
let summary: { total: number; count: number } = {
total: 0,
count: 0,
@@ -433,6 +455,15 @@ export async function getMrr(currency: string) {
return summary;
}
async function getTenantSubscriptionsInRlsBatches(tenantIds: string[]): Promise<(TenantSubscriptionWithDetails | null)[]> {
const subscriptions: (TenantSubscriptionWithDetails | null)[] = [];
for (let index = 0; index < tenantIds.length; index += ADMIN_MRR_TENANT_QUERY_BATCH_SIZE) {
const batch = tenantIds.slice(index, index + ADMIN_MRR_TENANT_QUERY_BATCH_SIZE);
subscriptions.push(...(await Promise.all(batch.map((tenantId) => runWithRlsContext({ tenantId }, () => getTenantSubscription(tenantId))))));
}
return subscriptions;
}
function getPriceInCurrency(subscriptionPrice: SubscriptionPrice | null, currency: string) {
if (!subscriptionPrice) {
return 0;
@@ -500,9 +531,11 @@ export async function clearAllSubscriptionsCache() {
clearCacheKey(`tenantSubscription:${tenantSub.tenantId}`);
});
// Wildcard fan-out — peer replicas flush their L1 entirely.
await getSubscriptionCache().invalidate().catch(() => {
/* logged inside helper */
});
await getSubscriptionCache()
.invalidate()
.catch(() => {
/* logged inside helper */
});
}
export async function cancelTenantSubscription(
@@ -513,27 +546,36 @@ export async function cancelTenantSubscription(
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (tenantSubscriptionProduct.subscriptionProduct.kind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition) {
throw new ProductAcquisitionError("ACQUISITION_NOT_FOUND");
}
if (tenantSubscriptionProduct.acquisition.productKind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition.lagoSubscriptionId?.trim()) {
throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
}
const user = userId ? await getUser(userId) : null;
const tenant = await getTenant(tenantId);
if (user && tenant) {
await EventsService.create({
event: "subscription.cancelled",
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto,
});
}
await cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: new Date(),
if (!user || !tenant) throw new Error("Subscription cancellation actor or tenant not found");
const eventData = {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto;
await cancelRecurringProductAcquisition({
tenantId,
actorUserId: user.id,
tenantSubscriptionProductId: tenantSubscriptionProduct.id,
eventData,
});
clearTenantSubscriptionCache(tenantId);
}
@@ -0,0 +1,23 @@
// AK-P21 — deletion_pending read-only state. While a tenant deletion request
// sits in its 30-day grace window (or is executing), the workspace is
// read-only. Enforced by the same central write guard as the AK-P20/BILL-05
// billing frozen mode (assertTenantWritableForRequest); the privacy area
// stays writable so admins can withdraw the request or pull an export.
import { getDbClient } from "@hivegrid/db/client.server";
export type TenantDeletionReadOnlyState = {
readOnly: boolean;
status: "none" | "pending" | "executing";
};
export async function getTenantDeletionReadOnlyState(tenantId: string): Promise<TenantDeletionReadOnlyState> {
const request = await getDbClient().tenantDeletionRequest.findFirst({
where: { tenantId, status: { in: ["pending", "executing"] } },
select: { status: true },
});
if (!request) {
return { readOnly: false, status: "none" };
}
return { readOnly: true, status: request.status === "executing" ? "executing" : "pending" };
}