Track HiveGrid Cloud planning reference

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

No files matched your search

@@ -0,0 +1,27 @@
import React from "react";
import "@testing-library/jest-dom/vitest";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { PortalTimestamp } from "./PortalTimestamp";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ i18n: { language: "de" } }),
}));
describe("PortalTimestamp", () => {
it("renders locale-aware relative text with machine-readable time metadata", () => {
const value = new Date("2026-05-26T10:20:30.000Z");
const { container } = render(<PortalTimestamp value={value} className="text-xs" />);
const timestamp = container.querySelector("time");
if (!timestamp) {
throw new Error("expected PortalTimestamp to render a time element");
}
expect(timestamp.tagName).toBe("TIME");
expect(timestamp).toHaveAttribute("dateTime", value.toISOString());
expect(timestamp).toHaveAttribute("title");
expect(timestamp).toHaveClass("text-xs");
expect(timestamp?.textContent).toBeTruthy();
});
});
@@ -0,0 +1,17 @@
import { useLocaleFormatters } from "~/locale/format";
type PortalTimestampProps = {
value: Date | string | number;
className?: string;
};
export function PortalTimestamp({ value, className }: PortalTimestampProps) {
const formatters = useLocaleFormatters();
const date = value instanceof Date ? value : new Date(value);
return (
<time dateTime={date.toISOString()} title={formatters.dateTime(date, { timeStyle: "medium" })} className={className}>
{formatters.relativeDate(date)}
</time>
);
}
@@ -0,0 +1,38 @@
import { db } from "~/utils/db.server";
export async function getCheckoutSessionStatus(id: string) {
return db.portalCheckoutSessionStatus.findUnique({
where: { id },
});
}
export async function createCheckoutSessionStatus(data: { id: string; portalId: string; email: string; fromUrl: string; fromUserId?: string | null }) {
return db.portalCheckoutSessionStatus.create({
data: {
id: data.id,
portalId: data.portalId,
pending: true,
email: data.email,
fromUrl: data.fromUrl,
fromUserId: data.fromUserId ?? null,
},
});
}
export async function updateCheckoutSessionStatus(
id: string,
data: {
pending: boolean;
createdUserId?: string | null;
}
) {
return db.portalCheckoutSessionStatus.update({
where: {
id,
},
data: {
pending: data.pending,
createdUserId: data.createdUserId ?? null,
},
});
}
@@ -0,0 +1,67 @@
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { db, dbRead } from "~/utils/db.server";
export async function getPortalPages(portalId: string) {
// Public portal page listing — read-only, replica-safe.
return await dbRead.portalPage.findMany({
where: {
portalId,
},
});
}
export async function getPortalPagesByName(portalId: string, name: string) {
// Public portal page lookup by name — read-only, replica-safe.
return await dbRead.portalPage.findUnique({
where: {
portalId_name: {
portalId,
name,
},
},
});
}
export async function createPortalPage(data: { portalId: string; name: string; attributes: JsonPropertiesValuesDto }) {
return await db.portalPage.create({
data: {
portalId: data.portalId,
name: data.name,
attributes: data.attributes,
},
});
}
export async function updatePortalPage(portalId: string, id: string, data: { attributes: JsonPropertiesValuesDto }) {
const result = await db.portalPage.updateMany({
where: {
portalId,
id,
},
data: {
attributes: data.attributes,
},
});
if (result.count !== 1) {
throw new Error("Portal page not found for portal scope.");
}
return await db.portalPage.findFirstOrThrow({
where: {
portalId,
id,
},
});
}
export async function deletePortalPage(portalId: string, id: string) {
const result = await db.portalPage.deleteMany({
where: {
portalId,
id,
},
});
if (result.count !== 1) {
throw new Error("Portal page not found for portal scope.");
}
return result;
}
@@ -0,0 +1,389 @@
import type { PortalSubscriptionFeature, PortalSubscriptionPrice, PortalSubscriptionProduct } from "@toolctrl/db/prisma-browser";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { db } from "~/utils/db.server";
export type PortalSubscriptionPriceWithProduct = PortalSubscriptionPrice & {
subscriptionProduct: PortalSubscriptionProduct;
};
export async function getAllPortalSubscriptionProductsWithUsers(portalId: string): Promise<SubscriptionProductDto[]> {
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: [{ public: "desc" }, { order: "asc" }],
})
.catch(() => {
return [];
});
}
export async function getAllPortalSubscriptionProducts(portalId: string, isPublic?: boolean): Promise<SubscriptionProductDto[]> {
if (isPublic) {
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
active: true,
public: true,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: {
order: "asc",
},
})
.catch(() => {
return [];
});
}
return await db.portalSubscriptionProduct
.findMany({
where: {
portalId,
active: true,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: {
order: "asc",
},
})
.catch(() => {
return [];
});
}
export async function getPortalSubscriptionProductsInIds(portalId: string, ids: string[]): Promise<SubscriptionProductDto[]> {
return await db.portalSubscriptionProduct.findMany({
where: {
portalId,
id: { in: ids },
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
orderBy: { order: "asc" },
});
}
export async function getAllPortalSubscriptionFeatures(
portalId: string
): Promise<{ name: string; order: number; title: string; type: number; value: number; accumulate: boolean }[]> {
return await db.portalSubscriptionFeature.findMany({
where: {
portalId,
},
select: { name: true, order: true, title: true, type: true, value: true, accumulate: true },
});
}
export async function getPortalSubscriptionProduct(portalId: string, id: string): Promise<SubscriptionProductDto | null> {
return await db.portalSubscriptionProduct.findUnique({
where: {
portalId,
id,
},
include: {
portalUserProducts: true,
prices: true,
features: {
orderBy: {
order: "asc",
},
},
},
});
}
export async function getPortalSubscriptionProductByStripeId(portalId: string, stripeId: string) {
return await db.portalSubscriptionProduct.findFirst({
where: {
portalId,
stripeId,
},
});
}
export async function getPortalSubscriptionPrices(portalId: string): Promise<PortalSubscriptionPriceWithProduct[]> {
return await db.portalSubscriptionPrice
.findMany({
where: {
portalId,
},
include: {
subscriptionProduct: true,
},
orderBy: [
{
subscriptionProduct: {
order: "asc",
},
},
{
price: "asc",
},
],
})
.catch(() => {
return [];
});
}
export async function getPortalSubscriptionPrice(portalId: string, id: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findUnique({
where: { portalId, id },
include: {
subscriptionProduct: true,
},
})
.catch(() => {
return null;
});
}
export async function getPortalSubscriptionPriceByStripeId(portalId: string, stripeId: string): Promise<PortalSubscriptionPriceWithProduct | null> {
return await db.portalSubscriptionPrice
.findFirst({
where: { portalId, stripeId },
include: {
subscriptionProduct: true,
},
})
.catch(() => {
return null;
});
}
export async function createPortalSubscriptionProduct(data: {
portalId: string;
stripeId: string;
order: number;
title: string;
model: PricingModel;
description?: string;
badge?: string;
groupTitle?: string;
groupDescription?: string;
active: boolean;
public: boolean;
billingAddressCollection: string;
hasQuantity: boolean;
canBuyAgain: boolean;
}): Promise<PortalSubscriptionProduct> {
return await db.portalSubscriptionProduct.create({
data: {
portalId: data.portalId,
stripeId: data.stripeId,
order: data.order,
title: data.title,
model: data.model,
description: data.description,
badge: data.badge,
groupTitle: data.groupTitle,
groupDescription: data.groupDescription,
active: data.active,
public: data.public,
billingAddressCollection: data.billingAddressCollection,
hasQuantity: data.hasQuantity,
canBuyAgain: data.canBuyAgain,
},
});
}
export async function updatePortalSubscriptionProduct(
portalId: string,
id: string,
data: {
stripeId?: string;
order?: number;
title?: string;
model?: PricingModel;
description?: string | null;
badge?: string | null;
groupTitle?: string | null;
groupDescription?: string | null;
public?: boolean;
billingAddressCollection?: string;
hasQuantity?: boolean;
canBuyAgain?: boolean;
}
): Promise<PortalSubscriptionProduct> {
const result = await db.portalSubscriptionProduct.updateMany({
where: {
id,
portalId,
},
data: {
stripeId: data.stripeId,
order: data.order,
title: data.title,
model: data.model,
description: data.description,
badge: data.badge,
groupTitle: data.groupTitle,
groupDescription: data.groupDescription,
public: data.public,
billingAddressCollection: data.billingAddressCollection,
hasQuantity: data.hasQuantity,
canBuyAgain: data.canBuyAgain,
},
});
if (result.count !== 1) {
throw new Error("Portal subscription product not found");
}
const item = await db.portalSubscriptionProduct.findFirst({ where: { id, portalId } });
if (!item) {
throw new Error("Portal subscription product not found");
}
return item;
}
export async function updatePortalSubscriptionProductStripeId(portalId: string, id: string, data: { stripeId: string }) {
return await db.portalSubscriptionProduct.update({
where: {
portalId,
id,
},
data,
});
}
export async function updatePortalSubscriptionPriceStripeId(portalId: string, id: string, data: { stripeId: string }) {
return await db.portalSubscriptionPrice.update({
where: {
portalId,
id,
},
data,
});
}
export async function createPortalSubscriptionPrice(data: {
portalId: string;
subscriptionProductId: string;
stripeId: string;
type: SubscriptionPriceType;
billingPeriod: SubscriptionBillingPeriod;
price: number;
currency: string;
trialDays: number;
active: boolean;
}): Promise<PortalSubscriptionPrice> {
return await db.portalSubscriptionPrice.create({
data: {
portalId: data.portalId,
subscriptionProductId: data.subscriptionProductId,
stripeId: data.stripeId,
type: data.type,
billingPeriod: data.billingPeriod,
price: data.price,
currency: data.currency,
trialDays: data.trialDays,
active: data.active,
},
});
}
export async function createPortalSubscriptionFeature(
portalId: string,
subscriptionProductId: string,
data: {
order: number;
title: string;
name: string;
type: SubscriptionFeatureLimitType;
value: number;
href?: string | null;
badge?: string | null;
accumulate?: boolean;
}
): Promise<PortalSubscriptionFeature> {
return await db.portalSubscriptionFeature.create({
data: {
portalId,
subscriptionProductId,
order: data.order,
title: data.title,
name: data.name,
type: data.type,
value: data.value,
href: data.href,
badge: data.badge,
accumulate: data.accumulate,
},
});
}
export async function deletePortalSubscriptionProduct(portalId: string, id: string) {
return await db.portalSubscriptionProduct.delete({
where: {
portalId,
id,
},
});
}
export async function deletePortalSubscriptionPrice(portalId: string, id: string) {
return await db.portalSubscriptionPrice.delete({
where: {
portalId,
id,
},
});
}
export async function deletePortalSubscriptionFeatures(portalId: string, subscriptionProductId: string) {
return await db.portalSubscriptionFeature.deleteMany({
where: {
portalId,
subscriptionProductId,
},
});
}
@@ -0,0 +1,254 @@
import {
Prisma,
PortalSubscriptionFeature,
PortalSubscriptionPrice,
PortalSubscriptionProduct,
PortalUserSubscription,
PortalUserSubscriptionProduct,
PortalUserSubscriptionProductPrice,
} from "@toolctrl/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { db } from "~/utils/db.server";
import { clearCacheKey } from "~/utils/cache.server";
import PortalUserSubscriptionProductModelHelper from "../helpers/PortalUserSubscriptionProductModelHelper";
import PortalSubscriptionServer from "../services/PortalSubscription.server";
export type PortalUserSubscriptionProductWithDetails = PortalUserSubscriptionProduct & {
subscriptionProduct: PortalSubscriptionProduct & { features: PortalSubscriptionFeature[] };
prices: (PortalUserSubscriptionProductPrice & {
subscriptionPrice: PortalSubscriptionPrice | null;
})[];
};
export type PortalUserSubscriptionProductWithTenant = PortalUserSubscriptionProductWithDetails & {
portalUserSubscription: PortalUserSubscription & {
portalUser: { id: string; email: string };
};
};
export async function getAllPortalUserSubscriptionProducts(
portalId: string,
filters?: FiltersDto,
pagination?: { page: number; pageSize: number }
): Promise<{ items: PortalUserSubscriptionProductWithTenant[]; pagination: PaginationDto }> {
let where: Prisma.PortalUserSubscriptionProductWhereInput = {};
const filterPortalUserId = filters?.properties.find((p) => p.name === "portalUserId")?.value;
const filterSubscriptionProductId = filters?.properties.find((p) => p.name === "subscriptionProductId")?.value;
const filterStatus = filters?.properties.find((p) => p.name === "status")?.value;
where = {
subscriptionProductId: filterSubscriptionProductId ? { equals: filterSubscriptionProductId } : undefined,
portalUserSubscription: {
portalUserId: filterPortalUserId ? { equals: filterPortalUserId } : undefined,
},
};
if (filterStatus === "active") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
};
} else if (filterStatus === "ended") {
where = {
...where,
endsAt: { lt: new Date(), not: null },
};
} else if (filterStatus === "active-cancelled") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
cancelledAt: { not: null },
};
} else if (filterStatus === "active-not-cancelled") {
where = {
...where,
OR: [
{
endsAt: { gte: new Date() },
},
{
endsAt: null,
},
],
cancelledAt: null,
};
}
const items = await db.portalUserSubscriptionProduct.findMany({
skip: pagination ? pagination?.pageSize * (pagination?.page - 1) : undefined,
take: pagination ? pagination?.pageSize : undefined,
where: {
portalId,
...where,
},
include: {
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
},
orderBy: {
createdAt: "desc",
},
});
const totalItems = await db.portalUserSubscriptionProduct.count({
where,
});
return {
items,
pagination: {
page: pagination?.page ?? 1,
pageSize: pagination?.pageSize ?? 10,
totalItems,
totalPages: Math.ceil(totalItems / (pagination?.pageSize ?? 10)),
},
};
}
export async function getPortalUserSubscriptionProduct(
portalId: string,
portalUserId: string,
subscriptionProductId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
portalUserSubscription: { portalUserId },
subscriptionProductId,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function getPortalUserSubscriptionProductById(portalId: string, id: string): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findUnique({
where: {
portalId,
id,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function getPortalUserSubscriptionProductByStripeSubscriptionId(
portalId: string,
stripeSubscriptionId: string
): Promise<PortalUserSubscriptionProductWithTenant | null> {
return await db.portalUserSubscriptionProduct.findFirst({
where: {
portalId,
stripeSubscriptionId,
},
include: {
portalUserSubscription: {
include: { portalUser: { select: { id: true, email: true } } },
},
...PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
},
});
}
export async function addPortalUserSubscriptionProduct(data: {
portalId: string;
portalUserSubscriptionId: string;
subscriptionProductId: string;
stripeSubscriptionId?: string;
quantity?: number;
fromCheckoutSessionId?: string | null;
prices: {
subscriptionPriceId?: string;
}[];
}) {
return await db.portalUserSubscriptionProduct
.create({
data: {
portalId: data.portalId,
portalUserSubscriptionId: data.portalUserSubscriptionId,
subscriptionProductId: data.subscriptionProductId,
stripeSubscriptionId: data.stripeSubscriptionId,
quantity: data.quantity,
fromCheckoutSessionId: data.fromCheckoutSessionId,
endsAt: null,
cancelledAt: null,
prices: {
create: data.prices.map((price) => ({
portalId: data.portalId,
subscriptionPriceId: price.subscriptionPriceId,
})),
},
},
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
return item;
});
}
export async function updatePortalUserSubscriptionProduct(
portalId: string,
id: string,
data: {
quantity?: number;
cancelledAt?: Date | null;
endsAt?: Date | null;
}
) {
return await db.portalUserSubscriptionProduct
.update({
where: { portalId, id },
data,
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
return item;
});
}
export async function cancelPortalUserSubscriptionProduct(
portalId: string,
id: string,
data: {
cancelledAt: Date | null;
endsAt: Date | null;
}
) {
await PortalSubscriptionServer.clearSubscriptionsCache(portalId);
return await db.portalUserSubscriptionProduct
.update({
where: { portalId, id },
data: {
cancelledAt: data.cancelledAt,
endsAt: data.endsAt,
},
include: { portalUserSubscription: true },
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${item.portalId}:${item.portalUserSubscription.portalUserId}`);
});
}
@@ -0,0 +1,116 @@
import { PortalUserSubscription } from "@toolctrl/db/prisma-browser";
import { clearCacheKey } from "~/utils/cache.server";
import { PortalUserSubscriptionProductWithDetails } from "./portalUserSubscriptionProducts.db.server";
import { db } from "~/utils/db.server";
import PortalUserSubscriptionProductModelHelper from "../helpers/PortalUserSubscriptionProductModelHelper";
export type PortalUserSubscriptionWithDetails = PortalUserSubscription & {
products: PortalUserSubscriptionProductWithDetails[];
};
export async function getOrPersistPortalUserSubscription(portalId: string, portalUserId: string): Promise<PortalUserSubscriptionWithDetails> {
const subscription = await db.portalUserSubscription.findUnique({
where: {
portalId,
portalUserId,
},
include: {
products: {
include: PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
if (!subscription) {
return await createPortalUserSubscription(portalId, portalUserId, "");
}
return subscription;
}
export async function getPortalUserSubscription(portalId: string, portalUserId: string): Promise<PortalUserSubscriptionWithDetails | null> {
return await db.portalUserSubscription.findUnique({
where: {
portalId,
portalUserId,
},
include: {
products: {
include: PortalUserSubscriptionProductModelHelper.includePortalUserSubscriptionProductDetails,
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
}
export async function getPortalUserSubscriptions(portalId: string): Promise<PortalUserSubscriptionWithDetails[]> {
return await db.portalUserSubscription.findMany({
where: {
portalId,
},
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
},
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
});
}
export async function createPortalUserSubscription(portalId: string, portalUserId: string, stripeCustomerId: string) {
return await db.portalUserSubscription
.create({
data: {
portalId,
portalUserId,
stripeCustomerId,
},
include: {
products: {
include: {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
},
orderBy: {
subscriptionProduct: {
order: "desc",
},
},
},
},
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${portalId}:${portalUserId}`);
return item;
});
}
export async function updatePortalUserSubscriptionCustomerId(portalId: string, portalUserId: string, data: { stripeCustomerId: string }) {
return await db.portalUserSubscription
.update({
where: {
portalId,
portalUserId,
},
data,
})
.then((item) => {
clearCacheKey(`portalUserSubscription:${portalId}:${portalUserId}`);
return item;
});
}
@@ -0,0 +1,194 @@
import { db } from "~/utils/db.server";
import { PortalUserDto } from "../dtos/PortalUserDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
export async function getPortalUserById(portalId: string, id: string): Promise<PortalUserDto | null> {
return await cachified({
key: `portalUser:${portalId}:${id}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portalUser.findFirst({
where: {
portalId,
id,
},
select: {
id: true,
portalId: true,
createdAt: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
});
},
});
}
export async function getPortalUserByEmail(portalId: string, email: string): Promise<PortalUserDto | null> {
return await cachified({
key: `portalUserByEmail:${portalId}:${email}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portalUser.findUnique({
where: {
portalId_email: {
portalId,
email,
},
},
select: {
id: true,
portalId: true,
createdAt: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
});
},
});
}
export async function getPortalUsers(portalId: string): Promise<PortalUserDto[]> {
return await db.portalUser.findMany({
where: {
portalId,
},
select: {
id: true,
createdAt: true,
portalId: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
},
orderBy: {
createdAt: "desc",
},
});
}
export async function createPortalUser(data: {
tenantId: string | null;
portalId: string;
email: string;
passwordHash: string;
firstName: string;
lastName: string;
avatar: string | null;
}) {
return await db.portalUser.create({
data: {
tenantId: data.tenantId,
portalId: data.portalId,
email: data.email,
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
avatar: data.avatar,
},
});
}
export async function updatePortalUser(
portalId: string,
id: string,
data: {
email?: string;
passwordHash?: string;
firstName?: string;
lastName?: string;
avatar?: string | null;
}
) {
const before = await db.portalUser.findFirst({
where: {
portalId,
id,
},
select: {
email: true,
},
});
if (!before) {
throw new Error("Portal user not found for portal scope.");
}
const result = await db.portalUser.updateMany({
where: {
portalId,
id,
},
data: {
email: data.email,
passwordHash: data.passwordHash,
firstName: data.firstName,
lastName: data.lastName,
avatar: data.avatar,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
const item = await db.portalUser.findFirstOrThrow({
where: {
portalId,
id,
},
});
clearCacheKey(`portalUser:${portalId}:${id}`);
clearCacheKey(`portalUserByEmail:${portalId}:${before.email}`);
clearCacheKey(`portalUserByEmail:${portalId}:${item.email}`);
return item;
}
export async function deletePortalUser(portalId: string, id: string) {
const result = await db.portalUser.deleteMany({
where: {
portalId,
id,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
clearCacheKey(`portalUser:${portalId}:${id}`);
return result;
}
export async function countPortalUsersByTenantId(tenantId: string | null): Promise<number> {
return await db.portalUser.count({
where: {
tenantId,
},
});
}
export async function getPortalUserPasswordHash(id: string): Promise<string | null> {
const user = await db.portalUser.findUnique({
where: {
id,
},
select: {
passwordHash: true,
},
});
return user?.passwordHash ?? null;
}
export async function updatePortalUserPassword(portalId: string, id: string, data: { passwordHash: string }) {
const result = await db.portalUser.updateMany({
where: { portalId, id },
data: {
passwordHash: data.passwordHash,
},
});
if (result.count !== 1) {
throw new Error("Portal user not found for portal scope.");
}
clearCacheKey(`portalUser:${portalId}:${id}`);
return result;
}
@@ -0,0 +1,29 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "portals.db.server.ts"), "utf8");
describe("portal db cache invalidation", () => {
test("clears both previous and updated domain cache keys when portals change", () => {
expect(source).toContain("clearCacheKey(`portalByDomain:${before.domain}`)");
expect(source).toContain("clearCacheKey(`portalByDomain:${item.domain}`)");
});
});
describe("portal db tenant scope", () => {
test("updates portals through the portal tenant scope", () => {
expect(source).toContain("db.portal.updateMany");
expect(source).toContain("where: { id: before.id, tenantId: before.tenantId }");
expect(source).toContain('throw new Error("Portal not found for tenant scope.")');
});
test("keeps tenant delete and admin delete boundaries separate", () => {
expect(source).toContain("export async function deletePortal({ id, tenantId }: { id: string; tenantId: string | null })");
expect(source).toContain("return deletePortalWithScope({ id, tenantId });");
expect(source).toContain("export async function adminDeletePortal(id: string)");
expect(source).toContain("return deletePortalWithScope({ id });");
});
});
@@ -0,0 +1,365 @@
import { Prisma, Portal } from "@toolctrl/db/prisma-browser";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { loadWebConfig } from "@toolctrl/config";
import { db, dbRead } from "~/utils/db.server";
import { TenantSimple } from "~/utils/db/tenants.db.server";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
import { createScopedLogger } from "~/utils/logger.server";
const portalsDbLogger = createScopedLogger("portals.db");
export type PortalWithDetails = Portal & {
tenant: TenantSimple | null;
};
export type PortalWithCount = PortalWithDetails & {
_count: {
users: number;
subscriptionProducts: number;
};
};
export async function getAllPortals({
tenantId,
filters,
filterableProperties,
pagination,
}: {
tenantId?: string | null;
filters: FiltersDto;
filterableProperties: FilterablePropertyDto[];
pagination: { pageSize: number; page: number };
}): Promise<{
items: PortalWithCount[];
pagination: PaginationDto;
}> {
const q = filters.query || "";
const AND_filters: Prisma.PortalWhereInput[] = [];
filterableProperties.forEach((filter) => {
const value = filters.properties.find((f) => f.name === filter.name)?.value;
if (value) {
AND_filters.push({
[filter.name]: value === "null" ? null : value,
});
}
});
const OR_filters: Prisma.PortalWhereInput[] = [];
if (q) {
OR_filters.push(
{ subdomain: { contains: q, mode: "insensitive" } },
{ domain: { contains: q, mode: "insensitive" } },
{ title: { contains: q, mode: "insensitive" } }
);
}
const whereFilters: Prisma.PortalWhereInput = {};
if (tenantId !== undefined) {
whereFilters.tenantId = tenantId;
}
if (OR_filters.length > 0) {
whereFilters.OR = OR_filters;
}
if (AND_filters.length > 0) {
whereFilters.AND = AND_filters;
}
// Admin paginated listing of portals — read-only, replica-safe.
const items = await dbRead.portal.findMany({
take: pagination.pageSize,
skip: pagination.pageSize * (pagination.page - 1),
where: whereFilters,
orderBy: {
createdAt: "desc",
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
_count: {
select: {
users: true,
subscriptionProducts: true,
},
},
},
});
const totalItems = await dbRead.portal.count({ where: whereFilters });
return {
items,
pagination: {
page: pagination.page,
pageSize: pagination.pageSize,
totalItems,
totalPages: Math.ceil(totalItems / pagination.pageSize),
},
};
}
export async function getAllTenantPortals({ tenantId }: { tenantId: string | null }): Promise<PortalWithCount[]> {
// Tenant portal listing for admin views — read-only, replica-safe.
return await dbRead.portal.findMany({
where: {
tenantId,
},
orderBy: {
createdAt: "desc",
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
_count: {
select: {
users: true,
subscriptionProducts: true,
},
},
},
});
}
export async function getPortalById(tenantId: string | null, id: string): Promise<PortalWithDetails | null> {
return await db.portal
.findFirstOrThrow({
where: {
tenantId,
OR: [{ id }, { subdomain: id }],
},
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
})
.catch(() => null);
}
export async function getPortalBySubdomain(subdomain: string): Promise<PortalWithDetails | null> {
return await cachified({
key: `portalBySubdomain:${subdomain}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portal.findUnique({
where: { subdomain },
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
});
},
});
}
export async function getPortalByDomain(domain: string): Promise<PortalWithDetails | null> {
return await cachified({
key: `portalByDomain:${domain}`,
ttl: 60 * 60 * 24,
getFreshValue: async () => {
return db.portal.findUnique({
where: { domain },
include: {
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
},
});
},
});
}
export async function createPortal(data: {
tenantId: string | null;
userId: string;
subdomain: string;
domain: string | null;
title: string;
isPublished: boolean;
stripeAccountId: string | null;
metadata: JsonPropertiesValuesDto;
themeColor: string | null;
themeScheme: string | null;
seoTitle: string | null;
seoDescription: string | null;
seoImage: string | null;
seoThumbnail: string | null;
seoTwitterCreator: string | null;
seoTwitterSite: string | null;
seoKeywords: string | null;
authRequireEmailVerification: boolean;
authRequireOrganization: boolean;
authRequireName: boolean;
analyticsSimpleAnalytics: boolean;
analyticsPlausibleAnalytics: boolean;
analyticsGoogleAnalyticsTrackingId: string | null;
brandingLogo: string | null;
brandingLogoDarkMode: string | null;
brandingIcon: string | null;
brandingIconDarkMode: string | null;
brandingFavicon: string | null;
}) {
return await db.portal
.create({
data: {
tenantId: data.tenantId,
createdByUserId: data.userId,
subdomain: data.subdomain,
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
seoTitle: data.seoTitle,
seoDescription: data.seoDescription,
seoImage: data.seoImage,
seoThumbnail: data.seoThumbnail,
seoTwitterCreator: data.seoTwitterCreator,
seoTwitterSite: data.seoTwitterSite,
seoKeywords: data.seoKeywords,
authRequireEmailVerification: data.authRequireEmailVerification,
authRequireOrganization: data.authRequireOrganization,
authRequireName: data.authRequireName,
analyticsSimpleAnalytics: data.analyticsSimpleAnalytics,
analyticsPlausibleAnalytics: data.analyticsPlausibleAnalytics,
analyticsGoogleAnalyticsTrackingId: data.analyticsGoogleAnalyticsTrackingId,
brandingLogo: data.brandingLogo,
brandingLogoDarkMode: data.brandingLogoDarkMode,
brandingIcon: data.brandingIcon,
brandingIconDarkMode: data.brandingIconDarkMode,
brandingFavicon: data.brandingFavicon,
},
})
.then((item) => {
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
return item;
});
}
export async function updatePortal(
before: Portal,
data: {
subdomain?: string;
domain?: string | null;
title?: string;
isPublished?: boolean;
stripeAccountId?: string | null;
metadata?: JsonPropertiesValuesDto;
themeColor?: string | null;
themeScheme?: string | null;
seoTitle?: string | null;
seoDescription?: string | null;
seoImage?: string | null;
seoThumbnail?: string | null;
seoTwitterCreator?: string | null;
seoTwitterSite?: string | null;
seoKeywords?: string | null;
authRequireEmailVerification?: boolean;
authRequireOrganization?: boolean;
authRequireName?: boolean;
analyticsSimpleAnalytics?: boolean;
analyticsPlausibleAnalytics?: boolean;
analyticsGoogleAnalyticsTrackingId?: string | null;
brandingLogo?: string | null;
brandingLogoDarkMode?: string | null;
brandingIcon?: string | null;
brandingIconDarkMode?: string | null;
brandingFavicon?: string | null;
}
) {
const updateResult = await db.portal.updateMany({
where: { id: before.id, tenantId: before.tenantId },
data: {
subdomain: data.subdomain,
domain: data.domain,
title: data.title,
isPublished: data.isPublished,
stripeAccountId: data.stripeAccountId,
metadata: data.metadata,
themeColor: data.themeColor,
themeScheme: data.themeScheme,
seoTitle: data.seoTitle,
seoDescription: data.seoDescription,
seoImage: data.seoImage,
seoThumbnail: data.seoThumbnail,
seoTwitterCreator: data.seoTwitterCreator,
seoTwitterSite: data.seoTwitterSite,
seoKeywords: data.seoKeywords,
authRequireEmailVerification: data.authRequireEmailVerification,
authRequireOrganization: data.authRequireOrganization,
authRequireName: data.authRequireName,
analyticsSimpleAnalytics: data.analyticsSimpleAnalytics,
analyticsPlausibleAnalytics: data.analyticsPlausibleAnalytics,
analyticsGoogleAnalyticsTrackingId: data.analyticsGoogleAnalyticsTrackingId,
brandingLogo: data.brandingLogo,
brandingLogoDarkMode: data.brandingLogoDarkMode,
brandingIcon: data.brandingIcon,
brandingIconDarkMode: data.brandingIconDarkMode,
brandingFavicon: data.brandingFavicon,
},
});
if (updateResult.count !== 1) {
throw new Error("Portal not found for tenant scope.");
}
return await db.portal
.findFirstOrThrow({
where: { id: before.id, tenantId: before.tenantId },
})
.then((item) => {
clearCacheKey(`portalBySubdomain:${before.subdomain}`);
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${before.domain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
const portalServerUrl = loadWebConfig().config.portalServer.url;
if (portalServerUrl) {
// post there with subdomain and domain in the body calling /api/cache/clear
fetch(`${portalServerUrl}/api/cache`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
subdomain: item.subdomain,
domain: item.domain,
}),
})
.then(async (response) => {
portalsDbLogger.info({ response: await response.json() }, "Clearing portal cache succeeded");
})
.catch(async (response) => {
portalsDbLogger.error({ response }, "Clearing portal cache failed");
});
}
return item;
});
}
async function deletePortalWithScope(where: Prisma.PortalWhereInput) {
const item = await db.portal.findFirst({ where });
if (!item) {
throw new Error("Portal not found for scope.");
}
const deleteResult = await db.portal.deleteMany({ where: { ...where, id: item.id } });
if (deleteResult.count !== 1) {
throw new Error("Portal not found for scope.");
}
clearCacheKey(`portalBySubdomain:${item.subdomain}`);
clearCacheKey(`portalByDomain:${item.domain}`);
await db.analyticsUniqueVisitor.deleteMany({ where: { portalId: item.id } }).catch(() => null);
await db.analyticsPageView.deleteMany({ where: { portalId: item.id } }).catch(() => null);
await db.analyticsEvent.deleteMany({ where: { portalId: item.id } }).catch(() => null);
return item;
}
export async function deletePortal({ id, tenantId }: { id: string; tenantId: string | null }) {
return deletePortalWithScope({ id, tenantId });
}
export async function adminDeletePortal(id: string) {
return deletePortalWithScope({ id });
}
export async function countPortals(): Promise<number> {
// Dashboard count — read-only, replica-safe.
return await dbRead.portalUser.count({});
}
@@ -0,0 +1,59 @@
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
export type PortalDto = {
id: string;
tenantId: string | null;
url: string;
subdomain: string;
domain: string | null;
title: string;
isPublished: boolean;
stripeAccountId: string | null;
metadata: JsonPropertiesValuesDto;
theme: {
color: string;
scheme: "light" | "dark";
};
seo: {
title: string | null;
description?: string | null;
image?: string | null;
};
auth: {
requireEmailVerification: boolean;
requireOrganization: boolean;
requireName: boolean;
authMethods: {
emailPassword: {
enabled: boolean;
};
github: {
enabled: boolean;
authorizationURL: string;
};
google: {
enabled: boolean;
};
};
};
subscription: {
required: boolean;
allowSubscribeBeforeSignUp: boolean;
allowSignUpBeforeSubscribe: boolean;
};
analytics: {
simpleAnalytics: boolean;
plausibleAnalytics: boolean;
googleAnalyticsTrackingId?: string | null;
};
branding: {
logo: string | null;
logoDarkMode: string | null;
icon: string | null;
iconDarkMode: string | null;
favicon: string | null;
};
cookies?: {
enabled: boolean;
};
};
@@ -0,0 +1,9 @@
export type PortalUserDto = {
id: string;
createdAt: Date;
portalId: string;
email: string;
firstName: string;
lastName: string;
avatar: string | null;
};
@@ -0,0 +1,41 @@
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,
};
@@ -0,0 +1,8 @@
const includePortalUserSubscriptionProductDetails = {
subscriptionProduct: { include: { features: true } },
prices: { include: { subscriptionPrice: true } },
};
export default {
includePortalUserSubscriptionProductDetails,
};
@@ -0,0 +1,78 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { getRepoRoot, readRepoFile, repoPathExists } from "~/utils/testing/repoPaths";
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",
"apps/web/app/modules/portals/db/portalPages.db.server.ts",
"apps/web/app/modules/portals/db/portalUsers.db.server.ts",
"apps/web/app/modules/sites/db/sites.db.server.ts",
];
function getExportLines(source: string): string[] {
return source
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line.startsWith("export "));
}
describe("Portals/Sites DB ownership boundary", () => {
it("keeps portal/site persistence out of packages/db until the Feature Decision decision", () => {
const exportLines = getExportLines(readFileSync(packagesDbIndexPath, "utf8"));
const forbiddenExportPattern = /\b(?:portal|portals|site|sites)\b/i;
const forbiddenLines = exportLines.filter((line) => forbiddenExportPattern.test(line));
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.",
`Forbidden export lines: ${forbiddenLines.join(" | ") || "none"}`,
].join(" ")
).toEqual([]);
});
it("documents the accepted temporary module-owned DB files", () => {
for (const relativePath of temporaryModuleDbFiles) {
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.`
).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');
}
});
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");
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 }");
expect(sitesSource).toContain("export async function deleteSite(scope: { id: string; tenantId: string })");
});
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");
expect(portalUsersSource).toContain("export async function updatePortalUser(");
expect(portalUsersSource).toContain("portalId: string,");
expect(portalUsersSource).toContain("db.portalUser.updateMany");
expect(portalUsersSource).toContain("where: { portalId, id }");
expect(portalUsersSource).toContain("export async function updatePortalUserPassword(portalId: string, id: string");
expect(portalPagesSource).toContain("export async function updatePortalPage(portalId: string, id: string");
expect(portalPagesSource).toContain("db.portalPage.updateMany");
expect(portalPagesSource).toContain("export async function deletePortalPage(portalId: string, id: string)");
expect(portalPagesSource).toContain("db.portalPage.deleteMany");
});
});
@@ -0,0 +1,107 @@
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/routes/admin/portals.tsx",
"apps/web/app/modules/portals/services/PortalStripe.server.ts",
"apps/web/app/modules/portals/services/StripeConnect.server.ts",
"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",
"apps/web/app/routes/admin/analytics/page-views.tsx",
"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",
".env.fly.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"/);
});
});
@@ -0,0 +1,25 @@
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");
});
});
@@ -0,0 +1,36 @@
import { loadWebConfig, type WebConfig } from "@toolctrl/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,
};
@@ -0,0 +1,200 @@
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,
updatePortalSubscriptionProductStripeId,
updatePortalSubscriptionPriceStripeId,
deletePortalSubscriptionPrice,
deletePortalSubscriptionProduct,
updatePortalSubscriptionProduct,
deletePortalSubscriptionFeatures,
} from "../db/portalSubscriptionProducts.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import PortalSubscriptionServer from "./PortalSubscription.server";
import PortalStripeServer from "./PortalStripe.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[]
) {
// Create stripe product
const stripeProduct = await PortalStripeServer.createStripeProduct({ title: plan.translatedTitle ?? plan.title });
// Save to db
const product = await createPortalSubscriptionProduct({
portalId,
stripeId: stripeProduct?.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,
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) => {
// Create stripe price
const stripePrice = await PortalStripeServer.createStripePrice(stripeProduct?.id ?? "", price);
// Save to db
return await createPortalSubscriptionPrice({
...price,
portalId,
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
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`);
}
const stripeProduct = await PortalStripeServer.createStripeProduct({ title: plan.translatedTitle ?? plan.title });
if (!stripeProduct) {
throw new Error("Could not create product");
}
await updatePortalSubscriptionProductStripeId(portalId, plan.id, {
stripeId: stripeProduct.id,
});
prices.map(async (price) => {
// Create stripe price
const stripePrice = await PortalStripeServer.createStripePrice(stripeProduct?.id ?? "", price);
if (!stripePrice) {
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
}
// Save to db
await updatePortalSubscriptionPriceStripeId(portalId, price.id ?? "", {
stripeId: stripePrice?.id ?? "",
});
});
}
async function updatePlan(portalId: string, plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
await PortalStripeServer.updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
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.stripeId)
.map(async (price) => {
await PortalStripeServer.archiveStripePrice(price.stripeId);
if (price.id) {
await deletePortalSubscriptionPrice(portalId, price.id);
}
return null;
})
);
portalPricingLogger.info({ stripeId: plan.stripeId }, "Deleting Product with Stripe ID");
if (plan.stripeId) {
try {
await PortalStripeServer.deleteStripeProduct(plan.stripeId);
} catch (e: any) {
portalPricingLogger.error({ err: e }, "deleteStripeProduct failed, falling back to archive");
await PortalStripeServer.archiveStripeProduct(plan.stripeId);
}
}
if (plan.id) {
await deletePortalSubscriptionProduct(portalId, plan.id);
}
}
export default {
createPlans,
createPlan,
syncPlan,
updatePlan,
deletePlan,
};
@@ -0,0 +1,562 @@
import type Stripe from "stripe";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { getAllPortalSubscriptionProducts } from "../db/portalSubscriptionProducts.db.server";
import { cachified } from "~/utils/cache.server";
import PortalSubscriptionServer from "./PortalSubscription.server";
import { PortalDto } from "../dtos/PortalDto";
import { getAbsoluteCurrentUrl } from "~/utils/url.server";
import { getStripeClient } from "~/utils/stripe.server";
import { createScopedLogger } from "~/utils/logger.server";
const portalStripeLogger = createScopedLogger("portals.stripe");
const stripe = new Proxy({} as Stripe, {
get(_target, property, receiver) {
return Reflect.get(getStripeClient(), property, receiver);
},
});
async function createStripeCheckoutSession(data: {
portal: PortalDto;
subscriptionProduct: SubscriptionProductDto;
customer?: string;
line_items: { price: string; quantity?: number }[];
mode: "payment" | "setup" | "subscription";
success_url: string;
cancel_url: string;
freeTrialDays?: number;
coupon?: string;
promo_code?: string;
referral?: string | null;
}) {
if (!data.portal.stripeAccountId) {
throw new Error("Stripe account not connected");
}
const discounts: { coupon?: string; promotion_code?: string }[] = [];
if (data.coupon) {
discounts.push({ coupon: data.coupon });
} else if (data.promo_code) {
discounts.push({ promotion_code: data.promo_code });
}
let billing_address_collection: "auto" | "required" | undefined = undefined;
if (data.subscriptionProduct.billingAddressCollection === "required") {
billing_address_collection = "required";
} else if (data.subscriptionProduct.billingAddressCollection === "auto") {
billing_address_collection = "auto";
}
let client_reference_id: string | undefined = undefined;
if (data.referral) {
client_reference_id = data.referral;
}
return await stripe.checkout.sessions
.create({
discounts,
customer: data.customer,
line_items: data.line_items,
mode: data.mode,
success_url: data.success_url,
cancel_url: data.cancel_url,
customer_creation: data.mode === "payment" && !data.customer ? "always" : undefined,
payment_method_collection: data.mode === "subscription" ? "if_required" : undefined,
subscription_data:
data.mode === "subscription"
? {
trial_period_days: data.freeTrialDays,
transfer_data: {
destination: data.portal.stripeAccountId,
},
}
: undefined,
billing_address_collection,
client_reference_id,
payment_intent_data:
data.mode == "payment"
? {
application_fee_amount: 0,
transfer_data: {
destination: data.portal.stripeAccountId,
},
}
: undefined,
})
.catch((e) => {
portalStripeLogger.error({ err: e }, "Portal stripe checkout session creation failed");
throw e;
});
}
async function createStripeSetupSession(request: Request, customer: string) {
const currentUrl = getAbsoluteCurrentUrl(request);
return await stripe.checkout.sessions.create({
customer,
success_url: `${currentUrl}?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: currentUrl,
mode: "setup",
payment_method_types: ["card"],
});
}
async function deleteStripePaymentMethod(id: string) {
return await stripe.paymentMethods.detach(id);
}
async function getStripeSession(id: string) {
return await stripe.checkout.sessions
.retrieve(id, {
expand: ["line_items"],
})
.catch(() => {
return null;
});
}
async function cancelStripeSubscription(subscriptionId: string) {
return await stripe.subscriptions.cancel(subscriptionId).catch((e: any) => {
portalStripeLogger.warn({ err: e }, "Could not cancel portal stripe subscription");
});
}
async function reactivateStripeSubscription(subscriptionId: string) {
return await stripe.subscriptions
.update(subscriptionId, {
cancel_at_period_end: false,
})
.catch((e: any) => {
portalStripeLogger.warn({ err: e }, "Could not reactivate portal stripe subscription");
});
}
async function getStripeSubscription(id: string) {
try {
return await stripe.subscriptions.retrieve(id);
} catch (e) {
return null;
}
}
async function createStripeSubscription(customer: string, price: string, trial_end?: number) {
return await stripe.subscriptions.create({
customer,
items: [
{
price,
},
],
trial_end,
});
}
async function getStripeInvoices(id: string | null) {
if (!id) {
return [];
}
try {
return (
await stripe.invoices.list({
customer: id,
})
).data;
} catch (e) {
return [];
}
}
async function getStripePaymentIntents(id: string | null, status?: Stripe.PaymentIntent.Status) {
if (!id) {
return [];
}
try {
let items = (
await stripe.paymentIntents.list({
customer: id,
})
).data;
if (status) {
items = items.filter((item) => item.status === status);
}
return items;
} catch (e) {
return [];
}
}
async function getStripePaymentIntent(id: string) {
try {
return await stripe.paymentIntents.retrieve(id);
} catch (e) {
return null;
}
}
async function getStripeUpcomingInvoice(id: string | null) {
if (!id) {
return null;
}
try {
return await stripe.invoices.createPreview({
customer: id,
});
} catch (e) {
return null;
}
}
async function getStripePaymentMethods(customer: string | null) {
if (!customer) {
return [];
}
try {
return (
await stripe.paymentMethods.list({
customer,
type: "card",
})
).data;
} catch (e) {
return [];
}
}
async function createStripeCustomer(email: string, name: string, stripeAccount: string) {
let customer = await stripe.customers
.create({
stripeAccount,
})
.catch((e: any) => {
portalStripeLogger.error({ err: e }, "Portal createStripeCustomer create failed");
return null;
});
if (customer) {
customer = await stripe.customers
.update(customer.id, {
email,
name,
})
.catch((e: any) => {
portalStripeLogger.error({ err: e }, "Portal createStripeCustomer update failed");
return null;
});
}
return customer;
}
async function deleteStripeCustomer(id: string) {
return await stripe.customers.del(id);
}
async function updateStripeCustomerPaymentMethod(id: string, default_payment_method: string) {
return await stripe.customers.update(id, {
invoice_settings: { default_payment_method },
});
}
async function createStripeProduct(data: { title: string }) {
return await stripe.products.create({
name: data.title,
});
}
async function updateStripeProduct(id: string, data: { title: string }) {
return await stripe.products
.update(id, {
name: data.title,
})
.catch((error) => {
// console.error(error);
// ignore
});
}
async function createStripePrice(productId: string, data: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }) {
if (!productId) {
return undefined;
}
let recurring:
| {
interval: "day" | "week" | "month" | "year";
trial_period_days: number | undefined;
interval_count?: number;
}
| undefined = undefined;
switch (data.billingPeriod) {
case SubscriptionBillingPeriod.MONTHLY:
recurring = { interval: "month", trial_period_days: data.trialDays };
break;
case SubscriptionBillingPeriod.QUARTERLY:
recurring = { interval: "month", interval_count: 3, trial_period_days: data.trialDays };
break;
case SubscriptionBillingPeriod.SEMI_ANNUAL:
recurring = { interval: "month", interval_count: 6, trial_period_days: data.trialDays };
break;
case SubscriptionBillingPeriod.WEEKLY:
recurring = { interval: "week", trial_period_days: data.trialDays };
break;
case SubscriptionBillingPeriod.YEARLY:
recurring = { interval: "year", trial_period_days: data.trialDays };
break;
case SubscriptionBillingPeriod.DAILY:
recurring = { interval: "day", trial_period_days: data.trialDays };
break;
}
return await stripe.prices.create({
unit_amount: Math.round(data.price * 100),
currency: data.currency,
recurring,
product: productId,
active: true,
});
}
async function deleteStripeProduct(productId: string) {
return await stripe.products.del(productId);
}
async function archiveStripeProduct(productId: string) {
return await stripe.products
.update(productId, {
active: false,
})
.catch(() => {
// ignore
});
}
async function archiveStripePrice(productId: string) {
return await stripe.prices
.update(productId, {
active: false,
})
.catch(() => {
// ignore
});
}
async function getStripeCoupon(id: string) {
return await stripe.coupons.retrieve(id, {
expand: ["applies_to"],
});
}
async function getStripePromotionCode(id: string) {
return await stripe.promotionCodes.retrieve(id);
}
async function getStripeCustomer(id: string | null) {
if (!id) {
return null;
}
return await stripe.customers.retrieve(id, {
expand: ["invoice_settings"],
});
}
async function getOpenInvoices(id: string) {
return await cachified({
key: `stripe:openInvoices:${id}`,
ttl: 1000 * 60 * 60 * 24, // 24 hours
getFreshValue: () =>
stripe.invoices.list({
customer: id,
status: "open",
}),
});
}
async function createCustomerPortalSession(request: Request, id: string) {
return await stripe.billingPortal.sessions.create({
customer: id,
return_url: getAbsoluteCurrentUrl(request),
});
}
async function getAllStripePayments() {
return cachified({
key: `stripe:payments`,
ttl: 1000 * 60 * 60 * 24, // 24 hours
getFreshValue: async () => {
let items: Stripe.PaymentIntent[] = [];
let hasMore = true;
let startingAfter: string | undefined = undefined;
let max = 10;
while (hasMore) {
const result: Stripe.ApiList<Stripe.PaymentIntent> = await stripe.paymentIntents.list({
limit: 100,
starting_after: startingAfter,
expand: ["data.charges"],
});
items = items.concat(result.data);
hasMore = result.has_more;
startingAfter = result.data[result.data.length - 1].id;
max--;
if (max <= 0) {
break;
}
}
return items;
},
});
}
/**
* Portal-scoped inverted map `paymentIntentId → Invoice`. See
* `getAllStripeInvoicesByPaymentIntent` in `stripe.server.ts` for the
* rationale (Stripe 19 removed `PaymentIntent.invoice`).
*/
async function getAllStripeInvoicesByPaymentIntent(): Promise<Map<string, Stripe.Invoice>> {
return cachified({
key: `stripe:portal:invoicesByPaymentIntent`,
ttl: 1000 * 60 * 60 * 24, // 24 hours
getFreshValue: async () => {
const map = new Map<string, Stripe.Invoice>();
let hasMore = true;
let startingAfter: string | undefined = undefined;
let max = 10;
while (hasMore) {
const result: Stripe.ApiList<Stripe.Invoice> = await stripe.invoices.list({
limit: 100,
starting_after: startingAfter,
});
for (const invoice of result.data) {
// Stripe 19 removed Invoice.payment_intent. The id now lives on
// each Invoice.payments[].payment.payment_intent (one invoice
// can have multiple payment attempts; we index by all).
for (const invoicePayment of invoice.payments?.data ?? []) {
const ref = invoicePayment.payment.payment_intent;
const piId = typeof ref === "string" ? ref : ref?.id;
if (piId) {
map.set(piId, invoice);
}
}
}
hasMore = result.has_more;
startingAfter = result.data[result.data.length - 1]?.id;
max--;
if (max <= 0) {
break;
}
}
return map;
},
});
}
export type StripeRevenueByProductPriceCurrency = {
product: string;
billingPeriod: SubscriptionBillingPeriod;
currency: string;
revenueInCurrency: number;
count: number;
countPercentage: number;
revenueUsd: number;
revenuePercentageUsd: number;
};
async function getStripeRevenueByProductPriceCurrency(portalId: string): Promise<StripeRevenueByProductPriceCurrency[]> {
const items: StripeRevenueByProductPriceCurrency[] = [];
const allProducts = await getAllPortalSubscriptionProducts(portalId);
const [payments, invoicesByPaymentIntent] = await Promise.all([
getAllStripePayments(),
getAllStripeInvoicesByPaymentIntent(),
]);
payments.forEach((payment) => {
if (payment.status !== "succeeded") {
return;
}
// Stripe 19 removed PaymentIntent.invoice. Traverse via the
// inverted map built from Invoice.payment_intent instead.
const invoice = invoicesByPaymentIntent.get(payment.id);
const lines = invoice?.lines?.data[0];
// Stripe 19 dropped InvoiceLineItem.plan; the (price, product)
// identifiers now live on InvoiceLineItem.pricing.price_details.
const pricing = lines?.pricing;
const amount = payment.amount / 100;
const currency = payment.currency;
const priceId = pricing?.price_details?.price;
const productId = pricing?.price_details?.product;
const product = allProducts.find((x) => x.stripeId === productId);
let productName = "?";
let billingPeriod: SubscriptionBillingPeriod = SubscriptionBillingPeriod.DAILY;
if (product) {
productName = product.title;
}
const price = product?.prices.find((x) => x.stripeId === priceId);
if (price) {
billingPeriod = price.billingPeriod;
}
const existing = items.find((x) => x.product === productName && x.currency === currency && x.billingPeriod === billingPeriod);
let revenueUsd = amount;
if (currency !== "usd") {
revenueUsd = PortalSubscriptionServer.convertToCurrency({
from: currency,
to: "usd",
price: amount,
});
}
if (existing) {
existing.revenueInCurrency += amount;
existing.revenueUsd += revenueUsd;
existing.count++;
} else {
items.push({
product: productName,
billingPeriod,
currency,
revenueInCurrency: amount,
revenueUsd,
count: 1,
countPercentage: 0,
revenuePercentageUsd: 0,
});
}
});
// process percentages
const totalRevenue = items.reduce((x, y) => x + y.revenueUsd, 0);
const totalCount = items.reduce((x, y) => x + y.count, 0);
items.forEach((item) => {
item.countPercentage = item.count / totalCount;
item.revenuePercentageUsd = item.revenueUsd / totalRevenue;
});
// sort by revenue desc
return items.sort((x, y) => (x.revenueUsd > y.revenueUsd ? -1 : 1));
}
export default {
createStripeCheckoutSession,
createStripeSetupSession,
deleteStripePaymentMethod,
getStripeSession,
cancelStripeSubscription,
reactivateStripeSubscription,
getStripeSubscription,
createStripeSubscription,
getStripeInvoices,
getStripePaymentIntents,
getStripePaymentIntent,
getStripeUpcomingInvoice,
getStripePaymentMethods,
createStripeCustomer,
deleteStripeCustomer,
updateStripeCustomerPaymentMethod,
createStripeProduct,
updateStripeProduct,
createStripePrice,
deleteStripeProduct,
archiveStripeProduct,
archiveStripePrice,
getStripeCoupon,
getStripePromotionCode,
getStripeCustomer,
getOpenInvoices,
createCustomerPortalSession,
getAllStripePayments,
getStripeRevenueByProductPriceCurrency,
};
@@ -0,0 +1,31 @@
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,
};
@@ -0,0 +1,58 @@
import type Stripe from "stripe";
import { getStripeClient } from "~/utils/stripe.server";
const stripe = new Proxy({} as Stripe, {
get(_target, property, receiver) {
return Reflect.get(getStripeClient(), property, receiver);
},
});
async function getStripeAccount(id: string) {
return await stripe.accounts.retrieve(id);
}
async function createStripeAccount({ email, country, metadata }: { email: string; country: string; metadata?: { [key: string]: string | number } }) {
return await stripe.accounts.create({
type: "standard",
email,
country,
// capabilities: {
// card_payments: {
// requested: true,
// },
// transfers: {
// requested: true,
// },
// },
metadata,
});
}
async function createStripeAccountLink({ account, refresh_url, return_url }: { account: string; refresh_url: string; return_url: string }) {
return await stripe.accountLinks.create({
account,
refresh_url,
return_url,
type: "account_onboarding",
});
}
async function deleteStripeAccount(id: string) {
return await stripe.accounts.del(id);
}
async function getStripeAccountProducts(id: string) {
return (
await stripe.products.list({
stripeAccount: id,
})
).data;
}
export default {
getStripeAccount,
createStripeAccount,
createStripeAccountLink,
deleteStripeAccount,
getStripeAccountProducts,
};
@@ -0,0 +1,9 @@
import { PortalDto } from "../dtos/PortalDto";
function getUrl(item: PortalDto, path: string) {
return `${item.url}${path}`;
}
export default {
getUrl,
};
@@ -0,0 +1,56 @@
const stripeConnectCountries = [
{ value: "AU", name: "Australia" },
{ value: "LV", name: "Latvia" },
{ value: "AT", name: "Austria" },
{ value: "LT", name: "Lithuania" },
{ value: "BE", name: "Belgium" },
{ value: "LU", name: "Luxembourg" },
{ value: "MY", name: "Malaysia" },
{ value: "BG", name: "Bulgaria" },
{ value: "BR", name: "Brazil" },
{ value: "MT", name: "Malta" },
{ value: "CA", name: "Canada" },
{ value: "MX", name: "Mexico" },
{ value: "CY", name: "Cyprus" },
{ value: "NL", name: "Netherlands" },
{ value: "CZ", name: "Czech Republic" },
{ value: "NZ", name: "New Zealand" },
{ value: "DK", name: "Denmark" },
{ value: "NO", name: "Norway" },
{ value: "EE", name: "Estonia" },
{ value: "PL", name: "Poland" },
{ value: "FI", name: "Finland" },
{ value: "PT", name: "Portugal" },
{ value: "FR", name: "France" },
{ value: "RO", name: "Romania" },
{ value: "DE", name: "Germany" },
{ value: "SG", name: "Singapore" },
{ value: "GR", name: "Greece" },
{ value: "SK", name: "Slovakia" },
{ value: "HK", name: "Hong Kong" },
{ value: "SI", name: "Slovenia" },
{ value: "HU", name: "Hungary" },
{ value: "ES", name: "Spain" },
{ value: "SE", name: "Sweden" },
{ value: "IN", name: "India" },
{ value: "IE", name: "Ireland" },
{ value: "CH", name: "Switzerland" },
{ value: "IT", name: "Italy" },
{ value: "GB", name: "United Kingdom" },
{ value: "JP", name: "Japan" },
{ value: "US", name: "United States" },
{ value: "AE", name: "United Arab Emirates" },
];
function getLocalizedStripeConnectCountries(locale: string | undefined) {
const displayNames = typeof Intl.DisplayNames === "function" ? new Intl.DisplayNames([locale || "en"], { type: "region" }) : null;
return stripeConnectCountries.map((country) => ({
...country,
name: displayNames?.of(country.value) ?? country.name,
}));
}
export default {
stripeConnectCountries,
getLocalizedStripeConnectCountries,
};
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { redactAnalyticsCookie, redactAnalyticsUrl } from "./analytics-redaction";
describe("analytics redaction", () => {
it("removes query strings from absolute and relative URLs", () => {
expect(redactAnalyticsUrl("https://example.com/path?token=secret&email=a@example.com#section")).toBe("https://example.com/path#section");
expect(redactAnalyticsUrl("/checkout?session_id=secret")).toBe("/checkout");
});
it("does not expose raw visitor cookies", () => {
expect(redactAnalyticsCookie("abcdef123456")).toBe("abcde...");
expect(redactAnalyticsCookie("abc")).toBe("[redacted]");
});
});
@@ -0,0 +1,21 @@
export function redactAnalyticsUrl(value: string | null): string | null {
if (!value) {
return value;
}
try {
const url = new URL(value);
return `${url.origin}${url.pathname}${url.hash}`;
} catch {
try {
const url = new URL(value, "https://redaction.local");
return `${url.pathname}${url.hash}`;
} catch {
return value.split("?")[0] ?? value;
}
}
}
export function redactAnalyticsCookie(value: string): string {
return value.length <= 5 ? "[redacted]" : `${value.slice(0, 5)}...`;
}