Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,38 +0,0 @@
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,137 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { readPortalEmailTemplateAdminSnapshot, upsertVisiblePortalEmailTemplate } from "./portalEmailTemplates.db.server";
function transaction() {
return {
portal: { findUnique: vi.fn() },
portalStageVisibility: { findMany: vi.fn(), findFirst: vi.fn() },
portalEmailTemplate: { findMany: vi.fn(), findUnique: vi.fn(), upsert: vi.fn() },
};
}
describe("portal email template DB service", () => {
let tx: ReturnType<typeof transaction>;
beforeEach(() => {
tx = transaction();
});
it("returns an empty admin snapshot when the tenant has no portal", async () => {
tx.portal.findUnique.mockResolvedValue(null);
await expect(readPortalEmailTemplateAdminSnapshot(tx as never, { tenantId: "tenant_1", locale: "de" })).resolves.toEqual({
portalId: null,
stages: [],
templates: [],
});
expect(tx.portalStageVisibility.findMany).not.toHaveBeenCalled();
expect(tx.portalEmailTemplate.findMany).not.toHaveBeenCalled();
});
it("loads only visible active stages in pipeline order and uses customer labels", async () => {
tx.portal.findUnique.mockResolvedValue({ id: "portal_1" });
tx.portalStageVisibility.findMany.mockResolvedValue([
{
stageId: "stage_2",
customerLabel: "Montage",
stage: { name: "Internal assembly", position: 2, pipeline: { position: 1 } },
},
{
stageId: "stage_1",
customerLabel: null,
stage: { name: "Angebot", position: 1, pipeline: { position: 1 } },
},
]);
tx.portalEmailTemplate.findMany.mockResolvedValue([{ id: "template_1", stageId: "stage_1", subject: "Status", body: "Hallo", active: true }]);
const snapshot = await readPortalEmailTemplateAdminSnapshot(tx as never, {
tenantId: "tenant_1",
locale: "de",
});
expect(snapshot).toEqual({
portalId: "portal_1",
stages: [
{ id: "stage_1", label: "Angebot", visible: true },
{ id: "stage_2", label: "Montage", visible: true },
],
templates: [{ id: "template_1", stageId: "stage_1", subject: "Status", body: "Hallo", active: true }],
});
expect(tx.portalStageVisibility.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ tenantId: "tenant_1", portalId: "portal_1", visible: true }),
})
);
expect(tx.portalEmailTemplate.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
tenantId: "tenant_1",
portalId: "portal_1",
locale: "de",
stageId: { in: ["stage_1", "stage_2"] },
}),
})
);
});
it("keeps repeated saves idempotent for the portal-stage-locale key", async () => {
const existing = { id: "template_1", stageId: "stage_1", subject: "Status", body: "Hallo", active: true };
tx.portal.findUnique.mockResolvedValue({ id: "portal_1" });
tx.portalStageVisibility.findFirst.mockResolvedValue({ customerLabel: "Angebot", stage: { name: "Offer" } });
tx.portalEmailTemplate.findUnique.mockResolvedValue(existing);
await expect(
upsertVisiblePortalEmailTemplate(tx as never, {
tenantId: "tenant_1",
stageId: "stage_1",
locale: "de",
subject: "Status",
body: "Hallo",
active: true,
})
).resolves.toEqual({
template: existing,
portalId: "portal_1",
stageLabel: "Angebot",
created: false,
changed: false,
});
expect(tx.portalEmailTemplate.findUnique).toHaveBeenCalledWith(
expect.objectContaining({
where: { portalId_stageId_locale: { portalId: "portal_1", stageId: "stage_1", locale: "de" } },
})
);
expect(tx.portalEmailTemplate.upsert).not.toHaveBeenCalled();
});
it("upserts a changed template only after proving the stage is visible", async () => {
tx.portal.findUnique.mockResolvedValue({ id: "portal_1" });
tx.portalStageVisibility.findFirst.mockResolvedValue({ customerLabel: null, stage: { name: "Angebot" } });
tx.portalEmailTemplate.findUnique.mockResolvedValue(null);
tx.portalEmailTemplate.upsert.mockResolvedValue({
id: "template_1",
stageId: "stage_1",
subject: "Neuer Status",
body: "Hallo",
active: true,
});
const result = await upsertVisiblePortalEmailTemplate(tx as never, {
tenantId: "tenant_1",
stageId: "stage_1",
locale: "de",
subject: "Neuer Status",
body: "Hallo",
active: true,
});
expect(result).toMatchObject({ portalId: "portal_1", stageLabel: "Angebot", created: true, changed: true });
expect(tx.portalEmailTemplate.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { portalId_stageId_locale: { portalId: "portal_1", stageId: "stage_1", locale: "de" } },
create: expect.objectContaining({ tenantId: "tenant_1", portalId: "portal_1", stageId: "stage_1", locale: "de" }),
})
);
});
});
@@ -0,0 +1,152 @@
import type { Prisma } from "@hivegrid/db/prisma-browser";
export type PortalEmailTemplateAdminStage = {
readonly id: string;
readonly label: string;
readonly visible: true;
};
export type PortalEmailTemplateAdminRow = {
readonly id: string;
readonly stageId: string;
readonly subject: string;
readonly body: string;
readonly active: boolean;
};
export type PortalEmailTemplateAdminSnapshot = {
readonly portalId: string | null;
readonly stages: readonly PortalEmailTemplateAdminStage[];
readonly templates: readonly PortalEmailTemplateAdminRow[];
};
export type PortalEmailTemplateUpsertResult = {
readonly template: PortalEmailTemplateAdminRow;
readonly portalId: string;
readonly stageLabel: string;
readonly created: boolean;
readonly changed: boolean;
};
export async function readPortalEmailTemplateAdminSnapshot(
tx: Prisma.TransactionClient,
input: { readonly tenantId: string; readonly locale: string }
): Promise<PortalEmailTemplateAdminSnapshot> {
const portal = await tx.portal.findUnique({
where: { tenantId: input.tenantId },
select: { id: true },
});
if (!portal) {
return { portalId: null, stages: [], templates: [] };
}
const visibilityRows = await tx.portalStageVisibility.findMany({
where: {
tenantId: input.tenantId,
portalId: portal.id,
visible: true,
stage: { archivedAt: null, pipeline: { archivedAt: null } },
},
select: {
stageId: true,
customerLabel: true,
stage: {
select: {
name: true,
position: true,
pipeline: { select: { position: true } },
},
},
},
});
visibilityRows.sort(
(left, right) =>
left.stage.pipeline.position - right.stage.pipeline.position ||
left.stage.position - right.stage.position ||
left.stage.name.localeCompare(right.stage.name)
);
const stages = visibilityRows.map(
(row): PortalEmailTemplateAdminStage => ({
id: row.stageId,
label: row.customerLabel?.trim() || row.stage.name,
visible: true,
})
);
if (stages.length === 0) {
return { portalId: portal.id, stages, templates: [] };
}
const templates = await tx.portalEmailTemplate.findMany({
where: {
tenantId: input.tenantId,
portalId: portal.id,
locale: input.locale,
stageId: { in: stages.map((stage) => stage.id) },
},
select: { id: true, stageId: true, subject: true, body: true, active: true },
});
return { portalId: portal.id, stages, templates };
}
export async function upsertVisiblePortalEmailTemplate(
tx: Prisma.TransactionClient,
input: {
readonly tenantId: string;
readonly stageId: string;
readonly locale: string;
readonly subject: string;
readonly body: string;
readonly active: boolean;
}
): Promise<PortalEmailTemplateUpsertResult | null> {
const portal = await tx.portal.findUnique({
where: { tenantId: input.tenantId },
select: { id: true },
});
if (!portal) return null;
const visibility = await tx.portalStageVisibility.findFirst({
where: {
tenantId: input.tenantId,
portalId: portal.id,
stageId: input.stageId,
visible: true,
stage: { archivedAt: null, pipeline: { archivedAt: null } },
},
select: { customerLabel: true, stage: { select: { name: true } } },
});
if (!visibility) return null;
const uniqueKey = {
portalId_stageId_locale: {
portalId: portal.id,
stageId: input.stageId,
locale: input.locale,
},
} as const;
const existing = await tx.portalEmailTemplate.findUnique({
where: uniqueKey,
select: { id: true, stageId: true, subject: true, body: true, active: true },
});
const stageLabel = visibility.customerLabel?.trim() || visibility.stage.name;
if (existing && existing.subject === input.subject && existing.body === input.body && existing.active === input.active) {
return { template: existing, portalId: portal.id, stageLabel, created: false, changed: false };
}
const template = await tx.portalEmailTemplate.upsert({
where: uniqueKey,
create: {
tenantId: input.tenantId,
portalId: portal.id,
stageId: input.stageId,
locale: input.locale,
subject: input.subject,
body: input.body,
active: input.active,
},
update: { subject: input.subject, body: input.body, active: input.active },
select: { id: true, stageId: true, subject: true, body: true, active: true },
});
return { template, portalId: portal.id, stageLabel, created: existing === null, changed: true };
}
@@ -1,389 +0,0 @@
import type { PortalSubscriptionFeature, PortalSubscriptionPrice, PortalSubscriptionProduct } from "@hivegrid/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 getPortalSubscriptionProductByBillingProviderId(portalId: string, billingProviderId: string) {
return await db.portalSubscriptionProduct.findFirst({
where: {
portalId,
billingProviderId,
},
});
}
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 getPortalSubscriptionPriceByBillingProviderId(portalId: string, billingProviderId: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findFirst({
where: { portalId, billingProviderId },
include: {
subscriptionProduct: true,
},
})
.catch(() => {
return null;
});
}
export async function createPortalSubscriptionProduct(data: {
portalId: string;
billingProviderId: 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,
billingProviderId: data.billingProviderId,
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: {
billingProviderId?: 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: {
billingProviderId: data.billingProviderId,
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 updatePortalSubscriptionProductBillingProviderId(portalId: string, id: string, data: { billingProviderId: string }) {
return await db.portalSubscriptionProduct.update({
where: {
portalId,
id,
},
data,
});
}
export async function updatePortalSubscriptionPriceBillingProviderId(portalId: string, id: string, data: { billingProviderId: string }) {
return await db.portalSubscriptionPrice.update({
where: {
portalId,
id,
},
data,
});
}
export async function createPortalSubscriptionPrice(data: {
portalId: string;
subscriptionProductId: string;
billingProviderId: 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,
billingProviderId: data.billingProviderId,
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,
},
});
}
@@ -1,254 +0,0 @@
import {
Prisma,
PortalSubscriptionFeature,
PortalSubscriptionPrice,
PortalSubscriptionProduct,
PortalUserSubscription,
PortalUserSubscriptionProduct,
PortalUserSubscriptionProductPrice,
} from "@hivegrid/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 getPortalUserSubscriptionProductByBillingProviderSubscriptionId(
portalId: string,
billingProviderSubscriptionId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
billingProviderSubscriptionId,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function addPortalUserSubscriptionProduct(data: {
portalId: string;
portalUserSubscriptionId: string;
subscriptionProductId: string;
billingProviderSubscriptionId?: string;
quantity?: number;
fromCheckoutSessionId?: string | null;
prices: {
subscriptionPriceId?: string;
}[];
}) {
return await db.portalUserSubscriptionProduct
.create({
data: {
portalId: data.portalId,
portalUserSubscriptionId: data.portalUserSubscriptionId,
subscriptionProductId: data.subscriptionProductId,
billingProviderSubscriptionId: data.billingProviderSubscriptionId,
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}`);
});
}
@@ -1,116 +0,0 @@
import { PortalUserSubscription } from "@hivegrid/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, billingProviderCustomerId: string) {
return await db.portalUserSubscription
.create({
data: {
portalId,
portalUserId,
billingProviderCustomerId,
},
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: { billingProviderCustomerId: string }) {
return await db.portalUserSubscription
.update({
where: {
portalId,
portalUserId,
},
data,
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${portalId}:${portalUserId}`);
return item;
});
}
@@ -2,10 +2,14 @@ import { db } from "~/utils/db.server";
import { PortalUserDto } from "../dtos/PortalUserDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
// cachified expects milliseconds. Portal-user mutations only clear the local
// web L1 today, so do not retain authorization-adjacent identity data longer.
const PORTAL_USER_CACHE_TTL_MS = 60_000;
export async function getPortalUserById(portalId: string, id: string): Promise<PortalUserDto | null> {
return await cachified({
key: `portalUser:${portalId}:${id}`,
ttl: 60 * 60 * 24,
ttl: PORTAL_USER_CACHE_TTL_MS,
getFreshValue: async () => {
return db.portalUser.findFirst({
where: {
@@ -27,15 +31,16 @@ export async function getPortalUserById(portalId: string, id: string): Promise<P
}
export async function getPortalUserByEmail(portalId: string, email: string): Promise<PortalUserDto | null> {
const emailNormalized = normalizePortalEmail(email);
return await cachified({
key: `portalUserByEmail:${portalId}:${email}`,
ttl: 60 * 60 * 24,
key: `portalUserByEmail:${portalId}:${emailNormalized}`,
ttl: PORTAL_USER_CACHE_TTL_MS,
getFreshValue: async () => {
return db.portalUser.findUnique({
where: {
portalId_email: {
portalId_emailNormalized: {
portalId,
email,
emailNormalized,
},
},
select: {
@@ -73,7 +78,7 @@ export async function getPortalUsers(portalId: string): Promise<PortalUserDto[]>
}
export async function createPortalUser(data: {
tenantId: string | null;
tenantId: string;
portalId: string;
email: string;
passwordHash: string;
@@ -86,6 +91,7 @@ export async function createPortalUser(data: {
tenantId: data.tenantId,
portalId: data.portalId,
email: data.email,
emailNormalized: normalizePortalEmail(data.email),
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
@@ -124,6 +130,7 @@ export async function updatePortalUser(
},
data: {
email: data.email,
emailNormalized: data.email === undefined ? undefined : normalizePortalEmail(data.email),
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
@@ -140,8 +147,8 @@ export async function updatePortalUser(
},
});
clearCacheKey(`portalUser:${portalId}:${id}`);
clearCacheKey(`portalUserByEmail:${portalId}:${before.email}`);
clearCacheKey(`portalUserByEmail:${portalId}:${item.email}`);
clearCacheKey(`portalUserByEmail:${portalId}:${normalizePortalEmail(before.email)}`);
clearCacheKey(`portalUserByEmail:${portalId}:${normalizePortalEmail(item.email)}`);
return item;
}
@@ -159,7 +166,7 @@ export async function deletePortalUser(portalId: string, id: string) {
return result;
}
export async function countPortalUsersByTenantId(tenantId: string | null): Promise<number> {
export async function countPortalUsersByTenantId(tenantId: string): Promise<number> {
return await db.portalUser.count({
where: {
tenantId,
@@ -167,6 +174,10 @@ export async function countPortalUsersByTenantId(tenantId: string | null): Promi
});
}
function normalizePortalEmail(email: string): string {
return email.trim().toLowerCase();
}
export async function getPortalUserPasswordHash(id: string): Promise<string | null> {
const user = await db.portalUser.findUnique({
where: {
@@ -1,29 +0,0 @@
// @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 });");
});
});
@@ -1,365 +0,0 @@
import { Prisma, Portal } from "@hivegrid/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 "@hivegrid/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;
paymentProviderAccountId: 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,
paymentProviderAccountId: data.paymentProviderAccountId,
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;
paymentProviderAccountId?: 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,
paymentProviderAccountId: data.paymentProviderAccountId,
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({});
}
@@ -5,7 +5,6 @@ export type PortalDto = {
tenantId: string | null;
url: string;
subdomain: string;
domain: string | null;
title: string;
isPublished: boolean;
paymentProviderAccountId: string | null;
@@ -1,41 +0,0 @@
export const selectSimplePortalUserProperties = {
id: true,
email: true,
firstName: true,
lastName: true,
phone: true,
locale: true,
createdAt: true,
};
const selectWithAvatar = {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
admin: true,
defaultTenantId: true,
createdAt: true,
locale: true,
};
const includeSimpleCreatedByUser = {
createdByUser: {
select: selectSimplePortalUserProperties,
},
};
const includeSimpleUser = {
user: {
select: selectSimplePortalUserProperties,
},
};
export default {
includeSimpleCreatedByUser,
includeSimpleUser,
selectSimplePortalUserProperties,
selectWithAvatar,
};
@@ -1,8 +0,0 @@
const includePortalUserSubscriptionProductDetails = {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
};
export default {
includePortalUserSubscriptionProductDetails,
};
@@ -5,12 +5,33 @@ import { getRepoRoot, readRepoFile, repoPathExists } from "~/utils/testing/repoP
const repoRoot = getRepoRoot();
const packagesDbIndexPath = path.join(repoRoot, "packages/db/src/index.ts");
const temporaryModuleDbFiles = [
"apps/web/app/modules/portals/db/portals.db.server.ts",
const retainedModuleDbFiles = [
"apps/web/app/modules/portals/db/portalPages.db.server.ts",
"apps/web/app/modules/portals/db/portalUsers.db.server.ts",
"apps/web/app/modules/portals/db/portalEmailTemplates.db.server.ts",
"apps/web/app/modules/sites/db/sites.db.server.ts",
];
const removedLegacyPortalFiles = [
"apps/web/app/modules/portals/db/portalCheckoutSessions.db.server.ts",
"apps/web/app/modules/portals/db/portalSubscriptionProducts.db.server.ts",
"apps/web/app/modules/portals/db/portalUserSubscriptionProducts.db.server.ts",
"apps/web/app/modules/portals/db/portalUserSubscriptions.db.server.ts",
"apps/web/app/modules/portals/db/portals.db.server.ts",
"apps/web/app/modules/portals/helpers/PortalUserModelHelper.ts",
"apps/web/app/modules/portals/helpers/PortalUserSubscriptionProductModelHelper.ts",
"apps/web/app/modules/portals/services/Portal.server.ts",
"apps/web/app/modules/portals/services/PortalPricing.server.ts",
"apps/web/app/modules/portals/services/PortalSubscription.server.ts",
];
const removedLegacyPortalModels = [
"PortalSubscriptionProduct",
"PortalSubscriptionPrice",
"PortalSubscriptionFeature",
"PortalUserSubscription",
"PortalUserSubscriptionProduct",
"PortalUserSubscriptionProductPrice",
"PortalCheckoutSessionStatus",
];
function getExportLines(source: string): string[] {
return source
@@ -20,7 +41,7 @@ function getExportLines(source: string): string[] {
}
describe("Portals/Sites DB ownership boundary", () => {
it("keeps portal/site persistence out of packages/db until the Feature Decision decision", () => {
it("keeps portal/site persistence in the VA-P26 module boundary", () => {
const exportLines = getExportLines(readFileSync(packagesDbIndexPath, "utf8"));
const forbiddenExportPattern = /\b(?:portal|portals|site|sites)\b/i;
const forbiddenLines = exportLines.filter((line) => forbiddenExportPattern.test(line));
@@ -28,33 +49,41 @@ describe("Portals/Sites DB ownership boundary", () => {
expect(
forbiddenLines,
[
"D006 defers Portals/Sites DB ownership until Feature Decision.",
"Remove portal/site persistence exports from packages/db/src/index.ts or update the Feature Decision ownership decision first.",
"VA-P26a and AD-30 keep Portal/Sites persistence module-owned.",
"Remove portal/site persistence exports from packages/db/src/index.ts or update the owning ticket and AD contract first.",
`Forbidden export lines: ${forbiddenLines.join(" | ") || "none"}`,
].join(" ")
).toEqual([]);
});
it("documents the accepted temporary module-owned DB files", () => {
for (const relativePath of temporaryModuleDbFiles) {
it("keeps only the retained module-owned Portal/Site persistence files", () => {
for (const relativePath of retainedModuleDbFiles) {
expect(
repoPathExists(relativePath),
`D006/Feature Decision boundary drift: ${relativePath} must remain as the temporary module-owned persistence file until Feature Decision changes the ownership decision.`
`VA-P26a persistence boundary drift: retained module file ${relativePath} must exist.`
).toBe(true);
}
expect(
readRepoFile(relativePath),
`D006/Feature Decision boundary drift: ${relativePath} must continue importing ~/utils/db.server while Portals/Sites persistence is deferred from packages/db.`
).toContain('~/utils/db.server');
for (const relativePath of retainedModuleDbFiles.filter((file) => !file.endsWith("portalEmailTemplates.db.server.ts"))) {
expect(readRepoFile(relativePath), `${relativePath} must continue using the module DB boundary.`).toContain('~/utils/db.server');
}
expect(readRepoFile("apps/web/app/modules/portals/db/portalEmailTemplates.db.server.ts")).toContain("Prisma.TransactionClient");
});
it("does not retain the excluded Portal commerce modules or schema models", () => {
for (const relativePath of removedLegacyPortalFiles) {
expect(repoPathExists(relativePath), `VA-P26a legacy recut drift: ${relativePath} must stay removed.`).toBe(false);
}
const portalSchema = readRepoFile("prisma/schema/portals.prisma");
for (const model of removedLegacyPortalModels) {
expect(portalSchema, `VA-P26a legacy recut drift: model ${model} must stay removed.`).not.toMatch(new RegExp(`\\bmodel\\s+${model}\\b`, "u"));
}
});
it("keeps tenant-owned portal and site mutations scoped at the DB boundary", () => {
const portalsSource = readRepoFile("apps/web/app/modules/portals/db/portals.db.server.ts");
it("keeps tenant-owned site mutations scoped at the DB boundary", () => {
const sitesSource = readRepoFile("apps/web/app/modules/sites/db/sites.db.server.ts");
expect(portalsSource).toContain("where: { id: before.id, tenantId: before.tenantId }");
expect(portalsSource).toContain("export async function deletePortal({ id, tenantId }: { id: string; tenantId: string | null })");
expect(sitesSource).toContain("export async function getSite({ id, tenantId }: { id: string; tenantId: string })");
expect(sitesSource).toContain("export async function updateSite(");
expect(sitesSource).toContain("scope: { id: string; tenantId: string }");
@@ -64,6 +93,7 @@ describe("Portals/Sites DB ownership boundary", () => {
it("keeps tenant-owned portal child mutations scoped at the DB boundary", () => {
const portalUsersSource = readRepoFile("apps/web/app/modules/portals/db/portalUsers.db.server.ts");
const portalPagesSource = readRepoFile("apps/web/app/modules/portals/db/portalPages.db.server.ts");
const portalEmailTemplatesSource = readRepoFile("apps/web/app/modules/portals/db/portalEmailTemplates.db.server.ts");
expect(portalUsersSource).toContain("export async function updatePortalUser(");
expect(portalUsersSource).toContain("portalId: string,");
@@ -74,5 +104,8 @@ describe("Portals/Sites DB ownership boundary", () => {
expect(portalPagesSource).toContain("db.portalPage.updateMany");
expect(portalPagesSource).toContain("export async function deletePortalPage(portalId: string, id: string)");
expect(portalPagesSource).toContain("db.portalPage.deleteMany");
expect(portalEmailTemplatesSource).toContain("where: { tenantId: input.tenantId }");
expect(portalEmailTemplatesSource).toContain("tenantId: input.tenantId");
expect(portalEmailTemplatesSource).toContain("await tx.portalEmailTemplate.upsert");
});
});
@@ -1,102 +0,0 @@
import { execFileSync } from "node:child_process";
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { getRepoRoot, resolveRepoPath } from "~/utils/testing/repoPaths";
const repoRoot = getRepoRoot();
const verifierPath = path.join(repoRoot, "scripts/verify-portals-sites-decision-report.mjs");
const requiredFixtureFiles = [
"docs/feature-decisions/portals-sites-decision-report.md",
"docs/feature-inventory.md",
"docs/feature-manifests/plugin-candidates.json",
"apps/web/app/modules/portals/db/portals.db.server.ts",
"apps/web/app/modules/sites/db/sites.db.server.ts",
"apps/web/app/modules/sites/site-types.ts",
"prisma/schema/analytics.prisma",
"apps/web/app/modules/domains/services/Domains.server.ts",
"apps/web/app/application/sidebar/AppSidebar.test.tsx",
"prisma/schema/portals.prisma",
"prisma/schema/sites.prisma",
".env.example",
".env.production.example",
];
const requiredFixtureDirectories = [
"apps/web/app/modules/portals",
"apps/web/app/modules/sites",
"apps/web/app/routes/app.$tenant/__portals",
"apps/web/app/routes/app.$tenant/sites",
];
let fixtureRoot: string | undefined;
function runVerifier(root: string = repoRoot): string {
return execFileSync(process.execPath, [verifierPath, root], {
cwd: repoRoot,
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
}
function copyRepoFileToFixture(relativePath: string): void {
if (!fixtureRoot) {
throw new Error("fixtureRoot must be initialized before copying files");
}
const destinationPath = relativePath.startsWith("app/") ? path.join(fixtureRoot, "apps/web", relativePath) : path.join(fixtureRoot, relativePath);
mkdirSync(path.dirname(destinationPath), { recursive: true });
copyFileSync(resolveRepoPath(relativePath), destinationPath);
}
function createFixtureRoot(): string {
fixtureRoot = mkdtempSync(path.join(tmpdir(), "portals-sites-verifier-"));
for (const relativePath of requiredFixtureFiles) {
copyRepoFileToFixture(relativePath);
}
for (const relativeDirectory of requiredFixtureDirectories) {
const fixtureDirectory = relativeDirectory.startsWith("app/")
? path.join(fixtureRoot, "apps/web", relativeDirectory)
: path.join(fixtureRoot, relativeDirectory);
mkdirSync(fixtureDirectory, { recursive: true });
writeFileSync(path.join(fixtureDirectory, ".keep"), "fixture directory marker\n");
}
return fixtureRoot;
}
function replaceFixtureFile(fixturePath: string, transform: (source: string) => string): void {
writeFileSync(fixturePath, transform(readFileSync(fixturePath, "utf8")));
}
describe("Portals/Sites decision report verifier", () => {
afterEach(() => {
if (fixtureRoot) {
rmSync(fixtureRoot, { recursive: true, force: true });
fixtureRoot = undefined;
}
});
it("passes for the committed Portals/Sites decision report, inventory, and manifest", () => {
expect(runVerifier()).toContain("PASS portals/sites decision report verification");
});
it("fails when a report fixture contains an unresolved TODO placeholder", () => {
const root = createFixtureRoot();
replaceFixtureFile(path.join(root, "docs/feature-decisions/portals-sites-decision-report.md"), (report) => `${report}\nTODO: fixture placeholder\n`);
expect(() => runVerifier(root)).toThrow(/report contains unresolved placeholder line: TODO: fixture placeholder/);
});
it("fails when the portals-sites manifest component is removed from a fixture", () => {
const root = createFixtureRoot();
replaceFixtureFile(path.join(root, "docs/feature-manifests/plugin-candidates.json"), (source) => {
const manifest = JSON.parse(source) as { components: Array<{ id: string }> };
manifest.components = manifest.components.filter((component) => component.id !== "portals-sites");
return `${JSON.stringify(manifest, null, 2)}\n`;
});
expect(() => runVerifier(root)).toThrow(/manifest must contain component id "portals-sites"/);
});
});
@@ -1,25 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import Portal from "./Portal.server";
const originalNodeEnv = process.env.NODE_ENV;
const originalPortalServerUrl = process.env.PORTAL_SERVER_URL;
afterEach(() => {
process.env.NODE_ENV = originalNodeEnv;
process.env.PORTAL_SERVER_URL = originalPortalServerUrl;
});
describe("Portal.server", () => {
it("normalizes production custom domains to https without double-scheming", () => {
process.env.NODE_ENV = "production";
expect(Portal.getPortalUrl({ subdomain: "demo", domain: "http://portal.example.com" })).toBe("https://portal.example.com");
});
it("builds a subdomain URL from PORTAL_SERVER_URL", () => {
process.env.NODE_ENV = "development";
process.env.PORTAL_SERVER_URL = "http://portals.example.test:3000";
expect(Portal.getPortalUrl({ subdomain: "demo", domain: null })).toBe("http://demo.portals.example.test:3000");
});
});
@@ -1,36 +0,0 @@
import { loadWebConfig, type WebConfig } from "@hivegrid/config";
function getPortalUrl(item: { subdomain: string; domain: string | null }, webConfig: WebConfig = loadWebConfig().config) {
if (item.domain) {
let domain = item.domain.trim();
if (!/^https?:\/\//i.test(domain) && webConfig.nodeEnv === "development") {
domain = `http://${domain}`;
} else if (webConfig.nodeEnv === "production") {
domain = domain.replace(/^http:\/\//i, "");
if (!/^https:\/\//i.test(domain)) {
domain = `https://${domain}`;
}
}
const url = new URL(domain);
let urlString = url.toString();
// without trailing slash
if (urlString.endsWith("/")) {
urlString = urlString.slice(0, -1);
}
return urlString;
}
if (!webConfig.portalServer.url) {
throw new Error("PORTAL_SERVER_URL is not defined");
}
const portalUrl = new URL(webConfig.portalServer.url);
let subdomain = item.subdomain;
subdomain = `${portalUrl.protocol}//${subdomain}.${portalUrl.hostname}`;
if (portalUrl.port) {
subdomain += `:${portalUrl.port}`;
}
return subdomain;
}
export default {
getPortalUrl,
};
@@ -1,169 +0,0 @@
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import {
createPortalSubscriptionProduct,
createPortalSubscriptionPrice,
createPortalSubscriptionFeature,
updatePortalSubscriptionProductBillingProviderId,
updatePortalSubscriptionPriceBillingProviderId,
deletePortalSubscriptionPrice,
deletePortalSubscriptionProduct,
updatePortalSubscriptionProduct,
deletePortalSubscriptionFeatures,
} from "../db/portalSubscriptionProducts.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import PortalSubscriptionServer from "./PortalSubscription.server";
import { createScopedLogger } from "~/utils/logger.server";
const portalPricingLogger = createScopedLogger("portals.pricing");
async function createPlans(portalId: string, plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
portalId,
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features
);
}
}
async function createPlan(
portalId: string,
plan: SubscriptionProductDto,
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[]
) {
const product = await createPortalSubscriptionProduct({
portalId,
billingProviderId: plan.billingProviderId || plan.id || plan.title,
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? undefined,
badge: plan.badge ?? undefined,
groupTitle: plan.groupTitle ?? undefined,
groupDescription: plan.groupDescription ?? undefined,
active: plan.active,
public: plan.public,
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity ?? false,
canBuyAgain: plan.canBuyAgain ?? false,
});
if (!product) {
throw new Error("Could not create subscription product");
}
await Promise.all(
prices.map(async (price) => {
return await createPortalSubscriptionPrice({
...price,
portalId,
subscriptionProductId: product.id,
billingProviderId: `${product.id}:${price.billingPeriod}:${price.currency}:${price.price}`,
type: SubscriptionPriceType.RECURRING,
billingPeriod: price.billingPeriod,
price: price.price,
currency: price.currency,
trialDays: price.trialDays ?? 0,
active: true,
});
})
);
await Promise.all(
features
.sort((a, b) => a.order - b.order)
.map(async (feature) => {
// Save to db
return await createPortalSubscriptionFeature(portalId, product.id, feature);
})
);
}
async function syncPlan(
portalId: string,
plan: SubscriptionProductDto,
prices: { id?: string; billingPeriod: SubscriptionBillingPeriod; price: number; currency: string }[]
) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
await updatePortalSubscriptionProductBillingProviderId(portalId, plan.id, {
billingProviderId: plan.billingProviderId || plan.id,
});
prices.map(async (price) => {
await updatePortalSubscriptionPriceBillingProviderId(portalId, price.id ?? "", {
billingProviderId: price.id ?? `${plan.id}:${price.billingPeriod}:${price.currency}`,
});
});
}
async function updatePlan(portalId: string, plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
await updatePortalSubscriptionProduct(portalId, plan.id, {
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? undefined,
badge: plan.badge ?? undefined,
groupTitle: plan.groupTitle ?? undefined,
groupDescription: plan.groupDescription ?? undefined,
public: plan.public,
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity,
canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain,
});
await deletePortalSubscriptionFeatures(portalId, plan.id ?? "");
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
return await Promise.all(
features
.sort((a, b) => a.order - b.order)
.map(async (feature) => {
return await createPortalSubscriptionFeature(portalId, plan.id ?? "", feature);
})
);
}
async function deletePlan(portalId: string, plan: SubscriptionProductDto) {
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
portalPricingLogger.info({ count: plan.prices?.length }, `Deleting ${plan.prices?.length} Flat-rate Prices`);
await Promise.all(
plan.prices
.filter((f) => f.billingProviderId)
.map(async (price) => {
if (price.id) {
await deletePortalSubscriptionPrice(portalId, price.id);
}
return null;
})
);
if (plan.id) {
await deletePortalSubscriptionProduct(portalId, plan.id);
}
}
export default {
createPlans,
createPlan,
syncPlan,
updatePlan,
deletePlan,
};
@@ -1,31 +0,0 @@
import currencies from "~/application/pricing/currencies";
import { clearCacheKey } from "~/utils/cache.server";
import { db } from "~/utils/db.server";
async function clearSubscriptionsCache(portalId: string) {
const portalUserSubscriptions = await db.portalUserSubscription.findMany({ where: { portalId } });
portalUserSubscriptions.forEach((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserId}`);
});
}
function convertToCurrency({ from, price, to }: { from: string; price: number; to: string }): number {
const fromCurrency = currencies.find((f) => f.value === from);
const toCurrency = currencies.find((f) => f.value === to);
if (!fromCurrency || !toCurrency) {
return 0;
}
const fromParity = fromCurrency.parities?.find((f) => f.from === to);
const toParity = toCurrency.parities?.find((f) => f.from === from);
if (fromParity && fromParity.parity !== 0) {
return price / fromParity.parity;
} else if (toParity && toParity.parity !== 0) {
return price / toParity.parity;
}
return 0;
}
export default {
clearSubscriptionsCache,
convertToCurrency,
};