Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
-38
@@ -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,
|
||||
},
|
||||
});
|
||||
}
|
||||
+137
@@ -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" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+152
@@ -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 };
|
||||
}
|
||||
-389
@@ -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,
|
||||
},
|
||||
});
|
||||
}
|
||||
-254
@@ -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}`);
|
||||
});
|
||||
}
|
||||
-116
@@ -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;
|
||||
});
|
||||
}
|
||||
+20
-9
@@ -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: {
|
||||
|
||||
-29
@@ -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 });");
|
||||
});
|
||||
});
|
||||
-365
@@ -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({});
|
||||
}
|
||||
Reference in new issue
Block a user