Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,282 @@
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" },
] 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;
}
export async function getFirstStepsChecklist(input: { tenantId: string; userId: string }) {
const session = await provisionShkTenantDefaults(input);
const rows = await db.onboardingSessionStep.findMany({
where: { onboardingSessionId: session.id },
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 },
});
}
const dismissed = session.status === "dismissed";
const items = rows.map((row) => {
const config = checklistSteps.find((step) => step.block === row.step.block);
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,
};
});
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,
status: !dismissed && items.length > 0 && completedCount === items.length ? "completed" : session.status,
dismissed,
completedCount,
totalCount: items.length,
percentComplete: items.length > 0 ? Math.round((completedCount / items.length) * 100) : 0,
items,
};
}
async function detectFirstStepsCompletion(input: { tenantId: string; userId: string }): Promise<Set<FirstStepsBlock>> {
const [user, contactCount, projectCount, subscription] = await Promise.all([
db.user.findUnique({ where: { id: input.userId }, select: { firstName: true, lastName: true, email: true } }),
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 (contactCount > 0) completed.add("contacts");
if (projectCount > 0) completed.add("projects");
if (subscription?.status === "trial" || subscription?.status === "active") completed.add("billing");
return completed;
}
export async function updateFirstStepsChecklist(input: {
tenantId: string;
userId: string;
sessionStepId?: string | null;
action: "complete" | "hide";
}) {
const session = await provisionShkTenantDefaults(input);
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");
}
return await db.onboardingSessionStep.updateMany({
where: {
id: input.sessionStepId,
onboardingSession: {
tenantId: input.tenantId,
userId: input.userId,
},
},
data: { completedAt: new Date() },
});
}
export async function getDemoDataStatus(tenantId: string) {
return await db.onboardingDemoProvisioning.findFirst({
where: { tenantId, templateCode: SHK_DEMO_TEMPLATE_CODE, status: "active", deletedAt: null },
orderBy: { createdAt: "desc" },
});
}
export async function provisionShkDemoData(input: { tenantId: string; userId: string }) {
const existing = await getDemoDataStatus(input.tenantId);
if (existing) {
return existing;
}
const { pipeline, firstOpenStage } = await ensureDefaultSalesPipeline({ tenantId: input.tenantId, userId: input.userId });
const contacts = await Promise.all(
["Muster GmbH", "Solar Schmidt", "Elektro Weber", "Hausverwaltung Nord", "Ada Lovelace"].map((name, index) =>
db.kontakt.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
kontaktTyp: index === 4 ? "privatperson" : "organisation",
kontaktStatus: index < 2 ? "kunde" : "kontakt",
orgName: index === 4 ? null : name,
vorname: index === 4 ? "Ada" : null,
nachname: index === 4 ? "Lovelace" : null,
primaerEmail: `demo-${index + 1}@example.invalid`,
isDemoData: true,
zustaendigerUserId: input.userId,
},
})
)
);
const projects = await Promise.all(
["Heizungstausch Musterstraße", "PV-Angebot Nord", "Wartung Bestandshaus"].map((name, index) =>
db.projekt.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
projektNummer: `DEMO-${String(index + 1).padStart(4, "0")}`,
projektname: name,
projekttyp: index === 2 ? "auftrag" : "deal",
quelle: "demo",
pipelineId: pipeline.id,
stageId: firstOpenStage.id,
zustaendigePersonId: input.userId,
isDemoData: true,
},
})
)
);
const tasks = await Promise.all(
["Demo-Kontakt prüfen", "Demo-Projekt kalkulieren", "Demo-Angebot versenden"].map((title, index) =>
db.task.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
assignedToUserId: input.userId,
title,
linkedEntityType: "project",
linkedEntityId: projects[index % projects.length].id,
isDemoData: true,
},
})
)
);
const entitiesCreated: DemoEntityMap = {
kontakt: contacts.map((item) => item.id),
projekt: projects.map((item) => item.id),
task: tasks.map((item) => item.id),
};
return await db.onboardingDemoProvisioning.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
templateCode: SHK_DEMO_TEMPLATE_CODE,
entitiesCreated,
removableUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
},
});
}
export async function deleteShkDemoData(input: { tenantId: string; provisioningId: string }) {
const provisioning = await db.onboardingDemoProvisioning.findFirst({
where: { id: input.provisioningId, tenantId: input.tenantId, status: "active", deletedAt: null },
});
if (!provisioning) {
return null;
}
const entities = provisioning.entitiesCreated as DemoEntityMap;
await db.$transaction([
db.task.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.task ?? [] }, isDemoData: true } }),
db.projekt.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.projekt ?? [] }, isDemoData: true } }),
db.kontakt.deleteMany({ where: { tenantId: input.tenantId, id: { in: entities.kontakt ?? [] }, isDemoData: true } }),
db.onboardingDemoProvisioning.update({
where: { id: provisioning.id },
data: { status: "deleted", deletedAt: new Date() },
}),
]);
return provisioning;
}
@@ -0,0 +1,211 @@
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,
},
});
});
});
@@ -0,0 +1,247 @@
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;
}
}
@@ -0,0 +1,142 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const billingDomainMock = vi.hoisted(() => ({
resolveTenantBillingState: vi.fn(),
}));
const dbMock = vi.hoisted(() => ({
tenantSubscription: {
findUnique: vi.fn(),
},
tenantSubscriptionUsageRecord: {
findUnique: vi.fn(),
groupBy: vi.fn(),
upsert: vi.fn(),
},
}));
vi.mock("~/utils/db.server", () => ({
db: dbMock,
}));
vi.mock("@hivegrid/db/billing-domain.server", () => ({
resolveTenantBillingState: billingDomainMock.resolveTenantBillingState,
}));
vi.mock("./subscriptionService", () => ({
clearTenantSubscriptionCache: vi.fn(),
}));
import {
assertBillingUsageWithinQuota,
BILLING_USAGE_METRICS,
BillingUsageQuotaExceededError,
buildBillingStatusBannerVm,
getBillingUsageSummary,
getTenantBillingReadOnlyState,
isTenantBillingReadOnly,
recordBillingUsage,
} from "./billingStatusService";
describe("billingStatusService", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("marks past-due, frozen and cancelled subscriptions as read-only", () => {
expect(isTenantBillingReadOnly("trial")).toBe(false);
expect(isTenantBillingReadOnly("active")).toBe(false);
expect(isTenantBillingReadOnly("past_due")).toBe(true);
expect(isTenantBillingReadOnly("frozen")).toBe(true);
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 });
await expect(getTenantBillingReadOnlyState("tenant_1")).resolves.toEqual({ readOnly: true, status: "frozen" });
expect(billingDomainMock.resolveTenantBillingState).toHaveBeenCalledWith("tenant_1");
});
it("returns usage summary with quota state from subscription features", async () => {
dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10));
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([{ metricCode: BILLING_USAGE_METRICS.automationRuns, _sum: { quantity: 8 } }]);
await expect(getBillingUsageSummary("tenant_1", new Date("2026-07-12T00:00:00.000Z"))).resolves.toMatchObject({
periodStart: new Date("2026-07-01T00:00:00.000Z"),
periodEnd: new Date("2026-08-01T00:00:00.000Z"),
metrics: expect.arrayContaining([
{
metricCode: BILLING_USAGE_METRICS.automationRuns,
quantity: 8,
quota: 10,
remaining: 2,
exceeded: false,
percentUsed: 80,
},
]),
});
});
it("throws a quota error before usage exceeds the current period limit", async () => {
dbMock.tenantSubscription.findUnique.mockResolvedValue(subscriptionWithQuota(10));
dbMock.tenantSubscriptionUsageRecord.groupBy.mockResolvedValue([{ metricCode: BILLING_USAGE_METRICS.automationRuns, _sum: { quantity: 9 } }]);
await expect(assertBillingUsageWithinQuota({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 2 })).rejects.toBeInstanceOf(
BillingUsageQuotaExceededError
);
});
it("records usage idempotently and does not double-count retries", async () => {
const existing = { id: "usage_1", quantity: 1 };
dbMock.tenantSubscriptionUsageRecord.findUnique.mockResolvedValue(existing);
await expect(
recordBillingUsage({ tenantId: "tenant_1", metricCode: BILLING_USAGE_METRICS.automationRuns, quantity: 1, idempotencyKey: "job_1" })
).resolves.toBe(existing);
expect(dbMock.tenantSubscription.findUnique).not.toHaveBeenCalled();
expect(dbMock.tenantSubscriptionUsageRecord.upsert).not.toHaveBeenCalled();
});
});
function subscriptionWithQuota(limit: number) {
return {
id: "subscription_1",
products: [
{
quantity: 1,
subscriptionProduct: {
features: [
{
code: BILLING_USAGE_METRICS.automationRuns,
name: BILLING_USAGE_METRICS.automationRuns,
quotaValue: { [BILLING_USAGE_METRICS.automationRuns]: limit },
type: 2,
value: limit,
accumulate: false,
},
],
},
prices: [
{
id: "tenant_price_1",
subscriptionUsageBasedPrice: {
unit: BILLING_USAGE_METRICS.automationRuns,
usageType: BILLING_USAGE_METRICS.automationRuns,
},
},
],
},
],
};
}
@@ -0,0 +1,341 @@
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { db } from "~/utils/db.server";
import { clearTenantSubscriptionCache } from "./subscriptionService";
export const BILLING_MODULE_KEY = "billing";
export const BILLING_USAGE_METRICS = {
automationRuns: "automation_runs",
storageBytes: "storage_bytes",
} as const;
export type BillingUsageMetric = (typeof BILLING_USAGE_METRICS)[keyof typeof BILLING_USAGE_METRICS];
export type TenantBillingStatus = "trial" | "active" | "past_due" | "cancelled" | "frozen";
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;
readonly limit: number;
readonly requestedQuantity: number;
readonly currentQuantity: number;
constructor(input: { metricCode: BillingUsageMetric; limit: number; requestedQuantity: number; currentQuantity: number }) {
super(`Billing usage quota exceeded for ${input.metricCode}.`);
this.name = "BillingUsageQuotaExceededError";
this.metricCode = input.metricCode;
this.limit = input.limit;
this.requestedQuantity = input.requestedQuantity;
this.currentQuantity = input.currentQuantity;
}
}
function normalizeBillingStatus(value: string | null | undefined): TenantBillingStatus {
if (value === "active" || value === "past_due" || value === "cancelled" || value === "frozen") {
return value;
}
return "trial";
}
export function isTenantBillingReadOnly(status: string | null | undefined): boolean {
const normalized = normalizeBillingStatus(status);
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 },
select: {
tenantId: true,
status: true,
trialStartsAt: true,
trialEndsAt: true,
pastDueSince: true,
frozenAt: true,
cancelledAt: true,
dunningAttemptCount: true,
lastDunningSentAt: true,
},
});
}
export async function getTenantBillingReadOnlyState(tenantId: string) {
const status = await resolveTenantBillingState(tenantId);
return {
readOnly: status.readOnly,
status: status.status,
};
}
function getPeriodBounds(now: Date) {
return {
periodStart: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1, 0, 0, 0)),
periodEnd: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 0, 0, 0)),
};
}
function toPositiveInteger(value: unknown): number | null {
if (typeof value !== "number" || !Number.isFinite(value)) {
return null;
}
const normalized = Math.trunc(value);
return normalized > 0 ? normalized : null;
}
function readQuotaFromJson(value: unknown, metricCode: BillingUsageMetric): number | null {
const direct = toPositiveInteger(value);
if (direct !== null) return direct;
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
const keyed = toPositiveInteger(record[metricCode]);
if (keyed !== null) return keyed;
if (record.metricCode === metricCode) {
return toPositiveInteger(record.limit) ?? toPositiveInteger(record.monthlyLimit) ?? toPositiveInteger(record.value);
}
const metrics = record.metrics;
if (metrics && typeof metrics === "object" && !Array.isArray(metrics)) {
return toPositiveInteger((metrics as Record<string, unknown>)[metricCode]);
}
return null;
}
function featureMatchesMetric(feature: { code?: string | null; name?: string | null }, metricCode: BillingUsageMetric): boolean {
return feature.code === metricCode || feature.name === metricCode;
}
function resolveFeatureQuota(
feature: { code?: string | null; name?: string | null; quotaValue?: unknown; type: number; value: number },
metricCode: BillingUsageMetric
): number | "unlimited" | null {
const quotaValue = readQuotaFromJson(feature.quotaValue, metricCode);
if (quotaValue !== null) return quotaValue;
if (!featureMatchesMetric(feature, metricCode)) return null;
if (feature.type === SUBSCRIPTION_FEATURE_LIMIT_UNLIMITED) return "unlimited";
if (feature.type === SUBSCRIPTION_FEATURE_LIMIT_MONTHLY || feature.type === SUBSCRIPTION_FEATURE_LIMIT_MAX) {
return toPositiveInteger(feature.value);
}
return null;
}
function resolveMetricQuota(subscription: Awaited<ReturnType<typeof loadTenantSubscriptionForUsage>>, metricCode: BillingUsageMetric): number | null {
let quota: number | null = null;
let unlimited = false;
for (const product of subscription?.products ?? []) {
const quantity = product.quantity && product.quantity > 0 ? product.quantity : 1;
for (const feature of product.subscriptionProduct.features) {
const featureQuota = resolveFeatureQuota(feature, metricCode);
if (featureQuota === "unlimited") {
unlimited = true;
continue;
}
if (featureQuota === null) continue;
const weightedQuota = feature.accumulate ? featureQuota * quantity : featureQuota;
quota = quota === null ? weightedQuota : feature.accumulate ? quota + weightedQuota : Math.max(quota, weightedQuota);
}
}
return unlimited ? null : quota;
}
async function loadTenantSubscriptionForUsage(tenantId: string) {
return await db.tenantSubscription.findUnique({
where: { tenantId },
include: {
products: {
include: {
subscriptionProduct: {
include: {
features: true,
},
},
prices: {
include: {
subscriptionUsageBasedPrice: true,
},
},
},
},
},
});
}
export async function setTenantBillingStatus(
tenantId: string,
data: {
status: TenantBillingStatus;
trialStartsAt?: Date | null;
trialEndsAt?: Date | null;
pastDueSince?: Date | null;
frozenAt?: Date | null;
cancelledAt?: Date | null;
dunningAttemptCount?: number;
lastDunningSentAt?: Date | null;
}
) {
const item = await db.tenantSubscription.upsert({
where: { tenantId },
create: {
tenantId,
status: data.status,
trialStartsAt: data.trialStartsAt,
trialEndsAt: data.trialEndsAt,
pastDueSince: data.pastDueSince,
frozenAt: data.frozenAt,
cancelledAt: data.cancelledAt,
dunningAttemptCount: data.dunningAttemptCount ?? 0,
lastDunningSentAt: data.lastDunningSentAt,
},
update: data,
});
clearTenantSubscriptionCache(tenantId);
return item;
}
export async function recordBillingUsage(input: {
tenantId: string;
metricCode: BillingUsageMetric;
quantity: number;
idempotencyKey?: string | null;
at?: Date;
}) {
if (input.quantity <= 0) {
return null;
}
const idempotencyKey = input.idempotencyKey ?? `${input.metricCode}:${Date.now()}`;
if (input.idempotencyKey) {
const existing = await db.tenantSubscriptionUsageRecord.findUnique({
where: {
tenantId_metricCode_idempotencyKey: {
tenantId: input.tenantId,
metricCode: input.metricCode,
idempotencyKey: input.idempotencyKey,
},
},
});
if (existing) return existing;
}
const subscription = await loadTenantSubscriptionForUsage(input.tenantId);
if (!subscription) {
return null;
}
await assertBillingUsageWithinQuota({ tenantId: input.tenantId, metricCode: input.metricCode, quantity: input.quantity, at: input.at });
const usagePrice = subscription.products
.flatMap((product) => product.prices)
.find((price) => price.subscriptionUsageBasedPrice?.unit === input.metricCode || price.subscriptionUsageBasedPrice?.usageType === input.metricCode);
if (!usagePrice) {
return null;
}
return await db.tenantSubscriptionUsageRecord.upsert({
where: {
tenantId_metricCode_idempotencyKey: {
tenantId: input.tenantId,
metricCode: input.metricCode,
idempotencyKey,
},
},
create: {
tenantId: input.tenantId,
tenantSubscriptionId: subscription.id,
tenantSubscriptionProductPriceId: usagePrice.id,
metricCode: input.metricCode,
timestamp: Math.floor((input.at ?? new Date()).getTime() / 1000),
quantity: input.quantity,
idempotencyKey,
billingProviderSubscriptionItemId: null,
},
update: {
quantity: input.quantity,
},
});
}
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 },
});
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 metric = summary.metrics.find((item) => item.metricCode === input.metricCode);
if (!metric?.quota) return;
if (metric.quantity + input.quantity > metric.quota) {
throw new BillingUsageQuotaExceededError({
metricCode: input.metricCode,
limit: metric.quota,
requestedQuantity: input.quantity,
currentQuantity: metric.quantity,
});
}
}
@@ -1,243 +0,0 @@
import Constants from "~/application/Constants";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { EntitiesTemplateDto, TemplateEntityDto, TemplateEntityViewDto } from "~/modules/templates/EntityTemplateDto";
import getMaxEntityOrder, { createEntity, EntityWithDetails, findEntityByName, getEntityByName } from "../../db/entities/entities.db.server";
import { createEntityRelationship, EntityRelationshipWithDetails } from "../../db/entities/entityRelationships.db.server";
import { createEntityView, updateEntityViewProperties, updateEntityViewFilters, updateEntityViewSort } from "../../db/entities/entityViews.db.server";
import { createProperty, updatePropertyOptions, updatePropertyAttributes, getEntityPropertyByName } from "../../db/entities/properties.db.server";
import { createEntityPermissions } from "../../db/permissions/permissions.db.server";
import EntityViewHelper from "../../helpers/EntityViewHelper";
import OrderHelper from "../../helpers/OrderHelper";
import { mapToEntityTemplateType } from "../../helpers/PropertyHelper";
export async function validateEntitiesFromTemplate(template: EntitiesTemplateDto) {
if (template.entities.length === 0) {
throw Error("Invalid configuration");
}
await Promise.all(
template.entities.map(async (entity) => {
const existingEntity = await findEntityByName({ tenantId: null, name: entity.name });
if (existingEntity) {
throw Error("Entity already exists: " + entity.name);
}
if (!entity.properties || entity.properties.length === 0) {
throw Error("Entity has no properties: " + entity.name);
}
entity.properties.forEach((property) => {
if (property.name.includes(" ")) {
throw Error("Property names cannot contain spaces: " + property.name);
}
if (property.name.includes("-")) {
throw Error("Property names cannot contain '-': " + property.name);
}
});
})
);
}
export async function importEntitiesFromTemplate({ template, createdByUserId }: { template: EntitiesTemplateDto; createdByUserId: string }) {
const maxEntityOrder = await getMaxEntityOrder();
const createdEntities = await Promise.all(
template.entities.map(async (entity, idx) => {
const createdEntity = await createEntity(
{
name: entity.name,
slug: entity.slug,
prefix: entity.prefix,
title: entity.title,
titlePlural: entity.titlePlural,
isAutogenerated: entity.isAutogenerated ?? true,
hasApi: entity.hasApi ?? true,
icon: entity.icon ?? "",
active: entity.active ?? true,
type: entity.type ?? DefaultEntityTypes.All,
showInSidebar: entity.showInSidebar ?? true,
hasTags: entity.hasTags ?? true,
hasComments: entity.hasComments ?? true,
hasTasks: entity.hasTasks ?? false,
hasActivity: entity.hasActivity !== undefined ? entity.hasActivity : true,
hasBulkDelete: entity.hasBulkDelete !== undefined ? entity.hasBulkDelete : false,
hasViews: entity.hasViews !== undefined ? entity.hasViews : true,
defaultVisibility: entity.defaultVisibility ?? DefaultVisibility.Tenant,
onCreated: entity.onCreated ?? "redirectToOverview",
onEdit: entity.onEdit ?? "editRoute",
},
maxEntityOrder + idx + 1
);
// eslint-disable-next-line no-console
console.log("Entity created", createdEntity.name);
if (!createdEntity) {
throw new Error("Unable to create entity: " + JSON.stringify(entity));
}
await createEntityPermissions(createdEntity);
const newEntity = await getEntityByName({ tenantId: null, name: createdEntity.name });
const propertyOrder = OrderHelper.getNextOrder(newEntity.properties);
const properties = await Promise.all(
entity.properties.map(async (property, idxProperty) => {
let type: PropertyType | undefined = undefined;
if (property.type === "string") {
type = PropertyType.TEXT;
} else if (property.type === "number") {
type = PropertyType.NUMBER;
} else if (property.type === "boolean") {
type = PropertyType.BOOLEAN;
} else if (property.type === "date") {
type = PropertyType.DATE;
} else if (property.type === "media") {
type = PropertyType.MEDIA;
} else if (property.type === "select") {
type = PropertyType.SELECT;
} else if (property.type === "multiSelect") {
type = PropertyType.MULTI_SELECT;
} else if (property.type === "multiText") {
type = PropertyType.MULTI_TEXT;
} else if (property.type === "rangeNumber") {
type = PropertyType.RANGE_NUMBER;
} else if (property.type === "rangeDate") {
type = PropertyType.RANGE_DATE;
} else if (property.type === "formula") {
type = PropertyType.FORMULA;
} else {
throw new Error("Invalid property type: " + property.type);
}
const createdProperty = await createProperty({
entityId: createdEntity.id,
name: property.name,
title: property.title,
type,
subtype: property.subtype ?? null,
order: propertyOrder + idxProperty,
isDefault: false,
isRequired: property.isRequired ?? false,
isHidden: false,
isDisplay: property.isDisplay ?? false,
isReadOnly: property.isReadOnly ?? false,
canUpdate: property.canUpdate !== undefined ? property.canUpdate : true,
showInCreate: property.showInCreate ?? true,
formulaId: null,
tenantId: property.tenantId ?? null,
});
if (property.options) {
await updatePropertyOptions(
createdProperty.id,
property.options.map((item, idxOption) => {
return {
order: idxOption + 1,
value: item.value,
name: item.name,
color: item.color === undefined ? undefined : item.color,
};
})
);
}
if (property.attributes) {
await updatePropertyAttributes(
createdProperty.id,
property.attributes.map((item) => {
return {
value: item.value,
name: item.name,
};
})
);
}
return createdProperty;
})
);
// Views
if (entity.views) {
await Promise.all(
entity.views.map(async (view, idx) => {
const groupByProperty = properties.find((f) => f.name === view.groupByProperty);
if (view.tenantId) {
return;
}
const entityView = await createEntityView({
order: idx + 1,
entityId: createdEntity.id,
layout: view.layout,
name: view.name,
title: view.title,
isDefault: view.isDefault ?? false,
tenantId: null,
userId: view.userId ?? null,
createdByUserId,
isSystem: view.isSystem ?? false,
pageSize: view.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
groupByPropertyId: groupByProperty?.id ?? null,
});
let viewProperties: { propertyId: string | null; order: number; name: string }[] = view.properties
? await Promise.all(
view.properties.map(async (prop, idxProp) => {
const property = await getEntityPropertyByName(createdEntity.id, prop);
return {
order: idxProp + 1,
propertyId: property?.id ?? null,
name: prop,
};
})
)
: [];
if (viewProperties.length === 0) {
viewProperties = newEntity.properties.map((item) => {
return {
propertyId: item.id,
order: item.order,
name: item.name,
};
});
}
const viewFilters: { name: string; condition: string; value: string; match: "and" | "or" }[] =
view.filters?.map((filter) => {
return {
match: filter.match ?? "and",
name: filter.name,
condition: filter.condition,
value: filter.value,
};
}) ?? [];
const viewSort: { name: string; asc: boolean; order: number }[] =
view.sort?.map((sort, idxSort) => {
return {
name: sort.name,
asc: sort.asc,
order: idxSort + 1,
};
}) ?? [];
await updateEntityViewProperties(entityView.id, viewProperties);
await updateEntityViewFilters(entityView.id, viewFilters);
await updateEntityViewSort(entityView.id, viewSort);
})
);
}
return createdEntity;
})
);
if (createdEntities.length > 0 && template.relationships) {
await Promise.all(
template.relationships.map(async (relationship) => {
const fromEntity = await getEntityByName({ tenantId: null, name: relationship.parent });
const toEntity = await getEntityByName({ tenantId: null, name: relationship.child });
return await createEntityRelationship({
parentId: fromEntity.id,
childId: toEntity.id,
order: relationship.order ?? 0,
title: relationship.title ?? null,
type: relationship.type ?? "one-to-many",
required: relationship.required ?? false,
cascade: false,
readOnly: relationship.readOnly ?? false,
hiddenIfEmpty: relationship.hiddenIfEmpty !== undefined ? relationship.hiddenIfEmpty : false,
childEntityViewId: null,
parentEntityViewId: null,
});
})
);
}
return createdEntities;
}
@@ -18,8 +18,8 @@ import {
createFlagEvalCache,
type EvaluateFlagResult,
type FlagEvalCache,
} from "@toolctrl/feature-flags";
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
} from "@hivegrid/feature-flags";
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
@@ -2,7 +2,7 @@
* Server-side evaluateFlag bridge.
*
* Wires the Prisma FeatureFlag table into the package-level
* `evaluateFlag` (`@toolctrl/feature-flags`). Caller passes a request
* `evaluateFlag` (`@hivegrid/feature-flags`). Caller passes a request
* + an EvaluationContext; we look up the row by name (caches L2-first
* via the feature-flag eval cache), run the pure evaluator and
* memo-cache the typed result for 60s.
@@ -19,9 +19,9 @@ import {
type EvaluateFlagResult,
type FlagLoader,
type StoredFeatureFlag,
} from "@toolctrl/feature-flags";
import type { EvaluationContext } from "@toolctrl/feature-flags";
import type { FeatureFlag } from "@toolctrl/db/prisma-browser";
} from "@hivegrid/feature-flags";
import type { EvaluationContext } from "@hivegrid/feature-flags";
import type { FeatureFlag } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
import { getFeatureFlagCache } from "./featureFlagCache.server";
@@ -16,7 +16,7 @@
*/
import { Params } from "react-router";
import type { EvaluateFlagResult } from "@toolctrl/feature-flags";
import type { EvaluateFlagResult } from "@hivegrid/feature-flags";
import { evaluateFlagForContext, evaluateFlagsForContext } from "./featureFlagEvaluator.server";
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getUserInfo } from "~/utils/session.server";
@@ -27,12 +27,31 @@ export interface RequestContextInput {
params: Params;
}
/**
* Resolve the tenant for a feature-flag lookup without ever redirecting.
*
* `getTenantIdOrNull` throws a redirect Response for "invalid-app-route" /
* "tenant-not-found" contexts (e.g. when a shared/root loader receives splat
* params instead of `:tenant`). Feature-flag evaluation runs in the root data
* loader on every request and must degrade to "no tenant" rather than bounce
* the whole app to the app root. Swallow the redirect Response only; rethrow
* real errors.
*/
async function resolveTenantIdForFlags(input: RequestContextInput): Promise<string | null> {
try {
return await getTenantIdOrNull(input);
} catch (error) {
if (error instanceof Response) return null;
throw error;
}
}
export async function evaluateFlagForRequest(
flagName: string,
{ request, params }: RequestContextInput,
): Promise<EvaluateFlagResult> {
const [tenantId, userInfo] = await Promise.all([
getTenantIdOrNull({ request, params }),
resolveTenantIdForFlags({ request, params }),
getUserInfo(request),
]);
return evaluateFlagForContext(flagName, {
@@ -66,7 +85,7 @@ export async function isFeatureFlagEnabled(
*/
export async function getCurrentEnabledFlagNames(input: RequestContextInput): Promise<string[]> {
const [tenantId, userInfo, flags] = await Promise.all([
getTenantIdOrNull(input),
resolveTenantIdForFlags(input),
getUserInfo(input.request),
getAllFeatureFlags(),
]);
@@ -6,8 +6,8 @@ import {
createSubscriptionProduct,
createSubscriptionPrice,
createSubscriptionFeature,
updateSubscriptionProductStripeId,
updateSubscriptionPriceStripeId,
updateSubscriptionProductBillingProviderId,
updateSubscriptionPriceBillingProviderId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
@@ -16,28 +16,12 @@ import {
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionPriceByStripeId,
getSubscriptionUsageBasedPriceByStripeId,
getSubscriptionProduct,
getAllSubscriptionProducts,
} from "../../db/subscriptionProducts.db.server";
import {
createStripeProduct,
createStripePrice,
archiveStripePrice,
deleteStripeProduct,
updateStripeProduct,
createStripeUsageBasedPrice,
archiveStripeProduct,
getStripeSession,
createStripeCustomer,
createStripeSubscription,
} from "../../stripe.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@toolctrl/db/prisma-browser";
import Stripe from "stripe";
import { getOrPersistTenantSubscription, updateTenantSubscriptionCustomerId } from "../../db/tenantSubscriptions.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 { getCheckoutSessionStatus, updateCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
@@ -50,9 +34,14 @@ import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscr
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";
const pricingLogger = createScopedLogger("pricing");
function localBillingProviderId(prefix: string, seed: string) {
return `local_${prefix}_${seed.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 72)}`;
}
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
@@ -77,11 +66,9 @@ export async function createPlan(
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
) {
// Create stripe product
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
// Save to db
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
const product = await createSubscriptionProduct({
stripeId: stripeProduct?.id ?? "",
billingProviderId: productBillingProviderId,
order: plan.order,
title: plan.title,
model: plan.model,
@@ -102,13 +89,10 @@ export async function createPlan(
await Promise.all(
prices.map(async (price) => {
// Create stripe price
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
// Save to db
return await createSubscriptionPrice({
...price,
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
billingProviderId: localBillingProviderId("price", `${product.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
type: SubscriptionPriceType.RECURRING,
billingPeriod: price.billingPeriod,
price: price.price,
@@ -135,13 +119,12 @@ export async function createPlan(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
);
const stripePrice = await createStripeUsageBasedPrice(stripeProduct?.id ?? "", {
...usageBasedPrice,
unitTitle: t ? t(usageBasedPrice.unitTitle) : usageBasedPrice.unitTitle,
});
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
billingProviderId: localBillingProviderId(
"usage",
`${product.id}_${usageBasedPrice.billingPeriod}_${usageBasedPrice.currency}_${usageBasedPrice.unit}`,
),
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
unit: usageBasedPrice.unit,
@@ -175,23 +158,14 @@ export async function syncPlan(
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
if (!stripeProduct) {
throw new Error("Could not create product");
}
await updateSubscriptionProductStripeId(plan.id, {
stripeId: stripeProduct.id,
const productBillingProviderId = plan.billingProviderId || localBillingProviderId("product", plan.title);
await updateSubscriptionProductBillingProviderId(plan.id, {
billingProviderId: productBillingProviderId,
});
prices.map(async (price) => {
// Create stripe price
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
if (!stripePrice) {
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
}
// Save to db
await updateSubscriptionPriceStripeId(price.id ?? "", {
stripeId: stripePrice?.id ?? "",
await updateSubscriptionPriceBillingProviderId(price.id ?? "", {
billingProviderId: localBillingProviderId("price", `${plan.id}_${price.billingPeriod}_${price.currency}_${price.price}`),
});
});
}
@@ -201,8 +175,6 @@ export async function updatePlan(plan: SubscriptionProductDto, features: Subscri
throw new Error(`Plan ${plan.title} not found on database`);
}
await updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
await updateSubscriptionProduct(plan.id, {
order: plan.order,
title: plan.title,
@@ -235,10 +207,7 @@ export async function deletePlan(plan: SubscriptionProductDto) {
await Promise.all(
plan.prices
.filter((f) => f.stripeId)
.map(async (price) => {
await archiveStripePrice(price.stripeId);
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
@@ -254,8 +223,6 @@ export async function deletePlan(plan: SubscriptionProductDto) {
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await archiveStripePrice(price.stripeId);
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
@@ -268,19 +235,6 @@ export async function deletePlan(plan: SubscriptionProductDto) {
);
}
pricingLogger.info({ op: "deletePlan.product", planId: plan.id, stripeId: plan.stripeId }, "Deleting Stripe product");
if (plan.stripeId) {
try {
await deleteStripeProduct(plan.stripeId);
} catch (e: any) {
pricingLogger.warn(
{ err: e, op: "deletePlan.product.archive", planId: plan.id, stripeId: plan.stripeId },
"Could not delete Stripe product; archiving instead",
);
await archiveStripeProduct(plan.stripeId);
}
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
@@ -301,91 +255,17 @@ export type CheckoutSessionResponse = {
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[];
status: CheckoutSessionStatus | null;
source?: "self-service" | "legacy";
};
export async function getAcquiredItemsFromCheckoutSession(session_id: string | null): Promise<CheckoutSessionResponse | null> {
const session = await getStripeSession(session_id ?? "");
if (!session || session.status !== "complete") {
export async function getAcquiredItemsFromCheckoutSession(
session_id: string | null,
options?: { tenantId?: string | null }
): Promise<CheckoutSessionResponse | null> {
if (!session_id || !options?.tenantId) {
pricingLogger.warn({ op: "getAcquiredItemsFromCheckoutSession", sessionId: session_id }, "Checkout session context is missing");
return null;
}
const prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[] = [];
try {
let line_items: { price: Stripe.Price; quantity: number | undefined }[] = [];
if (session.line_items) {
session.line_items.data.forEach((item) => {
if (item.price) {
line_items.push({
price: item.price,
quantity: item.quantity ?? undefined,
});
}
});
}
await Promise.all(
line_items.map(async (line_item) => {
const flatPrice = await getSubscriptionPriceByStripeId(line_item.price.id);
const usageBasedPrice = await getSubscriptionUsageBasedPriceByStripeId(line_item.price.id);
const quantity = line_item.quantity ?? undefined;
if (!flatPrice && !usageBasedPrice) {
throw new Error("Price not found: " + line_item.price.id);
}
prices.push({
flatPrice: flatPrice ?? undefined,
usageBasedPrice: usageBasedPrice ?? undefined,
quantity,
});
})
);
} catch (e: any) {
pricingLogger.error({ err: e, op: "getAcquiredItemsFromCheckoutSession" }, "Failed to load acquired items from checkout session");
}
const products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[] = [];
prices.forEach((item) => {
const productId = item.flatPrice?.subscriptionProductId ?? item.usageBasedPrice?.subscriptionProductId ?? "";
if (!productId) {
return;
}
const product = products.find((p) => p.id === productId);
if (!product) {
products.push({
id: productId,
title: "",
quantity: item.quantity ?? 1,
prices: [item],
subscription: session.subscription?.toString(),
});
} else {
product?.prices.push(item);
}
});
await Promise.all(
products.map(async (product) => {
const subscriptionProduct = await getSubscriptionProduct(product.id);
product.title = subscriptionProduct?.title ?? "";
})
);
const status = await getCheckoutSessionStatus(session.id);
return {
id: session.id,
customer: {
id: session.customer?.toString() ?? "",
name: session.customer_details?.name ?? "",
email: session.customer_details?.email ?? "",
},
products,
status,
};
return await completeSelfServiceCheckout({ sessionId: session_id, tenantId: options.tenantId });
}
export async function addTenantProductsFromCheckoutSession({
@@ -405,6 +285,9 @@ export async function addTenantProductsFromCheckoutSession({
createdTenantId?: string | null;
t: TFunction;
}) {
if (checkoutSession.source === "self-service") {
return;
}
clearTenantSubscriptionCache(tenantId);
const appConfiguration = await getAppConfiguration({ request });
const tenant = await getTenant(tenantId);
@@ -412,34 +295,13 @@ export async function addTenantProductsFromCheckoutSession({
throw new Error("Tenant not found");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
if (!tenantSubscription.stripeCustomerId) {
const customer = await createStripeCustomer(user.email, tenant.name);
if (customer) {
tenantSubscription.stripeCustomerId = customer.id;
await updateTenantSubscriptionCustomerId(tenant.id, {
stripeCustomerId: customer.id,
});
}
}
const existingSessionStatus = await getCheckoutSessionStatus(checkoutSession.id);
if (!checkoutSession) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (checkoutSession.customer.id !== tenantSubscription.stripeCustomerId) {
throw new Error(t("settings.subscription.checkout.invalidCustomer"));
} else if (!existingSessionStatus) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (!existingSessionStatus.pending) {
throw new Error(t("settings.subscription.checkout.alreadyProcessed"));
} else {
await updateCheckoutSessionStatus(checkoutSession.id, {
pending: false,
createdUserId,
createdTenantId,
});
if (!appConfiguration.subscription.multiple) {
const hasSubscribed = checkoutSession.products.some((product) => product.subscription);
const activeSubscriptions = await getActiveTenantSubscriptions(tenant.id);
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.stripeSubscriptionId) || [];
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.billingProviderSubscriptionId) || [];
pricingLogger.info(
{
op: "cancelExistingSubscriptions",
@@ -474,7 +336,7 @@ export async function addTenantProductsFromCheckoutSession({
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: product.id ?? "",
quantity: product.quantity,
stripeSubscriptionId: product.subscription ?? "",
billingProviderSubscriptionId: product.subscription ?? "",
fromCheckoutSessionId: checkoutSession.id,
prices: product.prices.map((price) => {
return {
@@ -558,10 +420,7 @@ export async function autosubscribeToTrialOrFreePlan({
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
if (!tenant.subscription?.stripeCustomerId) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant has no Stripe customer id; skipping");
return;
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
@@ -603,13 +462,11 @@ export async function autosubscribeToTrialOrFreePlan({
"Autosubscribing tenant to trial/free plan",
);
const price = productsWithTrialDays[0];
const trial_end = Math.floor(Date.now() / 1000) + (price.trialDays || 30) * 24 * 60 * 60;
const stripeSubscription = await createStripeSubscription(tenant.subscription.stripeCustomerId, price.stripeId, trial_end);
await addTenantSubscriptionProduct({
tenantSubscriptionId: tenant.subscription.id,
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
stripeSubscriptionId: stripeSubscription.id,
billingProviderSubscriptionId: "",
fromCheckoutSessionId: null,
prices: [
{
@@ -635,7 +492,9 @@ export async function autosubscribeToTrialOrFreePlan({
} satisfies SubscriptionSubscribedDto,
});
} else if (productsFree.length > 0) {
// TODO: IMPLEMENT
// 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",
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryAdapter, createSharedStore } from "@toolctrl/shared-store";
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
vi.mock("~/utils/cache.server", () => {
const map = new Map<string, unknown>();
@@ -15,7 +15,7 @@ vi.mock("~/utils/cache.server", () => {
});
vi.mock("~/shared-store.server", async () => {
const { MemoryAdapter, createSharedStore } = await import("@toolctrl/shared-store");
const { MemoryAdapter, createSharedStore } = await import("@hivegrid/shared-store");
const adapter = new MemoryAdapter();
const store = createSharedStore({ namespace: "web-test", adapter });
return {
@@ -1,5 +1,5 @@
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
@@ -2,9 +2,8 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({ db: {} }));
vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() }));
vi.mock("../../db/stripe/checkoutSessions.db.server", () => ({ createCheckoutSessionStatus: vi.fn(), getCheckoutSessionStatus: vi.fn() }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({ getAllSubscriptionFeatures: vi.fn() }));
vi.mock("@toolctrl/db/subscriptions.server", () => ({
vi.mock("@hivegrid/db/subscriptions.server", () => ({
createTenantSubscriptionUsageRecord: vi.fn(),
listTenantSubscriptionIds: vi.fn(),
updateTenantSubscriptionProduct: vi.fn(),
@@ -12,12 +11,6 @@ vi.mock("@toolctrl/db/subscriptions.server", () => ({
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn(), getTenantSubscriptions: vi.fn() }));
vi.mock("~/modules/emails/services/EmailService", () => ({ sendEmail: vi.fn() }));
vi.mock("../../helpers/ApiKeyHelper", () => ({ apiKeyCreditableStatusCodes: [], apiKeyIgnoreEndpoints: [] }));
vi.mock("../../stripe.server", () => ({
cancelStripeSubscription: vi.fn(),
createUsageRecord: vi.fn(),
getStripeSession: vi.fn(),
getStripeSubscription: vi.fn(),
}));
vi.mock("../../url.server", () => ({ getBaseURL: vi.fn() }));
vi.mock("./pricingService", () => ({ getAcquiredItemsFromCheckoutSession: vi.fn() }));
vi.mock("../../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn(), clearCacheKeyPrefix: vi.fn() }));
@@ -48,23 +41,21 @@ import {
clearAllSubscriptionsCache,
clearTenantSubscriptionCache,
} from "./subscriptionService";
import { cancelStripeSubscription } from "../../stripe.server";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { clearCacheKey } from "../../cache.server";
import { listTenantSubscriptionIds } from "@toolctrl/db/subscriptions.server";
import { listTenantSubscriptionIds } from "@hivegrid/db/subscriptions.server";
describe("cancelTenantSubscription", () => {
it("returns without logging or calling Stripe when the product is not subscribed", async () => {
it("returns without logging when the product is not subscribed", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce({
id: "tenant-sub-product-id",
stripeSubscriptionId: null,
billingProviderSubscriptionId: null,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" });
expect(consoleLog).not.toHaveBeenCalled();
expect(cancelStripeSubscription).not.toHaveBeenCalled();
consoleLog.mockRestore();
});
@@ -1,4 +1,4 @@
import { Prisma, SubscriptionPrice } from "@toolctrl/db/prisma-browser";
import { Prisma, SubscriptionPrice } from "@hivegrid/db/prisma-browser";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
@@ -6,21 +6,17 @@ import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/Sub
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import currencies from "~/application/pricing/currencies";
import { db } from "../../db.server";
import { findSimpleEntityByName } from "../../db/entities/entities.db.server";
import { createCheckoutSessionStatus, getCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { getAllSubscriptionFeatures } from "../../db/subscriptionProducts.db.server";
import {
createTenantSubscriptionUsageRecord,
listTenantSubscriptionIds,
updateTenantSubscriptionProduct,
type TenantSubscriptionWithDetails,
} from "@toolctrl/db/subscriptions.server";
} 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 { cancelStripeSubscription, getStripeSession, getStripeSubscription } from "../../stripe.server";
import { getBaseURL } from "../../url.server";
import { getAcquiredItemsFromCheckoutSession } from "./pricingService";
import { cachified, clearCacheKey } from "../../cache.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import DateUtils from "~/utils/shared/DateUtils";
@@ -34,6 +30,11 @@ import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
function getActiveTenantSubscriptionProducts(subscription: TenantSubscriptionWithDetails | null): TenantSubscriptionWithDetails["products"] {
const now = Date.now();
return subscription?.products.filter((product) => !product.endsAt || new Date(product.endsAt).getTime() > now) ?? [];
}
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
let subscription: TenantSubscriptionWithDetails | null = null;
if (tenantSubscription === undefined) {
@@ -43,16 +44,17 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
const features: { name: string; code?: string | null; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
features
.filter((f) => f.name)
.filter((f) => (f.code || f.name) && (f.code || f.name) !== DefaultFeatures.Credits)
.forEach((feature) => {
const existing = allFeatures.find((f) => f.name === feature.name);
const featureName = feature.code || feature.name;
const existing = allFeatures.find((f) => f.name === featureName);
if (!existing) {
allFeatures.push({
order: feature.order,
name: feature.name,
name: featureName,
title: feature.title,
type: feature.type,
value: feature.value,
@@ -65,7 +67,8 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
await Promise.all(
allFeatures.map(async (item) => {
let myFeatures: SubscriptionFeatureDto[] = [];
subscription?.products.forEach((product) => {
const activeProducts = getActiveTenantSubscriptionProducts(subscription);
activeProducts.forEach((product) => {
const feature = product.subscriptionProduct.features.find((f) => f.name === item.name);
if (feature) {
if (!product.quantity) {
@@ -80,9 +83,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
});
const existingSubscriptionFeature = mergeFeatures(myFeatures);
const feature = existingSubscriptionFeature ?? item;
const entity = await findSimpleEntityByName(item.name);
const usage: PlanFeatureUsageDto = {
entity: entity ?? undefined,
order: feature.order,
title: feature.title,
name: feature.name,
@@ -97,7 +98,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
if (!existingSubscriptionFeature) {
usage.type = SubscriptionFeatureLimitType.NOT_INCLUDED;
usage.enabled = false;
if (subscription?.products && subscription.products.length > 0) {
if (activeProducts.length > 0) {
usage.message = "featureLimits.upgradeSubscription";
} else {
usage.message = "featureLimits.noSubscription";
@@ -110,7 +111,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
usage.used = await getUsed(tenantId, feature, subscription);
usage.remaining = usage.value - usage.used;
if (usage.remaining <= 0) {
usage.message = `You've reached the limit (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.message = `You've reached the limit (${usage.used}/${usage.value}) for ${feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
@@ -121,7 +122,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
// var now = new Date();
// const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
usage.message = `You've reached the limit this month (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.message = `You've reached the limit this month (${usage.used}/${usage.value}) for ${feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
@@ -185,7 +186,7 @@ function getUsedPeriod(subscription: TenantSubscriptionWithDetails | null) {
lastDay = new Date(y + 1, 0, 0, 23, 59, 59);
}
subscription?.products.forEach((product) => {
getActiveTenantSubscriptionProducts(subscription).forEach((product) => {
if (product.currentPeriodStart && product.currentPeriodEnd) {
firstDay = product.currentPeriodStart;
lastDay = product.currentPeriodEnd;
@@ -252,33 +253,9 @@ async function getUsed(tenantId: string, feature: SubscriptionFeatureDto, subscr
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await getSpentCredits({ tenantId });
}
} else {
const entity = await findSimpleEntityByName(feature.name);
// if (!entity) {
// // throw new Error("Entity does not exist with plural title: " + feature.name);
// }
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
const where: Prisma.RowWhereInput = {
tenantId,
entityId: entity?.id ?? "",
createdAt: {
gte: firstDay,
lt: lastDay,
},
};
return db.row.count({
where,
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
const count = await db.row.count({
where: {
tenantId,
entityId: entity?.id ?? "",
},
});
return count;
}
}
// Entity-based feature usage was tracked through the generic entity-builder,
// which has been removed. Such features no longer have a row-based usage count.
return 0;
}
@@ -345,7 +322,7 @@ export async function getActiveTenantSubscriptions(tenantId: string) {
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
@@ -362,18 +339,11 @@ export async function getActiveTenantSubscriptions(tenantId: string) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
let startOfDay = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
let endOfDay = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
item.currentPeriodStart = DateUtils.getDateStartOfDay(startOfDay);
item.currentPeriodEnd = DateUtils.getDateEndOfDay(endOfDay);
}
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: the Stripe billing-period sync mutates the
// 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);
@@ -392,15 +362,7 @@ export async function getActiveTenantsSubscriptions() {
return await Promise.all(
subscriptions.map(async (mySubscription) => {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
item.currentPeriodStart = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
item.currentPeriodEnd = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
}
}
})
mySubscription.products.map(async () => undefined)
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
return mySubscription;
@@ -417,23 +379,16 @@ export async function reportUsage(tenantId: string, unit: string) {
tenantSubscription.products.map(async (product) => {
return await Promise.all(
product.prices.map(async (price) => {
if (!product.stripeSubscriptionId) {
return;
}
if (price.subscriptionUsageBasedPrice?.unit === unit) {
const stripeSubscription = await getStripeSubscription(product.stripeSubscriptionId);
const subscriptionItem = stripeSubscription?.items.data.find((f) => f.price.id === price.subscriptionUsageBasedPrice?.stripeId);
if (subscriptionItem) {
// Stripe submission is handled by the meter-based reporter in
// `apps/worker/src/jobs/ai-cost-stripe-report.ts`; this path only
// keeps local bookkeeping for tenant-facing usage history.
await createTenantSubscriptionUsageRecord({
tenantSubscriptionProductPriceId: price.id,
timestamp: Math.floor(Date.now() / 1000),
quantity: 1,
stripeSubscriptionItemId: subscriptionItem.id,
});
}
await createTenantSubscriptionUsageRecord({
tenantId,
tenantSubscriptionId: tenantSubscription.id,
tenantSubscriptionProductPriceId: price.id,
metricCode: unit,
timestamp: Math.floor(Date.now() / 1000),
quantity: 1,
billingProviderSubscriptionItemId: null,
});
}
})
);
@@ -454,40 +409,11 @@ export async function persistCheckoutSessionStatus({
fromUserId?: string | null;
fromTenantId?: string | null;
}) {
const existingCheckoutSession = await getCheckoutSessionStatus(id);
if (!existingCheckoutSession) {
const stripeCheckoutSession = await getStripeSession(id);
if (stripeCheckoutSession) {
const session = await createCheckoutSessionStatus({
id: stripeCheckoutSession.id,
email: stripeCheckoutSession.customer_details?.email ?? "",
fromUrl,
fromUserId,
fromTenantId,
});
if (!session.fromUserId && !session.fromTenantId) {
const sessionResponse = await getAcquiredItemsFromCheckoutSession(session.id);
if (sessionResponse && sessionResponse.products.length > 0) {
const mailTranslator = await getMailTranslatorFromRequest(request);
await sendEmail({
request,
to: session.email,
alias: "account-setup",
...EmailTemplates.ACCOUNT_SETUP_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: {
email: session.email,
plan: sessionResponse.products[0].title,
action_url: `${getBaseURL(request)}/pricing/${session.id}/success`,
},
t: mailTranslator.t,
locale: mailTranslator.locale,
}),
});
}
}
}
}
void request;
void id;
void fromUrl;
void fromUserId;
void fromTenantId;
}
export async function getMrr(currency: string) {
@@ -545,8 +471,8 @@ export function convertToCurrency({ from, price, to }: { from: string; price: nu
/**
* Invalidate the cached subscription for a single tenant. Prefer this over
* `clearAllSubscriptionsCache` whenever the change is tenant-scoped (e.g.
* Stripe webhooks) so we don't thrash every other tenant's cache entry.
* `clearAllSubscriptionsCache` whenever the change is tenant-scoped so we
* don't thrash every other tenant's cache entry.
*
* Publishes a cross-replica invalidation on the `cache:subscription:invalidate`
* channel via the two-tier cache so peer web replicas drop their L1 too.
@@ -587,9 +513,6 @@ export async function cancelTenantSubscription(
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (!tenantSubscriptionProduct.stripeSubscriptionId) {
return;
}
const user = userId ? await getUser(userId) : null;
const tenant = await getTenant(tenantId);
if (user && tenant) {
@@ -609,10 +532,8 @@ export async function cancelTenantSubscription(
} satisfies SubscriptionCancelledDto,
});
}
await cancelStripeSubscription(tenantSubscriptionProduct?.stripeSubscriptionId);
const stripeSubscription = await getStripeSubscription(tenantSubscriptionProduct.stripeSubscriptionId);
await cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: stripeSubscription?.items.data[0]?.current_period_end ? new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000) : new Date(),
endsAt: new Date(),
});
}
@@ -1,11 +1,11 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("@toolctrl/db/subscriptions.server", () => ({
vi.mock("@hivegrid/db/subscriptions.server", () => ({
getTenantSubscription: vi.fn(),
}));
vi.mock("@toolctrl/queue", () => ({
vi.mock("@hivegrid/queue", () => ({
setTenantPlanLookup: vi.fn(),
}));
@@ -21,8 +21,8 @@ vi.mock("~/utils/logger.server", () => ({
}),
}));
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import { setTenantPlanLookup } from "@toolctrl/queue";
import { getTenantSubscription } from "@hivegrid/db/subscriptions.server";
import { setTenantPlanLookup } from "@hivegrid/queue";
import { getSubscriptionCache } from "./subscriptionCache.server";
import {
__resetTenantPlanLookupForTests,
@@ -19,10 +19,10 @@
* ```
* Call once during web boot — idempotent.
*/
import type { TenantPlanIdentifier } from "@toolctrl/queue";
import { setTenantPlanLookup } from "@toolctrl/queue";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import type { TenantPlanIdentifier } from "@hivegrid/queue";
import { setTenantPlanLookup } from "@hivegrid/queue";
import type { TenantSubscriptionWithDetails } from "@hivegrid/db/subscriptions.server";
import { getTenantSubscription } from "@hivegrid/db/subscriptions.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import { createScopedLogger } from "~/utils/logger.server";
@@ -5,7 +5,7 @@ import UrlUtils from "../../app/UrlUtils";
import { getHostRoutingContextFromRequest } from "../../app/HostRouting.server";
import { isWebRoutePath } from "../../app/PublicRouteSegments";
import { cachified, clearCacheKey } from "../../cache.server";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
export type TenantResolverSource = "app-route-param" | "admin-query-param" | "none" | "invalid-app-route";