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";
@@ -1,10 +1,10 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@toolctrl/db/kpi.server";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@hivegrid/db/kpi.server";
import { StatChange } from "~/application/dtos/stats/StatChange";
import { getAdminDashboardStats } from "./adminDashboardService";
import { getMrr } from "./.server/subscriptionService";
vi.mock("@toolctrl/db/kpi.server", () => ({
vi.mock("@hivegrid/db/kpi.server", () => ({
getAdminActiveUserKpiCounts: vi.fn(),
getAdminTenantKpiCounts: vi.fn(),
}));
@@ -45,7 +45,7 @@ describe("getAdminDashboardStats", () => {
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledTimes(1);
expect(getAdminActiveUserKpiCounts).toHaveBeenCalledWith({ gte });
expect(getMrr).toHaveBeenCalledTimes(1);
expect(getMrr).toHaveBeenCalledWith("usd");
expect(getMrr).toHaveBeenCalledWith("eur");
expect(stats).toEqual([
{
name: "Translated accounts",
@@ -59,7 +59,7 @@ describe("getAdminDashboardStats", () => {
{
name: "Translated MRR",
hint: "Translated monthly revenue",
stat: "$1,234.50",
stat: "€1,234.50",
previousStat: "7 translated accounts",
},
{
@@ -94,7 +94,7 @@ describe("getAdminDashboardStats", () => {
expect(stats[1]).toMatchObject({
name: "admin.kpi.mrr.name",
hint: "admin.kpi.mrr.hint",
stat: "$0.00",
stat: "€0.00",
previousStat: "admin.kpi.mrr.previousStat",
});
expect(stats[2]).toMatchObject({
@@ -1,4 +1,4 @@
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@toolctrl/db/kpi.server";
import { getAdminActiveUserKpiCounts, getAdminTenantKpiCounts } from "@hivegrid/db/kpi.server";
import { Stat } from "~/application/dtos/stats/Stat";
import currencies from "~/application/pricing/currencies";
import { getStatChangeType } from "../app/DashboardUtils";
@@ -1,51 +0,0 @@
import { Entity } from "@toolctrl/db/prisma-browser";
import { Stat } from "~/application/dtos/stats/Stat";
import { getStatChangeType } from "../app/DashboardUtils";
import { db } from "../db.server";
import { getAllEntities } from "../db/entities/entities.db.server";
import DateUtils from "../shared/DateUtils";
export async function getCustomEntitiesDashboardStats(lastDays: number): Promise<Stat[]> {
const entities = await getAllEntities({ tenantId: null });
const stats = entities.map(async (entity) => {
return await getEntityStat(entity, lastDays);
});
return await Promise.all(stats);
}
async function getEntityStat(entity: Entity, lastDays: number) {
const { added, total } = await getEntityCreatedSince(entity.id, lastDays);
const tenantStat: Stat = {
name: entity.titlePlural,
hint: "",
stat: added.toString(),
previousStat: (total - added).toString(),
change: "+" + added.toString(),
changeType: getStatChangeType(added, total),
};
return tenantStat;
}
async function getEntityCreatedSince(entityId: string, lastDays: number) {
const from = DateUtils.daysFromDate(new Date(), lastDays * -1);
const [added, total] = await Promise.all([
db.row.count({
where: {
entityId,
createdAt: {
gte: from,
},
},
}),
db.row.count({
where: {
entityId,
},
}),
]);
return {
added,
total,
};
}
@@ -1,4 +1,4 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import { Prisma } from "@hivegrid/db/prisma-browser";
export type AdminSettingsSection = "general" | "authentication" | "analytics" | "cookies";
export type AdminSettingsValidationErrors = Record<string, string[]>;
@@ -1,16 +1,16 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@toolctrl/db/accounts.server", () => ({
vi.mock("@hivegrid/db/accounts.server", () => ({
createUniqueLegacyTenantIpAddress: vi.fn(),
findLegacyTenantByIdOrSlug: vi.fn(),
getLegacyTenantMembershipsForUser: vi.fn(),
}));
vi.mock("@toolctrl/db/api-keys.server", () => ({
vi.mock("@hivegrid/db/api-keys.server", () => ({
createLegacyApiKeyLog: vi.fn(),
findLegacyApiKeyByKey: vi.fn(),
setLegacyApiKeyLogStatus: vi.fn(),
}));
vi.mock("@toolctrl/db/users.server", () => ({ findLegacyUserWithoutPasswordById: vi.fn() }));
vi.mock("@hivegrid/db/users.server", () => ({ findLegacyUserWithoutPasswordById: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(),
getPlanFeatureUsage: vi.fn(),
@@ -20,12 +20,11 @@ vi.mock("jsonwebtoken", () => ({ default: { verify: vi.fn() } }));
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({
default: { sendToRoles: vi.fn() },
}));
vi.mock("../stripe.server", () => ({ getOpenInvoices: vi.fn() }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn() }));
vi.mock("./rateLimitService", () => ({ rateLimitByKey: vi.fn() }));
vi.mock("../cache.server", () => ({ cachified: vi.fn() }));
vi.mock("../app/CrossHostUrls", () => ({ absoluteAppPath: vi.fn(() => "https://app.example.com/acme/settings/api/keys") }));
vi.mock("@toolctrl/config", () => ({
vi.mock("@hivegrid/config", () => ({
loadApiConfig: vi.fn(() => ({
ok: true,
config: {
@@ -38,9 +37,9 @@ vi.mock("@toolctrl/config", () => ({
loadRequiredWebConfig: vi.fn(() => ({ apiAccessToken: "service-secret", jwtSecret: "web-jwt-secret", routing: {} })),
}));
import { findLegacyTenantByIdOrSlug } from "@toolctrl/db/accounts.server";
import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus } from "@toolctrl/db/api-keys.server";
import { loadApiConfig } from "@toolctrl/config";
import { findLegacyTenantByIdOrSlug } from "@hivegrid/db/accounts.server";
import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus } from "@hivegrid/db/api-keys.server";
import { loadApiConfig } from "@hivegrid/config";
import { cachified } from "../cache.server";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
@@ -76,7 +75,7 @@ describe("service API access token helpers", () => {
it("redacts sensitive API log query params before persistence", () => {
const request = new Request(
"https://example.com/v1/entities/contact/rows?entity=contact&id=row_1&page=2&token=raw-token&email=person@example.test&next=/dashboard&apiKey=sk_live_secret"
"https://example.com/v1/entities/contact/rows?entity=contact&id=row_1&page=2&token=raw-token&email=person@example.test&next=/dashboard&apiKey=secret_live_value"
);
expect(serializeApiLogSearchParams(request)).toBe(
@@ -3,15 +3,15 @@ import {
createUniqueLegacyTenantIpAddress,
findLegacyTenantByIdOrSlug,
getLegacyTenantMembershipsForUser,
} from "@toolctrl/db/accounts.server";
} from "@hivegrid/db/accounts.server";
import {
createLegacyApiKeyLog,
findLegacyApiKeyByKey,
setLegacyApiKeyLogStatus as setApiKeyLogStatus,
type LegacyApiKeySimple,
} from "@toolctrl/db/api-keys.server";
import type { ApiKeyLog } from "@toolctrl/db/prisma-browser";
import { findLegacyUserWithoutPasswordById } from "@toolctrl/db/users.server";
} from "@hivegrid/db/api-keys.server";
import type { ApiKeyLog } from "@hivegrid/db/prisma-browser";
import { findLegacyUserWithoutPasswordById } from "@hivegrid/db/users.server";
import { Params } from "react-router";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "./.server/subscriptionService";
@@ -19,11 +19,10 @@ import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatur
import { getClientIPAddress } from "../server/IpUtils";
import jwt from "jsonwebtoken";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { getOpenInvoices } from "../stripe.server";
import { getTranslations } from "~/locale/i18next.server";
import { rateLimitByKey } from "./rateLimitService";
import { cachified } from "../cache.server";
import { loadApiConfig, loadRequiredWebConfig } from "@toolctrl/config";
import { loadApiConfig, loadRequiredWebConfig } from "@hivegrid/config";
import { absoluteAppPath } from "../app/CrossHostUrls";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
@@ -268,24 +267,6 @@ export async function validateTenantApiKey(request: Request, params: Params): Pr
});
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
if (tenantSubscription && tenantSubscription.stripeCustomerId) {
const openInvoices = await getOpenInvoices(tenantSubscription.stripeCustomerId);
if (openInvoices.data.length > 0) {
const invoicesDescription = openInvoices.data.map((invoice) => `Invoice #${invoice.number} - ${invoice.total} ${invoice.currency}`).join("\n");
await NotificationService.sendToRoles({
channel: "admin-users",
tenantId: null,
notification: {
message: `${apiKey.tenant.name} (${apiKey.tenant.slug}) API error. You have open invoices: ${invoicesDescription}`,
action: {
url: absoluteAppPath(loadRequiredWebConfig().routing, apiKey.tenant.slug, "settings/api/keys"),
},
},
});
throw await setApiError(request, params, "You have open invoices: " + invoicesDescription, 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
}
}
return {
tenant: apiKey.tenant,
tenantApiKey: {
@@ -1,104 +1,18 @@
import { TFunction } from "i18next";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { Stat } from "~/application/dtos/stats/Stat";
import { getStatChangePercentage, getStatChangeType } from "../app/DashboardUtils";
import { db } from "../db.server";
import { EntitySimple, getAllEntities } from "../db/entities/entities.db.server";
import { TenantSimple } from "../db/tenants.db.server";
import { RowsApi } from "../api/.server/RowsApi";
export async function getAppDashboardStats({
tenant,
gte,
entities,
}: {
t: TFunction;
tenant: TenantSimple | null;
gte: Date | undefined | undefined;
entities?: EntitySimple[];
gte: Date | undefined;
}): Promise<Stat[]> {
// Entity/row-based dashboard stats were produced by the generic entity-builder,
// which has been removed. There are no entity stats to compute anymore.
if (!tenant) {
return [];
}
if (!entities) {
entities = await getAllEntities({ tenantId: tenant.id, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AppOnly] });
}
const promises = entities.map((entity) => getEntityStat(entity, tenant.id, gte));
const stats = await Promise.all(promises);
return stats;
}
export async function getEntityStat(entity: EntitySimple, tenantId: string, gte: Date | undefined) {
const { total, added } = await getRowsCreatedSince(entity.id, tenantId, gte);
const stat: Stat = {
name: entity.titlePlural,
hint: "",
stat: added.toString(),
previousStat: (total - added).toString(),
change: getStatChangePercentage(added, total) + "%",
changeType: getStatChangeType(added, total),
entity: {
slug: entity.slug,
},
};
return stat;
}
async function getRowsCreatedSince(entityId: string, tenantId: string, gte: Date | undefined) {
const [added, total] = await Promise.all([
db.row.count({
where: {
entityId,
tenantId,
createdAt: {
gte,
},
},
}),
db.row.count({
where: {
entityId,
tenantId,
},
}),
]);
return {
added,
total,
};
}
export type EntitySummaryDto = {
order: number;
rowsData: RowsApi.GetRowsData;
};
export async function getEntitySummaries({
entities,
tenantId,
}: {
entities: { name: string; pageSize?: number }[];
tenantId: string | null;
}): Promise<EntitySummaryDto[]> {
const entitySummaries: EntitySummaryDto[] = [];
await Promise.all(
entities.map(async ({ name, pageSize }, idx) => {
const entitySummary = {
order: idx,
rowsData: await RowsApi.getAll({
entity: { name },
tenantId,
pageSize: pageSize || 3,
urlSearchParams: new URLSearchParams({
view: "null",
}),
}),
};
entitySummaries.push(entitySummary);
})
);
return entitySummaries;
return [];
}
@@ -87,11 +87,6 @@ vi.mock("~/modules/events/services/.server/EventsService", () => ({
},
}));
vi.mock("~/utils/stripe.server", () => ({
createStripeCustomer: vi.fn(),
isStripeConfigured: vi.fn(() => false),
}));
vi.mock("~/modules/ipAddress/services/IpAddressService.server", () => ({
default: {
log: vi.fn(async () => undefined),
@@ -6,7 +6,6 @@ import { getAllRoles } from "../db/permissions/roles.db.server";
import { createTenant, createTenantUser, getTenantBySlug } from "../db/tenants.db.server";
import { getUserByEmail, register } from "../db/users.db.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { createStripeCustomer, isStripeConfigured } from "../stripe.server";
import crypto from "crypto";
import { createRegistration, getRegistrationByEmail, updateRegistration } from "../db/registration.db.server";
import { db } from "~/utils/db.server";
@@ -25,9 +24,9 @@ import { validatePassword as validatePolicyPassword } from "~/services/auth/pass
import { verifyLeadToken } from "~/utils/leads/leadToken.server";
import { recordExistingTenantLeadConversion } from "~/utils/leads/convertLead.server";
import { createScopedLogger } from "~/utils/logger.server";
import { resolveCaptchaConfig, verifyCaptchaToken, getSitekey, isCaptchaConfigured } from "@toolctrl/captcha";
import { resolveCaptchaConfig, verifyCaptchaToken, getSecret, getSitekey, isCaptchaConfigured } from "@hivegrid/captcha";
import { validateDesiredTenantSlug } from "./tenantService";
import { seedShkRolesForTenant } from "./shkRoles.server";
import { provisionShkTenantDefaults } from "./.server/akP20OnboardingService";
const authServiceLogger = createScopedLogger("auth-service");
@@ -52,7 +51,7 @@ export type RegistrationData = {
leadId?: string;
leadToken?: string;
leadPlanId?: string;
/** mCaptcha proof-of-work token from the client widget (hidden `mcaptcha__token` field). */
/** Captcha token from the client widget (hidden `cap-token` or `mcaptcha__token` field). */
captchaToken?: string;
};
@@ -67,7 +66,7 @@ export async function getRegistrationFormData(request: Request): Promise<Registr
const leadId = formData.get("leadId")?.toString().trim() || undefined;
const leadToken = formData.get("leadToken")?.toString().trim() || undefined;
const leadPlanId = formData.get("leadPlanId")?.toString().trim() || undefined;
const captchaToken = formData.get("mcaptcha__token")?.toString().trim() || undefined;
const captchaToken = formData.get("cap-token")?.toString().trim() || formData.get("mcaptcha__token")?.toString().trim() || undefined;
const ipError = await IpAddressServiceServer.log(request, {
action: "register",
@@ -114,13 +113,11 @@ export async function validateRegistration({
registrationData,
addToTrialOrFreePlan,
checkEmailVerification = true,
stripeCustomerId,
}: {
request: Request;
registrationData: RegistrationData;
addToTrialOrFreePlan: boolean;
checkEmailVerification?: boolean;
stripeCustomerId?: string;
}) {
const { t } = await getTranslations(request);
const userInfo = await getUserInfo(request);
@@ -130,7 +127,7 @@ export async function validateRegistration({
throw Error(t("account.register.errors.invalidEmail"));
}
// Anti-spam: verify the mCaptcha PoW token for human signups (email/password is
// Anti-spam: verify the captcha token for human signups (email/password is
// the only signup path after EU-Sterilisation removed social OAuth). No-op when
// captcha is unconfigured; verification fails open if the instance is unreachable
// (CAPTCHA_FAIL_OPEN).
@@ -139,8 +136,9 @@ export async function validateRegistration({
const captchaOk = await verifyCaptchaToken({
token: registrationData.captchaToken,
sitekey: getSitekey(captcha, "login"),
secret: captcha.accountSecret,
secret: getSecret(captcha, "login"),
instanceUrl: captcha.instanceUrl,
provider: captcha.provider,
failOpen: captcha.failOpen,
logger: authServiceLogger,
});
@@ -223,7 +221,6 @@ export async function validateRegistration({
company,
firstName,
lastName,
stripeCustomerId,
avatarURL,
locale,
slug,
@@ -345,7 +342,6 @@ interface CreateUserAndTenantDto {
company?: string;
firstName?: string;
lastName?: string;
stripeCustomerId?: string;
avatarURL?: string;
locale?: string;
slug?: string;
@@ -357,20 +353,12 @@ export async function createUserAndTenant({
company,
firstName,
lastName,
stripeCustomerId,
avatarURL,
locale,
slug,
}: CreateUserAndTenantDto) {
let tenantName = company ?? email.split("@")[0];
if (!stripeCustomerId && isStripeConfigured()) {
const stripeCustomer = await createStripeCustomer(email, tenantName);
if (!stripeCustomer) {
throw Error("Could not create Stripe customer");
}
stripeCustomerId = stripeCustomer.id;
}
const tenant = await createTenant({ name: tenantName, subscriptionCustomerId: stripeCustomerId, slug });
const tenant = await createTenant({ name: tenantName, slug });
if (!tenant) {
throw Error("Could not create tenant");
}
@@ -397,12 +385,13 @@ export async function createUserAndTenant({
roles
);
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
// R-P2b — neuen (SHK-)Tenant mit den SHK-Standard-Rollen-Templates bestuecken. Best-effort:
// ein Seed-Fehler darf die Registrierung nicht blockieren (Rollen sind anpassbar/nachseedbar).
await seedShkRolesForTenant(tenant.id).catch((error: unknown) => {
// AK-P20 — new SHK tenants get baseline roles, project pipeline, and first steps.
// Best-effort: provisioning can be re-run later and must not block signup.
const { t } = await getTranslations(request);
await provisionShkTenantDefaults({ tenantId: tenant.id, userId: user.id, t }).catch((error: unknown) => {
authServiceLogger.warn(
{ op: "register.seedShkRoles.failed", tenantId: tenant.id, err: { name: error instanceof Error ? error.name : "Error" } },
"Tenant created but SHK standard roles could not be seeded; they can be re-seeded later."
{ op: "register.provisionShkDefaults.failed", tenantId: tenant.id, err: { name: error instanceof Error ? error.name : "Error" } },
"Tenant created but SHK defaults could not be provisioned; they can be re-run later."
);
});
@@ -61,7 +61,6 @@ vi.mock("~/utils/db/registration.db.server", () => ({
updateRegistration: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: { lead: { findUnique: (...args: unknown[]) => mocks.leadFindUnique(...args) } } }));
vi.mock("~/utils/stripe.server", () => ({ createStripeCustomer: vi.fn(), isStripeConfigured: vi.fn(() => false) }));
vi.mock("~/utils/url.server", () => ({ getAbsoluteUrl: vi.fn(() => "https://example.test") }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/modules/emails/services/TransactionalEmailQueue.server", () => ({ queueTransactionalEmail: vi.fn() }));
@@ -1,6 +1,5 @@
import { describe, expect, test, vi } from "vitest";
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn() }));
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ createPermissions: vi.fn(), getAllPermissions: vi.fn() }));
vi.mock("~/utils/db/permissions/rolePermissions.db.server", () => ({ createRolePermission: vi.fn() }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ createRole: vi.fn(), getAllRoles: vi.fn(), getRoleByName: vi.fn() }));
@@ -1,28 +1,14 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn() }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ createRole: vi.fn(), getAllRoles: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ createUserRoleAssignments: vi.fn() }));
vi.mock("~/utils/db/tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ adminGetAllUsers: vi.fn() }));
vi.mock("~/utils/db.server", () => ({
db: {
role: {
findMany: vi.fn(),
},
permission: {
createMany: vi.fn(),
findMany: vi.fn(),
},
rolePermission: {
createMany: vi.fn(),
},
},
db: {},
}));
vi.mock("~/utils/cache.server", () => ({ clearCacheKey: vi.fn() }));
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getEntityPermissions: vi.fn() }));
vi.mock("@toolctrl/db/permissions-seed.server", async () => {
const actual = await vi.importActual<typeof import("@toolctrl/db/permissions-seed.server")>("@toolctrl/db/permissions-seed.server");
vi.mock("@hivegrid/db/permissions-seed.server", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/db/permissions-seed.server")>("@hivegrid/db/permissions-seed.server");
return {
...actual,
syncDefaultRolesAndPermissions: vi.fn(async () => ({
@@ -34,27 +20,17 @@ vi.mock("@toolctrl/db/permissions-seed.server", async () => {
};
});
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
import { createUserRoleAssignments } from "~/utils/db/permissions/userRoles.db.server";
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
import { adminGetAllUsers } from "~/utils/db/users.db.server";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
import { syncDefaultRolesAndPermissions } from "@toolctrl/db/permissions-seed.server";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { syncDefaultRolesAndPermissions } from "@hivegrid/db/permissions-seed.server";
import { defaultAdminRoles, defaultAppRoles, defaultPermissions, seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent } from "./rolesAndPermissionsService";
const getAllEntitiesMock = vi.mocked(getAllEntities);
const getAllRolesMock = vi.mocked(getAllRoles);
const createUserRoleAssignmentsMock = vi.mocked(createUserRoleAssignments);
const adminGetAllTenantsMock = vi.mocked(adminGetAllTenants);
const adminGetAllUsersMock = vi.mocked(adminGetAllUsers);
const dbMock = vi.mocked(db);
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const getEntityPermissionsMock = vi.mocked(getEntityPermissions);
const syncDefaultRolesAndPermissionsMock = vi.mocked(syncDefaultRolesAndPermissions);
type RoleRow = Awaited<ReturnType<typeof getAllRoles>>[number];
@@ -85,31 +61,6 @@ describe("seedRolesAndPermissions diagnostics", () => {
if (type === "app") return appRoleRows;
return allRoleRows;
});
dbMock.permission.createMany.mockResolvedValue({ count: 3 } as never);
dbMock.permission.findMany.mockResolvedValue([
{ id: "permission-widget-view", name: "app.widget.view" },
{ id: "permission-report-view", name: "app.report.view" },
{ id: "permission-report-read", name: "app.report.read" },
] as never);
dbMock.role.findMany.mockResolvedValue(
[
{ id: "admin-role-super-admin", name: DefaultAdminRoles.SuperAdmin },
{ id: "app-role-super-user", name: DefaultAppRoles.SuperUser },
{ id: "app-role-admin", name: DefaultAppRoles.Admin },
{ id: "app-role-user", name: DefaultAppRoles.User },
] as never
);
dbMock.rolePermission.createMany.mockResolvedValue({ count: 12 } as never);
getAllEntitiesMock.mockResolvedValue([
{ id: "entity-1", type: "widget" } as Awaited<ReturnType<typeof getAllEntities>>[number],
{ id: "entity-2", type: "report" } as Awaited<ReturnType<typeof getAllEntities>>[number],
]);
getEntityPermissionsMock
.mockResolvedValueOnce([{ name: "app.widget.view", description: "View widgets" }])
.mockResolvedValueOnce([
{ name: "app.report.view", description: "View reports" },
{ name: "app.report.read", description: "Read reports" },
]);
adminGetAllUsersMock.mockResolvedValue({
items: [
{ id: "admin-user-id", email: "admin@email.com", admin: { userId: "admin-user-id" }, passwordHash: "hashed-password" },
@@ -158,7 +109,7 @@ describe("seedRolesAndPermissions diagnostics", () => {
adminRoleCount: adminRoleRows.length,
appRoleCount: appRoleRows.length,
defaultPermissionCount: defaultPermissions.length,
dynamicEntityPermissionCount: 3,
dynamicEntityPermissionCount: 0,
adminUserAssignmentCount: adminRoleRows.length,
tenantUserAssignmentCount: 2 * appRoleRows.length,
},
@@ -168,46 +119,6 @@ describe("seedRolesAndPermissions diagnostics", () => {
expect(serializedDiagnostics(events)).not.toContain("hashed-password");
expect(serializedDiagnostics(events)).not.toContain("sk_live_secret");
expect(serializedDiagnostics(events)).not.toContain("admin-user-id");
const defaultAppPermissionCount = defaultPermissions.filter((permission) => permission.type === "app").length;
expect(dbMock.permission.createMany).toHaveBeenCalledWith({
data: [
{
order: defaultAppPermissionCount + 3,
name: "app.widget.view",
description: "View widgets",
type: "widget",
isDefault: true,
entityId: null,
},
{
order: defaultAppPermissionCount + 4,
name: "app.report.view",
description: "View reports",
type: "report",
isDefault: true,
entityId: null,
},
{
order: defaultAppPermissionCount + 5,
name: "app.report.read",
description: "Read reports",
type: "report",
isDefault: true,
entityId: null,
},
],
skipDuplicates: true,
});
expect(dbMock.rolePermission.createMany).toHaveBeenCalledWith({
data: expect.arrayContaining([
{ permissionId: "permission-widget-view", roleId: "admin-role-super-admin" },
{ permissionId: "permission-widget-view", roleId: "app-role-super-user" },
{ permissionId: "permission-widget-view", roleId: "app-role-admin" },
{ permissionId: "permission-widget-view", roleId: "app-role-user" },
]),
skipDuplicates: true,
});
expect(clearCacheKeyMock).toHaveBeenCalledWith("permission:app.widget.view");
expect(createUserRoleAssignmentsMock).toHaveBeenCalledWith(
expect.arrayContaining([
{ userId: "admin-user-id", roleId: adminRoleRows[0]?.id, tenantId: null },
@@ -228,7 +139,7 @@ describe("seedRolesAndPermissions diagnostics", () => {
test("emits failure diagnostics and rethrows the original seed error", async () => {
const diagnostics = vi.fn();
const originalError = new Error("seed failed without password token literals");
getAllEntitiesMock.mockRejectedValueOnce(originalError);
adminGetAllUsersMock.mockRejectedValueOnce(originalError);
await expect(seedRolesAndPermissions({ adminEmail: "admin@email.com", diagnostics })).rejects.toBe(originalError);
@@ -1,5 +1,3 @@
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import {
defaultAdminRoleSeeds,
@@ -8,15 +6,12 @@ import {
syncDefaultRolesAndPermissions,
type DefaultPermissionSeed,
type DefaultRoleSeed,
} from "@toolctrl/db/permissions-seed.server";
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
} from "@hivegrid/db/permissions-seed.server";
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
import { createUserRoleAssignments, type UserRoleAssignment } from "~/utils/db/permissions/userRoles.db.server";
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
import { adminGetAllUsers } from "~/utils/db/users.db.server";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
export type CreateRoleDto = DefaultRoleSeed;
export const defaultAdminRoles: CreateRoleDto[] = [...defaultAdminRoleSeeds];
@@ -65,78 +60,6 @@ async function emitRolesAndPermissionsSeedDiagnostic(
await diagnostics?.(event);
}
async function createDynamicEntityPermissions(permissions: { inRoles: string[]; name: string; description: string; type: string; order: number }[]): Promise<void> {
if (permissions.length === 0) {
return;
}
const permissionNames = [...new Set(permissions.map((permission) => permission.name))];
await db.permission.createMany({
data: permissions.map((permission) => ({
order: permission.order,
name: permission.name,
description: permission.description,
type: permission.type,
isDefault: true,
entityId: null,
})),
skipDuplicates: true,
});
permissionNames.forEach((permissionName) => {
clearCacheKey(`permission:${permissionName}`);
});
const createdOrExistingPermissions = await db.permission.findMany({
where: {
name: {
in: permissionNames,
},
},
select: {
id: true,
name: true,
},
});
const permissionByName = new Map(createdOrExistingPermissions.map((permission) => [permission.name, permission]));
const roleNames = [...new Set(permissions.flatMap((permission) => permission.inRoles))];
const roles = await db.role.findMany({
where: {
name: {
in: roleNames,
},
tenantId: null,
},
select: {
id: true,
name: true,
},
});
const roleByName = new Map(roles.map((role) => [role.name, role]));
const rolePermissionData = permissions.flatMap((permission) => {
const createdOrExistingPermission = permissionByName.get(permission.name);
if (!createdOrExistingPermission) {
return [];
}
return permission.inRoles.map((roleName) => {
const role = roleByName.get(roleName);
if (!role) {
throw new Error("Role required: " + roleName);
}
return {
permissionId: createdOrExistingPermission.id,
roleId: role.id,
};
});
});
if (rolePermissionData.length > 0) {
await db.rolePermission.createMany({
data: rolePermissionData,
skipDuplicates: true,
});
}
}
export async function seedRolesAndPermissions(adminEmailOrOptions?: string | SeedRolesAndPermissionsOptions): Promise<void> {
const { adminEmail, diagnostics } = toSeedRolesAndPermissionsOptions(adminEmailOrOptions);
const counts = {
@@ -158,25 +81,6 @@ export async function seedRolesAndPermissions(adminEmailOrOptions?: string | See
const appRoles = await getAllRoles("app");
counts.appRoleCount = appRoles.length;
const entities = await getAllEntities({ tenantId: null, active: true });
const entityPermissionGroups = await Promise.all(
entities.map(async (entity) =>
(await getEntityPermissions(entity)).map((permission) => ({
inRoles: [DefaultAdminRoles.SuperAdmin, DefaultAppRoles.SuperUser, DefaultAppRoles.Admin, DefaultAppRoles.User].map((f) => f.toString()),
name: permission.name as DefaultPermission,
description: permission.description,
type: entity.type,
}))
)
);
const appPermissionCount = defaultPermissions.filter((f) => f.type === "app").length;
const dynamicEntityPermissions = entityPermissionGroups.flat().map((permission, index) => ({
...permission,
order: appPermissionCount + index + 3,
}));
counts.dynamicEntityPermissionCount = dynamicEntityPermissions.length;
await createDynamicEntityPermissions(dynamicEntityPermissions);
const users = (await adminGetAllUsers()).items;
const userRoleAssignments: UserRoleAssignment[] = [];
users
@@ -1,76 +0,0 @@
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { db } from "../db.server";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { createRow, getMaxRowFolio, getRow } from "../db/entities/rows.db.server";
import { createManualRowLog, createRowLog } from "../db/logs.db.server";
export async function getCreateNewRow({ entityName, createdByUserId, tenantId }: { entityName: string; createdByUserId: string; tenantId?: string | null }) {
const entity = await db.entity.findUnique({ where: { name: entityName } });
if (!entity) {
throw new Error("Entity required: " + entityName);
}
let folio = 1;
const maxFolio = await getMaxRowFolio({ tenantId: tenantId ?? null, entityId: entity.id });
if (maxFolio && maxFolio._max.folio !== null) {
folio = maxFolio._max.folio + 1;
}
return {
row: {
create: {
entityId: entity.id,
createdByUserId,
tenantId: tenantId ?? null,
folio,
},
},
};
}
export async function createNewRowWithEntity({
entity,
createdByUserId,
tenantId,
request,
nextFolio,
}: {
entity: EntityWithDetails;
createdByUserId: string | null;
tenantId?: string | null;
request?: Request;
nextFolio?: number;
}) {
const row = await createRow({
entity,
data: {
createdByUserId,
tenantId: tenantId ?? null,
properties: {},
dynamicProperties: [],
},
nextFolio,
});
const item = await getRow({ entityId: entity.id, id: row!.id, tenantId: tenantId ?? null });
if (row) {
if (request) {
await createRowLog(request, {
tenantId: tenantId ?? null,
createdByUserId,
action: DefaultLogActions.Created,
entity,
item,
});
} else {
await createManualRowLog(
{
tenantId: tenantId ?? null,
createdByUserId,
action: DefaultLogActions.Created + " " + entity.title,
entity,
item,
},
request
);
}
}
return row;
}
@@ -1,18 +0,0 @@
import { SetupItem } from "~/application/dtos/setup/SetupItem";
import { getAllSubscriptionProducts } from "../db/subscriptionProducts.db.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { t as i18nT } from "i18next";
export async function getSetupSteps(): Promise<SetupItem[]> {
return [await getPricingStep()];
}
async function getPricingStep(): Promise<SetupItem> {
let items = await getAllSubscriptionProducts();
return Promise.resolve({
title: i18nT("setup.pricing.title"),
description: i18nT("setup.pricing.description"),
completed: items.length > 0,
path: adminPath("settings/pricing", { mode: "host-aware" }),
});
}
@@ -6,11 +6,14 @@ const dbMock = vi.hoisted(() => ({
rolePermission: { findFirst: vi.fn(), create: vi.fn() },
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
const configMock = vi.hoisted(() => ({ nodeEnv: "test" }));
vi.mock("@hivegrid/config", () => ({ loadWebConfig: () => ({ config: { nodeEnv: configMock.nodeEnv } }) }));
import { SHK_ROLE_NAMES, SHK_ROLE_SEEDS, seedShkRolesForTenant } from "./shkRoles.server";
import { SHK_ROLE_NAMES, SHK_ROLE_SEEDS, seedShkRolesForTenant, shouldSeedShkRoles } from "./shkRoles.server";
beforeEach(() => {
vi.clearAllMocks();
configMock.nodeEnv = "test";
});
describe("SHK role definitions", () => {
@@ -26,6 +29,36 @@ describe("SHK role definitions", () => {
});
});
describe("shouldSeedShkRoles (production seeds admin-only)", () => {
it("skips the SHK seeds on production by default (David's D-P2 decision)", () => {
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({})).toBe(false);
});
it("seeds on staging (SENTRY_ENVIRONMENT wins over NODE_ENV=production) and local dev", () => {
// Staging containers run NODE_ENV=production — the deploy-scoped env var decides.
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({ SENTRY_ENVIRONMENT: "staging" })).toBe(true);
configMock.nodeEnv = "development";
expect(shouldSeedShkRoles({})).toBe(true);
});
it("lets SEED_SHK_ROLES override in both directions", () => {
configMock.nodeEnv = "production";
expect(shouldSeedShkRoles({ SEED_SHK_ROLES: "true" })).toBe(true);
configMock.nodeEnv = "test";
expect(shouldSeedShkRoles({ SEED_SHK_ROLES: "false" })).toBe(false);
});
it("makes seedShkRolesForTenant a no-op on production", async () => {
configMock.nodeEnv = "production";
const result = await seedShkRolesForTenant("t1");
expect(result).toEqual({ createdRoles: 0 });
expect(dbMock.permission.findMany).not.toHaveBeenCalled();
expect(dbMock.role.create).not.toHaveBeenCalled();
});
});
describe("seedShkRolesForTenant", () => {
it("creates the missing roles as tenant-scoped app roles and links resolvable permissions", async () => {
dbMock.permission.findMany.mockResolvedValue([{ id: "perm_dash", name: "app.dashboard.view" }]);
@@ -1,3 +1,4 @@
import { loadWebConfig } from "@hivegrid/config";
import { db } from "~/utils/db.server";
// R-P2b — SHK-Standard-Rollen (vom Partner genannt). PROVISORISCH/ANPASSBAR: datengetrieben, per
@@ -78,9 +79,26 @@ export const SHK_ROLE_SEEDS: readonly ShkRoleSeed[] = [
export const SHK_ROLE_NAMES: readonly string[] = SHK_ROLE_SEEDS.map((role) => role.name);
// Product decision 2026-07-07 (Akeshan, resolving the R-P2b seed-vs-design conflict): on PRODUCTION a
// fresh tenant starts with the admin system role only (David's validated D-P2 decision); the 6 SHK seed
// roles stay a staging/dev testing convenience. SEED_SHK_ROLES=true|false overrides either way in case
// the partner wants the seeds in production after all. Environment detection: NODE_ENV is "production"
// on staging containers too, so the deploy-scoped SENTRY_ENVIRONMENT (staging|production, estate
// standard §1) decides first and nodeEnv only covers local dev/test.
export function shouldSeedShkRoles(env: Record<string, string | undefined> = process.env): boolean {
if (env.SEED_SHK_ROLES === "true") return true;
if (env.SEED_SHK_ROLES === "false") return false;
const environment = env.SENTRY_ENVIRONMENT ?? loadWebConfig().config.nodeEnv;
return environment !== "production";
}
// Seedt die SHK-Rollen als App-Rollen eines Tenants (idempotent). Setzt fehlende Rollen + ihre
// vorhandenen Permission-Verknuepfungen auf; bestehende bleiben unberuehrt (anpassbar im Editor).
// Auf Produktion no-op (s. shouldSeedShkRoles) — dort startet ein Tenant nur mit der Admin-Systemrolle.
export async function seedShkRolesForTenant(tenantId: string): Promise<{ createdRoles: number }> {
if (!shouldSeedShkRoles()) {
return { createdRoles: 0 };
}
const wantedKeys = [...new Set(SHK_ROLE_SEEDS.flatMap((role) => role.permissionKeys))];
const permissions = await db.permission.findMany({ where: { name: { in: wantedKeys } }, select: { id: true, name: true } });
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
@@ -11,7 +11,6 @@ import { db } from "../db.server";
vi.mock("../db.server", () => ({ db: { tenant: { count: vi.fn() } } }));
const countMock = vi.mocked(db.tenant.count);
vi.mock("../stripe.server", () => ({ deleteStripeCustomer: vi.fn() }));
vi.mock("../db/tenants.db.server", () => ({ deleteTenant: vi.fn() }));
vi.mock("../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn() }));
vi.mock("./.server/subscriptionService", () => ({ cancelTenantSubscription: vi.fn() }));
@@ -3,7 +3,6 @@ import { reservedTenantChildRouteSlugs, reservedTenantRouteSlugs } from "../app/
import { db } from "../db.server";
import { deleteTenant } from "../db/tenants.db.server";
import { getTenantSubscription } from "../db/tenantSubscriptions.db.server";
import { deleteStripeCustomer } from "../stripe.server";
import { TFunction } from "i18next";
import { cancelTenantSubscription } from "./.server/subscriptionService";
@@ -55,11 +54,7 @@ export function validateDesiredTenantSlug(input: string): TenantSlugValidation {
}
export async function deleteAndCancelTenant({ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }) {
const tenantSubscription = await getTenantSubscription(tenantId);
await cancelAllTenantPlans({ t, tenantId, userId });
if (tenantSubscription?.stripeCustomerId) {
await deleteStripeCustomer(tenantSubscription?.stripeCustomerId);
}
return await deleteTenant(tenantId);
}
@@ -6,8 +6,10 @@ import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const dbMock = vi.hoisted(() => ({
tenantUser: { findFirst: vi.fn(), update: vi.fn(), count: vi.fn() },
group: { updateMany: vi.fn() },
$transaction: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
vi.mock("~/services/search/searchIndexProjection.server", () => ({ publishTenantUserSearchUpsert: vi.fn(async () => undefined) }));
import { deactivateTenantUser, reactivateTenantUser } from "./tenantUserLifecycle.server";
@@ -15,6 +17,7 @@ beforeEach(() => {
vi.clearAllMocks();
dbMock.tenantUser.update.mockResolvedValue({});
dbMock.group.updateMany.mockResolvedValue({ count: 0 });
dbMock.$transaction.mockImplementation(async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
});
describe("deactivateTenantUser", () => {
@@ -41,7 +44,7 @@ describe("deactivateTenantUser", () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", type: TenantUserType.OWNER, status: TenantUserStatus.ACTIVE });
dbMock.tenantUser.count.mockResolvedValue(1);
expect(await deactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: true });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith({ where: { id: "m1" }, data: { status: TenantUserStatus.INACTIVE } });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "m1" }, data: { status: TenantUserStatus.INACTIVE } }));
});
it("deactivates a plain member without an admin-count check", async () => {
@@ -68,7 +71,7 @@ describe("reactivateTenantUser", () => {
it("reactivates an inactive member", async () => {
dbMock.tenantUser.findFirst.mockResolvedValue({ id: "m1", status: TenantUserStatus.INACTIVE });
expect(await reactivateTenantUser({ tenantId: "t1", targetUserId: "u1" })).toEqual({ ok: true });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith({ where: { id: "m1" }, data: { status: TenantUserStatus.ACTIVE } });
expect(dbMock.tenantUser.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "m1" }, data: { status: TenantUserStatus.ACTIVE } }));
});
it("is idempotent for an already active member", async () => {
@@ -1,11 +1,31 @@
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { publishTenantUserSearchUpsert } from "~/services/search/searchIndexProjection.server";
import { db } from "~/utils/db.server";
// R-P2b — User-Lifecycle: Soft-Deaktivierung mit Last-Admin-Guard + optionalem Ownership-Reassign.
// Ein Tenant muss IMMER mindestens einen aktiven Owner/Admin behalten, sonst waere er handlungsunfaehig.
const PRIVILEGED_TYPES = [TenantUserType.OWNER, TenantUserType.ADMIN];
const tenantUserSearchInclude = {
user: {
select: {
id: true,
createdAt: true,
email: true,
firstName: true,
lastName: true,
active: true,
admin: { select: { userId: true } },
logs: {
where: { action: "Login" },
orderBy: { createdAt: "desc" },
take: 1,
select: { createdAt: true },
},
},
},
} as const;
export type DeactivateTenantUserResult =
| { ok: true }
@@ -70,7 +90,10 @@ export async function deactivateTenantUser({
if (reassignToUserId && reassignToUserId !== targetUserId) {
await reassignTenantUserOwnership({ tenantId, fromUserId: targetUserId, toUserId: reassignToUserId });
}
await db.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.INACTIVE } });
await db.$transaction(async (tx) => {
const updated = await tx.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.INACTIVE }, include: tenantUserSearchInclude });
await publishTenantUserSearchUpsert(tx, updated);
});
return { ok: true };
}
@@ -91,6 +114,9 @@ export async function reactivateTenantUser({
if (member.status === TenantUserStatus.ACTIVE) {
return { ok: false, reason: "already-active" };
}
await db.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.ACTIVE } });
await db.$transaction(async (tx) => {
const updated = await tx.tenantUser.update({ where: { id: member.id }, data: { status: TenantUserStatus.ACTIVE }, include: tenantUserSearchInclude });
await publishTenantUserSearchUpsert(tx, updated);
});
return { ok: true };
}
@@ -45,9 +45,9 @@ describe("deleteUserWithItsTenants", () => {
});
it("does not delete the user if tenant cancellation fails", async () => {
vi.mocked(deleteAndCancelTenant).mockRejectedValueOnce(new Error("stripe unavailable") as never);
vi.mocked(deleteAndCancelTenant).mockRejectedValueOnce(new Error("billing unavailable") as never);
await expect(deleteUserWithItsTenants("user_1")).rejects.toThrow("stripe unavailable");
await expect(deleteUserWithItsTenants("user_1")).rejects.toThrow("billing unavailable");
expect(deleteUser).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,4 @@
import { Tenant, Role } from "@toolctrl/db/prisma-browser";
import { Tenant, Role } from "@hivegrid/db/prisma-browser";
import { getMyTenants, getTenantWithUsers } from "../db/tenants.db.server";
import { UserWithoutPassword, deleteUser } from "../db/users.db.server";
import { deleteAndCancelTenant } from "./tenantService";