Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,38 @@
import { db } from "~/utils/db.server";
export async function getCheckoutSessionStatus(id: string) {
return db.portalCheckoutSessionStatus.findUnique({
where: { id },
});
}
export async function createCheckoutSessionStatus(data: { id: string; portalId: string; email: string; fromUrl: string; fromUserId?: string | null }) {
return db.portalCheckoutSessionStatus.create({
data: {
id: data.id,
portalId: data.portalId,
pending: true,
email: data.email,
fromUrl: data.fromUrl,
fromUserId: data.fromUserId ?? null,
},
});
}
export async function updateCheckoutSessionStatus(
id: string,
data: {
pending: boolean;
createdUserId?: string | null;
}
) {
return db.portalCheckoutSessionStatus.update({
where: {
id,
},
data: {
pending: data.pending,
createdUserId: data.createdUserId ?? null,
},
});
}
@@ -0,0 +1,67 @@
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { db, dbRead } from "~/utils/db.server";
export async function getPortalPages(portalId: string) {
// Public portal page listing — read-only, replica-safe.
return await dbRead.portalPage.findMany({
where: {
portalId,
},
});
}
export async function getPortalPagesByName(portalId: string, name: string) {
// Public portal page lookup by name — read-only, replica-safe.
return await dbRead.portalPage.findUnique({
where: {
portalId_name: {
portalId,
name,
},
},
});
}
export async function createPortalPage(data: { portalId: string; name: string; attributes: JsonPropertiesValuesDto }) {
return await db.portalPage.create({
data: {
portalId: data.portalId,
name: data.name,
attributes: data.attributes,
},
});
}
export async function updatePortalPage(portalId: string, id: string, data: { attributes: JsonPropertiesValuesDto }) {
const result = await db.portalPage.updateMany({
where: {
portalId,
id,
},
data: {
attributes: data.attributes,
},
});
if (result.count !== 1) {
throw new Error("Portal page not found for portal scope.");
}
return await db.portalPage.findFirstOrThrow({
where: {
portalId,
id,
},
});
}
export async function deletePortalPage(portalId: string, id: string) {
const result = await db.portalPage.deleteMany({
where: {
portalId,
id,
},
});
if (result.count !== 1) {
throw new Error("Portal page not found for portal scope.");
}
return result;
}
@@ -0,0 +1,389 @@
import type { PortalSubscriptionFeature, PortalSubscriptionPrice, PortalSubscriptionProduct } from "@toolctrl/db/prisma-browser";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { db } from "~/utils/db.server";
export type PortalSubscriptionPriceWithProduct = PortalSubscriptionPrice & {
subscriptionProduct: PortalSubscriptionProduct;
};
export async function getAllPortalSubscriptionProductsWithUsers(portalId: string): Promise<SubscriptionProductDto[]> {
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: [{ public: "desc" }, { order: "asc" }],
})
.catch(() => {
return [];
});
}
export async function getAllPortalSubscriptionProducts(portalId: string, isPublic?: boolean): Promise<SubscriptionProductDto[]> {
if (isPublic) {
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
active: true,
public: true,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: {
order: "asc",
},
})
.catch(() => {
return [];
});
}
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
active: true,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: {
order: "asc",
},
})
.catch(() => {
return [];
});
}
export async function getPortalSubscriptionProductsInIds(portalId: string, ids: string[]): Promise<SubscriptionProductDto[]> {
return await db.portalSubscriptionProduct.findMany({
where: {
portalId,
id: { in: ids },
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: { order: "asc" },
});
}
export async function getAllPortalSubscriptionFeatures(
portalId: string
): Promise<{ name: string; order: number; title: string; type: number; value: number; accumulate: boolean }[]> {
return await db.portalSubscriptionFeature.findMany({
where: {
portalId,
},
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
});
}
export async function getPortalSubscriptionProduct(portalId: string, id: string): Promise<SubscriptionProductDto | null> {
return await db.portalSubscriptionProduct.findUnique({
where: {
portalId,
id,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
});
}
export async function getPortalSubscriptionProductByStripeId(portalId: string, stripeId: string) {
return await db.portalSubscriptionProduct.findFirst({
where: {
portalId,
stripeId,
},
});
}
export async function getPortalSubscriptionPrices(portalId: string): Promise<PortalSubscriptionPriceWithProduct[]> {
return await db.portalSubscriptionPrice
.findMany({
where: {
portalId,
},
include: {
subscriptionProduct: true,
},
orderBy: [
{
subscriptionProduct: {
order: "asc",
},
},
{
price: "asc",
},
],
})
.catch(() => {
return [];
});
}
export async function getPortalSubscriptionPrice(portalId: string, id: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findUnique({
where: { portalId, id },
include: {
subscriptionProduct: true,
},
})
.catch(() => {
return null;
});
}
export async function getPortalSubscriptionPriceByStripeId(portalId: string, stripeId: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findFirst({
where: { portalId, stripeId },
include: {
subscriptionProduct: true,
},
})
.catch(() => {
return null;
});
}
export async function createPortalSubscriptionProduct(data: {
portalId: string;
stripeId: string;
order: number;
title: string;
model: PricingModel;
description?: string;
badge?: string;
groupTitle?: string;
groupDescription?: string;
active: boolean;
public: boolean;
billingAddressCollection: string;
hasQuantity: boolean;
canBuyAgain: boolean;
}): Promise<PortalSubscriptionProduct> {
return await db.portalSubscriptionProduct.create({
data: {
portalId: data.portalId,
stripeId: data.stripeId,
order: data.order,
title: data.title,
model: data.model,
description: data.description,
badge: data.badge,
groupTitle: data.groupTitle,
groupDescription: data.groupDescription,
active: data.active,
public: data.public,
billingAddressCollection: data.billingAddressCollection,
hasQuantity: data.hasQuantity,
canBuyAgain: data.canBuyAgain,
},
});
}
export async function updatePortalSubscriptionProduct(
portalId: string,
id: string,
data: {
stripeId?: string;
order?: number;
title?: string;
model?: PricingModel;
description?: string | null;
badge?: string | null;
groupTitle?: string | null;
groupDescription?: string | null;
public?: boolean;
billingAddressCollection?: string;
hasQuantity?: boolean;
canBuyAgain?: boolean;
}
): Promise<PortalSubscriptionProduct> {
const result = await db.portalSubscriptionProduct.updateMany({
where: {
id,
portalId,
},
data: {
stripeId: data.stripeId,
order: data.order,
title: data.title,
model: data.model,
description: data.description,
badge: data.badge,
groupTitle: data.groupTitle,
groupDescription: data.groupDescription,
public: data.public,
billingAddressCollection: data.billingAddressCollection,
hasQuantity: data.hasQuantity,
canBuyAgain: data.canBuyAgain,
},
});
if (result.count !== 1) {
throw new Error("Portal subscription product not found");
}
const item = await db.portalSubscriptionProduct.findFirst({ where: { id, portalId } });
if (!item) {
throw new Error("Portal subscription product not found");
}
return item;
}
export async function updatePortalSubscriptionProductStripeId(portalId: string, id: string, data: { stripeId: string }) {
return await db.portalSubscriptionProduct.update({
where: {
portalId,
id,
},
data,
});
}
export async function updatePortalSubscriptionPriceStripeId(portalId: string, id: string, data: { stripeId: string }) {
return await db.portalSubscriptionPrice.update({
where: {
portalId,
id,
},
data,
});
}
export async function createPortalSubscriptionPrice(data: {
portalId: string;
subscriptionProductId: string;
stripeId: string;
type: SubscriptionPriceType;
billingPeriod: SubscriptionBillingPeriod;
price: number;
currency: string;
trialDays: number;
active: boolean;
}): Promise<PortalSubscriptionPrice> {
return await db.portalSubscriptionPrice.create({
data: {
portalId: data.portalId,
subscriptionProductId: data.subscriptionProductId,
stripeId: data.stripeId,
type: data.type,
billingPeriod: data.billingPeriod,
price: data.price,
currency: data.currency,
trialDays: data.trialDays,
active: data.active,
},
});
}
export async function createPortalSubscriptionFeature(
portalId: string,
subscriptionProductId: string,
data: {
order: number;
title: string;
name: string;
type: SubscriptionFeatureLimitType;
value: number;
href?: string | null;
badge?: string | null;
accumulate?: boolean;
}
): Promise<PortalSubscriptionFeature> {
return await db.portalSubscriptionFeature.create({
data: {
portalId,
subscriptionProductId,
order: data.order,
title: data.title,
name: data.name,
type: data.type,
value: data.value,
href: data.href,
badge: data.badge,
accumulate: data.accumulate,
},
});
}
export async function deletePortalSubscriptionProduct(portalId: string, id: string) {
return await db.portalSubscriptionProduct.delete({
where: {
portalId,
id,
},
});
}
export async function deletePortalSubscriptionPrice(portalId: string, id: string) {
return await db.portalSubscriptionPrice.delete({
where: {
portalId,
id,
},
});
}
export async function deletePortalSubscriptionFeatures(portalId: string, subscriptionProductId: string) {
return await db.portalSubscriptionFeature.deleteMany({
where: {
portalId,
subscriptionProductId,
},
});
}
@@ -0,0 +1,254 @@
import {
Prisma,
PortalSubscriptionFeature,
PortalSubscriptionPrice,
PortalSubscriptionProduct,
PortalUserSubscription,
PortalUserSubscriptionProduct,
PortalUserSubscriptionProductPrice,
} from "@toolctrl/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import PortalUserSubscriptionProductModelHelper from "../helpers/PortalUserSubscriptionProductModelHelper";
import PortalSubscriptionServer from "../services/PortalSubscription.server";
export type PortalUserSubscriptionProductWithDetails = PortalUserSubscriptionProduct & {
subscriptionProduct: PortalSubscriptionProduct & { features: PortalSubscriptionFeature[] };
prices: (PortalUserSubscriptionProductPrice & {
subscriptionPrice: PortalSubscriptionPrice | null;
})[];
};
export type PortalUserSubscriptionProductWithTenant = PortalUserSubscriptionProductWithDetails & {
portalUserSubscription: PortalUserSubscription & {
portalUser: { id: string; email: string };
};
};
export async function getAllPortalUserSubscriptionProducts(
portalId: string,
filters?: FiltersDto,
pagination?: { page: number; pageSize: number }
): Promise<{ items: PortalUserSubscriptionProductWithTenant[]; pagination: PaginationDto }> {
let where: Prisma.PortalUserSubscriptionProductWhereInput = {};
const filterPortalUserId = filters?.properties.find((p) => p.name === "portalUserId")?.value;
const filterSubscriptionProductId = filters?.properties.find((p) => p.name === "subscriptionProductId")?.value;
const filterStatus = filters?.properties.find((p) => p.name === "status")?.value;
where = {
subscriptionProductId: filterSubscriptionProductId ? { equals: filterSubscriptionProductId } : undefined,
portalUserSubscription: {
portalUserId: filterPortalUserId ? { equals: filterPortalUserId } : undefined,
},
};
if (filterStatus === "active") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
};
} else if (filterStatus === "ended") {
where = {
...where,
endsAt: { lt: new Date(), not: null },
};
} else if (filterStatus === "active-cancelled") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
cancelledAt: { not: null },
};
} else if (filterStatus === "active-not-cancelled") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
cancelledAt: null,
};
}
const items = await db.portalUserSubscriptionProduct.findMany({
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
take: pagination ? pagination?.pageSize : undefined,
where: {
portalId,
...where,
},
include: {
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
},
orderBy: {
createdAt: "desc",
},
});
const totalItems = await db.portalUserSubscriptionProduct.count({
where,
});
return {
items,
pagination: {
page: pagination?.page ?? 1,
pageSize: pagination?.pageSize ?? 10,
totalItems,
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? 10)),
},
};
}
export async function getPortalUserSubscriptionProduct(
portalId: string,
portalUserId: string,
subscriptionProductId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
portalUserSubscription: { portalUserId },
subscriptionProductId,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function getPortalUserSubscriptionProductById(portalId: string, id: string): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findUnique({
where: {
portalId,
id,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function getPortalUserSubscriptionProductByStripeSubscriptionId(
portalId: string,
stripeSubscriptionId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
stripeSubscriptionId,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function addPortalUserSubscriptionProduct(data: {
portalId: string;
portalUserSubscriptionId: string;
subscriptionProductId: string;
stripeSubscriptionId?: string;
quantity?: number;
fromCheckoutSessionId?: string | null;
prices: {
subscriptionPriceId?: string;
}[];
}) {
return await db.portalUserSubscriptionProduct
.create({
data: {
portalId: data.portalId,
portalUserSubscriptionId: data.portalUserSubscriptionId,
subscriptionProductId: data.subscriptionProductId,
stripeSubscriptionId: data.stripeSubscriptionId,
quantity: data.quantity,
fromCheckoutSessionId: data.fromCheckoutSessionId,
endsAt: null,
cancelledAt: null,
prices: {
create: data.prices.map((price) => ({
portalId: data.portalId,
subscriptionPriceId: price.subscriptionPriceId,
})),
},
},
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
return item;
});
}
export async function updatePortalUserSubscriptionProduct(
portalId: string,
id: string,
data: {
quantity?: number;
cancelledAt?: Date | null;
endsAt?: Date | null;
}
) {
return await db.portalUserSubscriptionProduct
.update({
where: { portalId, id },
data,
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
return item;
});
}
export async function cancelPortalUserSubscriptionProduct(
portalId: string,
id: string,
data: {
cancelledAt: Date | null;
endsAt: Date | null;
}
) {
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
return await db.portalUserSubscriptionProduct
.update({
where: { portalId, id },
data: {
cancelledAt: data.cancelledAt,
endsAt: data.endsAt,
},
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
});
}
@@ -0,0 +1,116 @@
import { PortalUserSubscription } from "@toolctrl/db/prisma-browser";
import { clearCacheKey } from "~/utils/cache.server";
import { PortalUserSubscriptionProductWithDetails } from "./portalUserSubscriptionProducts.db.server";
import { db } from "~/utils/db.server";
import PortalUserSubscriptionProductModelHelper from "../helpers/PortalUserSubscriptionProductModelHelper";
export type PortalUserSubscriptionWithDetails = PortalUserSubscription & {
products: PortalUserSubscriptionProductWithDetails[];
};
export async function getOrPersistPortalUserSubscription(portalId: string, portalUserId: string): Promise<PortalUserSubscriptionWithDetails> {
const subscription = await db.portalUserSubscription.findUnique({
where: {
portalId,
portalUserId,
},
include: {
products: {
include: PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
if (!subscription) {
return await createPortalUserSubscription(portalId, portalUserId, "");
}
return subscription;
}
export async function getPortalUserSubscription(portalId: string, portalUserId: string): Promise<PortalUserSubscriptionWithDetails | null> {
return await db.portalUserSubscription.findUnique({
where: {
portalId,
portalUserId,
},
include: {
products: {
include: PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
}
export async function getPortalUserSubscriptions(portalId: string): Promise<PortalUserSubscriptionWithDetails[]> {
return await db.portalUserSubscription.findMany({
where: {
portalId,
},
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
},
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
}
export async function createPortalUserSubscription(portalId: string, portalUserId: string, stripeCustomerId: string) {
return await db.portalUserSubscription
.create({
data: {
portalId,
portalUserId,
stripeCustomerId,
},
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
},
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${portalId}:${portalUserId}`);
return item;
});
}
export async function updatePortalUserSubscriptionCustomerId(portalId: string, portalUserId: string, data: { stripeCustomerId: string }) {
return await db.portalUserSubscription
.update({
where: {
portalId,
portalUserId,
},
data,
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${portalId}:${portalUserId}`);
return item;
});
}
@@ -0,0 +1,194 @@
import { db } from "~/utils/db.server";
import { PortalUserDto } from "../dtos/PortalUserDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
export async function getPortalUserById(portalId: string, id: string): Promise<PortalUserDto | null> {
return await cachified({
key: `portalUser:${portalId}:${id}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portalUser.findFirst({
where: {
portalId,
id,
},
select: {
id: true,
portalId: true,
createdAt: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
});
},
});
}
export async function getPortalUserByEmail(portalId: string, email: string): Promise<PortalUserDto | null> {
return await cachified({
key: `portalUserByEmail:${portalId}:${email}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portalUser.findUnique({
where: {
portalId_email: {
portalId,
email,
},
},
select: {
id: true,
portalId: true,
createdAt: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
});
},
});
}
export async function getPortalUsers(portalId: string): Promise<PortalUserDto[]> {
return await db.portalUser.findMany({
where: {
portalId,
},
select: {
id: true,
createdAt: true,
portalId: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
orderBy: {
createdAt: "desc",
},
});
}
export async function createPortalUser(data: {
tenantId: string | null;
portalId: string;
email: string;
passwordHash: string;
firstName: string;
lastName: string;
avatar: string | null;
}) {
return await db.portalUser.create({
data: {
tenantId: data.tenantId,
portalId: data.portalId,
email: data.email,
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
avatar: data.avatar,
},
});
}
export async function updatePortalUser(
portalId: string,
id: string,
data: {
email?: string;
passwordHash?: string;
firstName?: string;
lastName?: string;
avatar?: string | null;
}
) {
const before = await db.portalUser.findFirst({
where: {
portalId,
id,
},
select: {
email: true,
},
});
if (!before) {
throw new Error("Portal user not found for portal scope.");
}
const result = await db.portalUser.updateMany({
where: {
portalId,
id,
},
data: {
email: data.email,
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
avatar: data.avatar,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
const item = await db.portalUser.findFirstOrThrow({
where: {
portalId,
id,
},
});
clearCacheKey(`portalUser:${portalId}:${id}`);
clearCacheKey(`portalUserByEmail:${portalId}:${before.email}`);
clearCacheKey(`portalUserByEmail:${portalId}:${item.email}`);
return item;
}
export async function deletePortalUser(portalId: string, id: string) {
const result = await db.portalUser.deleteMany({
where: {
portalId,
id,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
clearCacheKey(`portalUser:${portalId}:${id}`);
return result;
}
export async function countPortalUsersByTenantId(tenantId: string | null): Promise<number> {
return await db.portalUser.count({
where: {
tenantId,
},
});
}
export async function getPortalUserPasswordHash(id: string): Promise<string | null> {
const user = await db.portalUser.findUnique({
where: {
id,
},
select: {
passwordHash: true,
},
});
return user?.passwordHash ?? null;
}
export async function updatePortalUserPassword(portalId: string, id: string, data: { passwordHash: string }) {
const result = await db.portalUser.updateMany({
where: { portalId, id },
data: {
passwordHash: data.passwordHash,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
clearCacheKey(`portalUser:${portalId}:${id}`);
return result;
}
@@ -0,0 +1,29 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "portals.db.server.ts"), "utf8");
describe("portal db cache invalidation", () => {
test("clears both previous and updated domain cache keys when portals change", () => {
expect(source).toContain("clearCacheKey(`portalByDomain:${before.domain}`)");
expect(source).toContain("clearCacheKey(`portalByDomain:${item.domain}`)");
});
});
describe("portal db tenant scope", () => {
test("updates portals through the portal tenant scope", () => {
expect(source).toContain("db.portal.updateMany");
expect(source).toContain("where: { id: before.id, tenantId: before.tenantId }");
expect(source).toContain('throw new Error("Portal not found for tenant scope.")');
});
test("keeps tenant delete and admin delete boundaries separate", () => {
expect(source).toContain("export async function deletePortal({ id, tenantId }: { id: string; tenantId: string | null })");
expect(source).toContain("return deletePortalWithScope({ id, tenantId });");
expect(source).toContain("export async function adminDeletePortal(id: string)");
expect(source).toContain("return deletePortalWithScope({ id });");
});
});
@@ -0,0 +1,365 @@
import { Prisma, Portal } from "@toolctrl/db/prisma-browser";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { loadWebConfig } from "@toolctrl/config";
import { db, dbRead } from "~/utils/db.server";
import { TenantSimple } from "~/utils/db/tenants.db.server";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
import { createScopedLogger } from "~/utils/logger.server";
const portalsDbLogger = createScopedLogger("portals.db");
export type PortalWithDetails = Portal & {
tenant: TenantSimple | null;
};
export type PortalWithCount = PortalWithDetails & {
_count: {
users: number;
subscriptionProducts: number;
};
};
export async function getAllPortals({
tenantId,
filters,
filterableProperties,
pagination,
}: {
tenantId?: string | null;
filters: FiltersDto;
filterableProperties: FilterablePropertyDto[];
pagination: { pageSize: number; page: number };
}): Promise<{
items: PortalWithCount[];
pagination: PaginationDto;
}> {
const q = filters.query || "";
const AND_filters: Prisma.PortalWhereInput[] = [];
filterableProperties.forEach((filter) => {
const value = filters.properties.find((f) => f.name === filter.name)?.value;
if (value) {
AND_filters.push({
[filter.name]: value === "null" ? null : value,
});
}
});
const OR_filters: Prisma.PortalWhereInput[] = [];
if (q) {
OR_filters.push(
{ subdomain: { contains: q, mode: "insensitive" } },
{ domain: { contains: q, mode: "insensitive" } },
{ title: { contains: q, mode: "insensitive" } }
);
}
const whereFilters: Prisma.PortalWhereInput = {};
if (tenantId !== undefined) {
whereFilters.tenantId = tenantId;
}
if (OR_filters.length > 0) {
whereFilters.OR = OR_filters;
}
if (AND_filters.length > 0) {
whereFilters.AND = AND_filters;
}
// Admin paginated listing of portals — read-only, replica-safe.
const items = await dbRead.portal.findMany({
take: pagination.pageSize,
skip: pagination.pageSize * (pagination.page - 1),
where: whereFilters,
orderBy: {
createdAt: "desc",
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
_count: {
select: {
users: true,
subscriptionProducts: true,
},
},
},
});
const totalItems = await dbRead.portal.count({ where: whereFilters });
return {
items,
pagination: {
page: pagination.page,
pageSize: pagination.pageSize,
totalItems,
totalPages: Math.ceil(totalItems / pagination.pageSize),
},
};
}
export async function getAllTenantPortals({ tenantId }: { tenantId: string | null }): Promise<PortalWithCount[]> {
// Tenant portal listing for admin views — read-only, replica-safe.
return await dbRead.portal.findMany({
where: {
tenantId,
},
orderBy: {
createdAt: "desc",
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
_count: {
select: {
users: true,
subscriptionProducts: true,
},
},
},
});
}
export async function getPortalById(tenantId: string | null, id: string): Promise<PortalWithDetails | null> {
return await db.portal
.findFirstOrThrow({
where: {
tenantId,
OR: [{ id }, { subdomain: id }],
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
})
.catch(() => null);
}
export async function getPortalBySubdomain(subdomain: string): Promise<PortalWithDetails | null> {
return await cachified({
key: `portalBySubdomain:${subdomain}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portal.findUnique({
where: { subdomain },
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
});
},
});
}
export async function getPortalByDomain(domain: string): Promise<PortalWithDetails | null> {
return await cachified({
key: `portalByDomain:${domain}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portal.findUnique({
where: { domain },
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
});
},
});
}
export async function createPortal(data: {
tenantId: string | null;
userId: string;
subdomain: string;
domain: string | null;
title: string;
isPublished: boolean;
stripeAccountId: string | null;
metadata: JsonPropertiesValuesDto;
themeColor: string | null;
themeScheme: string | null;
seoTitle: string | null;
seoDescription: string | null;
seoImage: string | null;
seoThumbnail: string | null;
seoTwitterCreator: string | null;
seoTwitterSite: string | null;
seoKeywords: string | null;
authRequireEmailVerification: boolean;
authRequireOrganization: boolean;
authRequireName: boolean;
analyticsSimpleAnalytics: boolean;
analyticsPlausibleAnalytics: boolean;
analyticsGoogleAnalyticsTrackingId: string | null;
brandingLogo: string | null;
brandingLogoDarkMode: string | null;
brandingIcon: string | null;
brandingIconDarkMode: string | null;
brandingFavicon: string | null;
}) {
return await db.portal
.create({
data: {
tenantId: data.tenantId,
createdByUserId: data.userId,
subdomain: data.subdomain,
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
seoTitle: data.seoTitle,
seoDescription: data.seoDescription,
seoImage: data.seoImage,
seoThumbnail: data.seoThumbnail,
seoTwitterCreator: data.seoTwitterCreator,
seoTwitterSite: data.seoTwitterSite,
seoKeywords: data.seoKeywords,
authRequireEmailVerification: data.authRequireEmailVerification,
authRequireOrganization: data.authRequireOrganization,
authRequireName: data.authRequireName,
analyticsSimpleAnalytics: data.analyticsSimpleAnalytics,
analyticsPlausibleAnalytics: data.analyticsPlausibleAnalytics,
analyticsGoogleAnalyticsTrackingId: data.analyticsGoogleAnalyticsTrackingId,
brandingLogo: data.brandingLogo,
brandingLogoDarkMode: data.brandingLogoDarkMode,
brandingIcon: data.brandingIcon,
brandingIconDarkMode: data.brandingIconDarkMode,
brandingFavicon: data.brandingFavicon,
},
})
.then((item) => {
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
return item;
});
}
export async function updatePortal(
before: Portal,
data: {
subdomain?: string;
domain?: string | null;
title?: string;
isPublished?: boolean;
stripeAccountId?: string | null;
metadata?: JsonPropertiesValuesDto;
themeColor?: string | null;
themeScheme?: string | null;
seoTitle?: string | null;
seoDescription?: string | null;
seoImage?: string | null;
seoThumbnail?: string | null;
seoTwitterCreator?: string | null;
seoTwitterSite?: string | null;
seoKeywords?: string | null;
authRequireEmailVerification?: boolean;
authRequireOrganization?: boolean;
authRequireName?: boolean;
analyticsSimpleAnalytics?: boolean;
analyticsPlausibleAnalytics?: boolean;
analyticsGoogleAnalyticsTrackingId?: string | null;
brandingLogo?: string | null;
brandingLogoDarkMode?: string | null;
brandingIcon?: string | null;
brandingIconDarkMode?: string | null;
brandingFavicon?: string | null;
}
) {
const updateResult = await db.portal.updateMany({
where: { id: before.id, tenantId: before.tenantId },
data: {
subdomain: data.subdomain,
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
seoTitle: data.seoTitle,
seoDescription: data.seoDescription,
seoImage: data.seoImage,
seoThumbnail: data.seoThumbnail,
seoTwitterCreator: data.seoTwitterCreator,
seoTwitterSite: data.seoTwitterSite,
seoKeywords: data.seoKeywords,
authRequireEmailVerification: data.authRequireEmailVerification,
authRequireOrganization: data.authRequireOrganization,
authRequireName: data.authRequireName,
analyticsSimpleAnalytics: data.analyticsSimpleAnalytics,
analyticsPlausibleAnalytics: data.analyticsPlausibleAnalytics,
analyticsGoogleAnalyticsTrackingId: data.analyticsGoogleAnalyticsTrackingId,
brandingLogo: data.brandingLogo,
brandingLogoDarkMode: data.brandingLogoDarkMode,
brandingIcon: data.brandingIcon,
brandingIconDarkMode: data.brandingIconDarkMode,
brandingFavicon: data.brandingFavicon,
},
});
if (updateResult.count !== 1) {
throw new Error("Portal not found for tenant scope.");
}
return await db.portal
.findFirstOrThrow({
where: { id: before.id, tenantId: before.tenantId },
})
.then((item) => {
clearCacheKey(`portalBySubdomain:${before.subdomain}`);
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${before.domain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
const portalServerUrl = loadWebConfig().config.portalServer.url;
if (portalServerUrl) {
// post there with subdomain and domain in the body calling /api/cache/clear
fetch(`${portalServerUrl}/api/cache`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
subdomain: item.subdomain,
domain: item.domain,
}),
})
.then(async (response) => {
portalsDbLogger.info({ response: await response.json() }, "Clearing portal cache succeeded");
})
.catch(async (response) => {
portalsDbLogger.error({ response }, "Clearing portal cache failed");
});
}
return item;
});
}
async function deletePortalWithScope(where: Prisma.PortalWhereInput) {
const item = await db.portal.findFirst({ where });
if (!item) {
throw new Error("Portal not found for scope.");
}
const deleteResult = await db.portal.deleteMany({ where: { ...where, id: item.id } });
if (deleteResult.count !== 1) {
throw new Error("Portal not found for scope.");
}
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
await db.analyticsUniqueVisitor.deleteMany({ where: { portalId: item.id } }).catch(() => null);
await db.analyticsPageView.deleteMany({ where: { portalId: item.id } }).catch(() => null);
await db.analyticsEvent.deleteMany({ where: { portalId: item.id } }).catch(() => null);
return item;
}
export async function deletePortal({ id, tenantId }: { id: string; tenantId: string | null }) {
return deletePortalWithScope({ id, tenantId });
}
export async function adminDeletePortal(id: string) {
return deletePortalWithScope({ id });
}
export async function countPortals(): Promise<number> {
// Dashboard count — read-only, replica-safe.
return await dbRead.portalUser.count({});
}