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,243 @@
import Constants from "~/application/Constants";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { EntitiesTemplateDto, TemplateEntityDto, TemplateEntityViewDto } from "~/modules/templates/EntityTemplateDto";
import getMaxEntityOrder, { createEntity, EntityWithDetails, findEntityByName, getEntityByName } from "../../db/entities/entities.db.server";
import { createEntityRelationship, EntityRelationshipWithDetails } from "../../db/entities/entityRelationships.db.server";
import { createEntityView, updateEntityViewProperties, updateEntityViewFilters, updateEntityViewSort } from "../../db/entities/entityViews.db.server";
import { createProperty, updatePropertyOptions, updatePropertyAttributes, getEntityPropertyByName } from "../../db/entities/properties.db.server";
import { createEntityPermissions } from "../../db/permissions/permissions.db.server";
import EntityViewHelper from "../../helpers/EntityViewHelper";
import OrderHelper from "../../helpers/OrderHelper";
import { mapToEntityTemplateType } from "../../helpers/PropertyHelper";
export async function validateEntitiesFromTemplate(template: EntitiesTemplateDto) {
if (template.entities.length === 0) {
throw Error("Invalid configuration");
}
await Promise.all(
template.entities.map(async (entity) => {
const existingEntity = await findEntityByName({ tenantId: null, name: entity.name });
if (existingEntity) {
throw Error("Entity already exists: " + entity.name);
}
if (!entity.properties || entity.properties.length === 0) {
throw Error("Entity has no properties: " + entity.name);
}
entity.properties.forEach((property) => {
if (property.name.includes(" ")) {
throw Error("Property names cannot contain spaces: " + property.name);
}
if (property.name.includes("-")) {
throw Error("Property names cannot contain '-': " + property.name);
}
});
})
);
}
export async function importEntitiesFromTemplate({ template, createdByUserId }: { template: EntitiesTemplateDto; createdByUserId: string }) {
const maxEntityOrder = await getMaxEntityOrder();
const createdEntities = await Promise.all(
template.entities.map(async (entity, idx) => {
const createdEntity = await createEntity(
{
name: entity.name,
slug: entity.slug,
prefix: entity.prefix,
title: entity.title,
titlePlural: entity.titlePlural,
isAutogenerated: entity.isAutogenerated ?? true,
hasApi: entity.hasApi ?? true,
icon: entity.icon ?? "",
active: entity.active ?? true,
type: entity.type ?? DefaultEntityTypes.All,
showInSidebar: entity.showInSidebar ?? true,
hasTags: entity.hasTags ?? true,
hasComments: entity.hasComments ?? true,
hasTasks: entity.hasTasks ?? false,
hasActivity: entity.hasActivity !== undefined ? entity.hasActivity : true,
hasBulkDelete: entity.hasBulkDelete !== undefined ? entity.hasBulkDelete : false,
hasViews: entity.hasViews !== undefined ? entity.hasViews : true,
defaultVisibility: entity.defaultVisibility ?? DefaultVisibility.Tenant,
onCreated: entity.onCreated ?? "redirectToOverview",
onEdit: entity.onEdit ?? "editRoute",
},
maxEntityOrder + idx + 1
);
// eslint-disable-next-line no-console
console.log("Entity created", createdEntity.name);
if (!createdEntity) {
throw new Error("Unable to create entity: " + JSON.stringify(entity));
}
await createEntityPermissions(createdEntity);
const newEntity = await getEntityByName({ tenantId: null, name: createdEntity.name });
const propertyOrder = OrderHelper.getNextOrder(newEntity.properties);
const properties = await Promise.all(
entity.properties.map(async (property, idxProperty) => {
let type: PropertyType | undefined = undefined;
if (property.type === "string") {
type = PropertyType.TEXT;
} else if (property.type === "number") {
type = PropertyType.NUMBER;
} else if (property.type === "boolean") {
type = PropertyType.BOOLEAN;
} else if (property.type === "date") {
type = PropertyType.DATE;
} else if (property.type === "media") {
type = PropertyType.MEDIA;
} else if (property.type === "select") {
type = PropertyType.SELECT;
} else if (property.type === "multiSelect") {
type = PropertyType.MULTI_SELECT;
} else if (property.type === "multiText") {
type = PropertyType.MULTI_TEXT;
} else if (property.type === "rangeNumber") {
type = PropertyType.RANGE_NUMBER;
} else if (property.type === "rangeDate") {
type = PropertyType.RANGE_DATE;
} else if (property.type === "formula") {
type = PropertyType.FORMULA;
} else {
throw new Error("Invalid property type: " + property.type);
}
const createdProperty = await createProperty({
entityId: createdEntity.id,
name: property.name,
title: property.title,
type,
subtype: property.subtype ?? null,
order: propertyOrder + idxProperty,
isDefault: false,
isRequired: property.isRequired ?? false,
isHidden: false,
isDisplay: property.isDisplay ?? false,
isReadOnly: property.isReadOnly ?? false,
canUpdate: property.canUpdate !== undefined ? property.canUpdate : true,
showInCreate: property.showInCreate ?? true,
formulaId: null,
tenantId: property.tenantId ?? null,
});
if (property.options) {
await updatePropertyOptions(
createdProperty.id,
property.options.map((item, idxOption) => {
return {
order: idxOption + 1,
value: item.value,
name: item.name,
color: item.color === undefined ? undefined : item.color,
};
})
);
}
if (property.attributes) {
await updatePropertyAttributes(
createdProperty.id,
property.attributes.map((item) => {
return {
value: item.value,
name: item.name,
};
})
);
}
return createdProperty;
})
);
// Views
if (entity.views) {
await Promise.all(
entity.views.map(async (view, idx) => {
const groupByProperty = properties.find((f) => f.name === view.groupByProperty);
if (view.tenantId) {
return;
}
const entityView = await createEntityView({
order: idx + 1,
entityId: createdEntity.id,
layout: view.layout,
name: view.name,
title: view.title,
isDefault: view.isDefault ?? false,
tenantId: null,
userId: view.userId ?? null,
createdByUserId,
isSystem: view.isSystem ?? false,
pageSize: view.pageSize ?? Constants.DEFAULT_PAGE_SIZE,
groupByPropertyId: groupByProperty?.id ?? null,
});
let viewProperties: { propertyId: string | null; order: number; name: string }[] = view.properties
? await Promise.all(
view.properties.map(async (prop, idxProp) => {
const property = await getEntityPropertyByName(createdEntity.id, prop);
return {
order: idxProp + 1,
propertyId: property?.id ?? null,
name: prop,
};
})
)
: [];
if (viewProperties.length === 0) {
viewProperties = newEntity.properties.map((item) => {
return {
propertyId: item.id,
order: item.order,
name: item.name,
};
});
}
const viewFilters: { name: string; condition: string; value: string; match: "and" | "or" }[] =
view.filters?.map((filter) => {
return {
match: filter.match ?? "and",
name: filter.name,
condition: filter.condition,
value: filter.value,
};
}) ?? [];
const viewSort: { name: string; asc: boolean; order: number }[] =
view.sort?.map((sort, idxSort) => {
return {
name: sort.name,
asc: sort.asc,
order: idxSort + 1,
};
}) ?? [];
await updateEntityViewProperties(entityView.id, viewProperties);
await updateEntityViewFilters(entityView.id, viewFilters);
await updateEntityViewSort(entityView.id, viewSort);
})
);
}
return createdEntity;
})
);
if (createdEntities.length > 0 && template.relationships) {
await Promise.all(
template.relationships.map(async (relationship) => {
const fromEntity = await getEntityByName({ tenantId: null, name: relationship.parent });
const toEntity = await getEntityByName({ tenantId: null, name: relationship.child });
return await createEntityRelationship({
parentId: fromEntity.id,
childId: toEntity.id,
order: relationship.order ?? 0,
title: relationship.title ?? null,
type: relationship.type ?? "one-to-many",
required: relationship.required ?? false,
cascade: false,
readOnly: relationship.readOnly ?? false,
hiddenIfEmpty: relationship.hiddenIfEmpty !== undefined ? relationship.hiddenIfEmpty : false,
childEntityViewId: null,
parentEntityViewId: null,
});
})
);
}
return createdEntities;
}
@@ -0,0 +1,87 @@
/**
* Feature-flags eval-cache (two-tier). Mirrors subscriptionCache pattern.
*
* L1 = in-process Map for sub-microsecond reads on the render hot-path.
* L2 = SharedStore (Redis or in-memory adapter) for cross-replica reuse.
* Pub/sub channel `shared-store:<ns>:ch:cache:feature-flags:invalidate`
* fans out flag-mutation events — every replica flushes its L1 on
* receipt so the next eval re-reads from DB.
*
* Bootstrap: call `subscribeFeatureFlagCache()` exactly once during web
* boot (idempotent). On flag mutation (admin save) the action handler
* calls `getFeatureFlagCache().invalidateFlag(flagName)` which publishes
* a sentinel — peer L1s flush wholesale (cheap, mutations are rare).
*/
import {
FEATURE_FLAGS_INVALIDATION_CHANNEL,
createFlagEvalCache,
type EvaluateFlagResult,
type FlagEvalCache,
} from "@toolctrl/feature-flags";
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("feature-flags-cache");
const TTL_SECONDS_DEFAULT = 60; // spec: per-ctx eval result cached 60s.
let tierSingleton: TwoTierCache<EvaluateFlagResult> | null = null;
let cacheSingleton: FlagEvalCache | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
function ttlSecondsFromEnv(): number {
const raw = process.env.FEATURE_FLAGS_CACHE_TTL_SECONDS;
if (!raw) return TTL_SECONDS_DEFAULT;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
return Math.floor(parsed);
}
function getTier(): TwoTierCache<EvaluateFlagResult> {
if (tierSingleton) return tierSingleton;
tierSingleton = createTwoTierCache<EvaluateFlagResult>({
store: getSharedStore(),
namespace: "feature-flags",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
});
return tierSingleton;
}
export function getFeatureFlagCache(): FlagEvalCache {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createFlagEvalCache(getTier());
return cacheSingleton;
}
/**
* Start the subscriber for this process. Idempotent. The handler
* flushes the entire L1 on any invalidation receipt, which is the
* correct trade-off because flag mutations are rare and L1 is small.
*/
export async function subscribeFeatureFlagCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const tier = getTier();
subscribeDisposer = await tier.subscribe(() => {
// Any invalidation drops everything — see cache.ts comment.
tier.flushLocal();
});
log.info({ namespace: "feature-flags", channel: FEATURE_FLAGS_INVALIDATION_CHANNEL }, "feature-flag cache subscriber started");
return subscribeDisposer;
}
/** Test seam. */
export function __resetFeatureFlagCacheForTests(): void {
tierSingleton = null;
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -0,0 +1,96 @@
/**
* Server-side evaluateFlag bridge.
*
* Wires the Prisma FeatureFlag table into the package-level
* `evaluateFlag` (`@toolctrl/feature-flags`). Caller passes a request
* + an EvaluationContext; we look up the row by name (caches L2-first
* via the feature-flag eval cache), run the pure evaluator and
* memo-cache the typed result for 60s.
*
* Multi-key lookup: the package-level loader is keyed by `name`, but
* dependency-resolution calls back with a parent-flag *id*. We
* therefore accept either via a single Prisma `OR` query so the
* second-level lookup keeps working.
*/
import {
evaluateFlag as evaluatePackage,
getFeatureFlagVariant as packageGetVariant,
type EvaluateFlagResult,
type FlagLoader,
type StoredFeatureFlag,
} from "@toolctrl/feature-flags";
import type { EvaluationContext } from "@toolctrl/feature-flags";
import type { FeatureFlag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { getFeatureFlagCache } from "./featureFlagCache.server";
function toStored(row: FeatureFlag | null): StoredFeatureFlag | null {
if (!row) return null;
return {
id: row.id,
name: row.name,
enabled: row.enabled,
rules: row.rules ?? null,
variants: Array.isArray(row.variants) ? row.variants : [],
enabledFrom: row.enabledFrom ?? null,
enabledUntil: row.enabledUntil ?? null,
parentFlagId: row.parentFlagId ?? null,
};
}
const createLoader = (): FlagLoader => async (key: string) => {
// OR-lookup so dependency-resolution (which calls back with an id)
// works against the same loader.
const row = await db.featureFlag.findFirst({
where: { OR: [{ name: key }, { id: key }] },
});
return toStored(row);
};
/**
* Evaluate a single flag with full cache, dependency-resolution, and
* variant-selection. Returns the structured `{ enabled, variant?, reason }`.
*/
export async function evaluateFlagForContext(
name: string,
ctx: EvaluationContext,
): Promise<EvaluateFlagResult> {
const cache = getFeatureFlagCache();
const cached = await cache.get(name, ctx);
if (cached) return cached;
const result = await evaluatePackage(name, ctx, { load: createLoader() });
await cache.set(name, ctx, result);
return result;
}
/** Variant-only convenience wrapper. */
export async function getFeatureFlagVariantForContext(
name: string,
ctx: EvaluationContext,
) {
return packageGetVariant(name, ctx, { load: createLoader() });
}
/**
* Evaluate several flags in parallel. Used by root-loader SSR
* hydration so the React tree can read flags synchronously through
* a single context provider without re-fetching per call.
*/
export async function evaluateFlagsForContext(
names: readonly string[],
ctx: EvaluationContext,
): Promise<Record<string, EvaluateFlagResult>> {
const entries = await Promise.all(
names.map(async (n) => [n, await evaluateFlagForContext(n, ctx)] as const),
);
return Object.fromEntries(entries);
}
/**
* Drop every cached eval for a flag — call after admin mutations.
* Publishes on the feature-flags:invalidate channel.
*/
export async function invalidateFlagCache(flagName: string): Promise<void> {
await getFeatureFlagCache().invalidateFlag(flagName);
}
@@ -0,0 +1,85 @@
/**
* Request-bound bridge into the v2 evaluator.
*
* The legacy {@link FeatureFlagsService.hasFeatureFlag} accepts
* `(request, params, flagName)`. The v2 engine accepts an
* {@link EvaluationContext}. This helper assembles the context from
* the request (tenantId, userId) and delegates to
* `evaluateFlagForContext`, so existing call-sites can switch
* imports without changing their signatures.
*
* Returns `{ enabled, variant?, reason }` — call-sites that only
* care about the boolean use the convenience `isFeatureFlagEnabled`
* wrapper. Existing v1 routes that already build their own context
* via `FeatureFlagsService.hasFeatureFlag` keep working in parallel;
* v2 is opt-in.
*/
import { Params } from "react-router";
import type { EvaluateFlagResult } from "@toolctrl/feature-flags";
import { evaluateFlagForContext, evaluateFlagsForContext } from "./featureFlagEvaluator.server";
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
export interface RequestContextInput {
request: Request;
params: Params;
}
export async function evaluateFlagForRequest(
flagName: string,
{ request, params }: RequestContextInput,
): Promise<EvaluateFlagResult> {
const [tenantId, userInfo] = await Promise.all([
getTenantIdOrNull({ request, params }),
getUserInfo(request),
]);
return evaluateFlagForContext(flagName, {
flagName,
tenantId: tenantId ?? null,
userId: userInfo.userId || null,
});
}
/** Boolean shortcut for callers migrating from `hasFeatureFlag`. */
export async function isFeatureFlagEnabled(
flagName: string,
input: RequestContextInput,
): Promise<boolean> {
const result = await evaluateFlagForRequest(flagName, input);
return result.enabled;
}
/**
* SSR-hydration helper — return the names of every flag whose v2
* evaluation resolves `enabled` for the current request context.
*
* Replaces the v1 `FeatureFlagsService.getCurrentFeatureFlags` which
* was scoped + filtered through `FeatureFlagsFiltersService` (a
* separate filter engine that ran *outside* the v2 evaluator). The v2
* port skips the legacy filter table: callers are responsible for
* porting any per-flag filter rows into v2 rules in
* `FeatureFlag.rules` (see `docs/improvement-plan/...`). Until that
* data migration lands, results reflect the flag's bare
* `enabled=true` boolean modulo v2 rule evaluation.
*/
export async function getCurrentEnabledFlagNames(input: RequestContextInput): Promise<string[]> {
const [tenantId, userInfo, flags] = await Promise.all([
getTenantIdOrNull(input),
getUserInfo(input.request),
getAllFeatureFlags(),
]);
const names = flags
.map((f) => f.name ?? f.key ?? "")
.filter((n) => n.length > 0);
if (names.length === 0) return [];
const results = await evaluateFlagsForContext(names, {
flagName: "*",
tenantId: tenantId ?? null,
userId: userInfo.userId || null,
});
return Object.entries(results)
.filter(([, r]) => r.enabled)
.map(([n]) => n);
}
@@ -0,0 +1,652 @@
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { SubscriptionProductDto } from "../../../application/dtos/subscriptions/SubscriptionProductDto";
import {
createSubscriptionProduct,
createSubscriptionPrice,
createSubscriptionFeature,
updateSubscriptionProductStripeId,
updateSubscriptionPriceStripeId,
deleteSubscriptionPrice,
deleteSubscriptionProduct,
updateSubscriptionProduct,
deleteSubscriptionFeatures,
deleteSubscriptionUsageBasedTier,
deleteSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedPrice,
createSubscriptionUsageBasedTier,
getSubscriptionPriceByStripeId,
getSubscriptionUsageBasedPriceByStripeId,
getSubscriptionProduct,
getAllSubscriptionProducts,
} from "../../db/subscriptionProducts.db.server";
import {
createStripeProduct,
createStripePrice,
archiveStripePrice,
deleteStripeProduct,
updateStripeProduct,
createStripeUsageBasedPrice,
archiveStripeProduct,
getStripeSession,
createStripeCustomer,
createStripeSubscription,
} from "../../stripe.server";
import { CheckoutSessionStatus, SubscriptionPrice, SubscriptionUsageBasedPrice } from "@toolctrl/db/prisma-browser";
import Stripe from "stripe";
import { getOrPersistTenantSubscription, updateTenantSubscriptionCustomerId } from "../../db/tenantSubscriptions.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { getCheckoutSessionStatus, updateCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { SubscriptionUsageBasedPriceDto } from "~/application/dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { TFunction } from "i18next";
import { TenantTypesApi } from "../../api/.server/TenantTypesApi";
import { addTenantSubscriptionProduct } from "../../db/subscriptions/tenantSubscriptionProducts.db.server";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { SubscriptionSubscribedDto } from "~/modules/events/dtos/SubscriptionSubscribedDto";
import { SubscriptionPriceDto } from "~/application/dtos/subscriptions/SubscriptionPriceDto";
import { getUser } from "../../db/users.db.server";
import { cancelTenantSubscription, clearAllSubscriptionsCache, clearTenantSubscriptionCache, getActiveTenantSubscriptions } from "./subscriptionService";
import currencies from "~/application/pricing/currencies";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { createScopedLogger } from "~/utils/logger.server";
const pricingLogger = createScopedLogger("pricing");
export async function createPlans(plans: SubscriptionProductDto[]) {
for (const plan of plans.sort((a, b) => a.order - b.order)) {
await createPlan(
plan,
plan.prices.map((price) => {
return {
billingPeriod: price.billingPeriod,
currency: price.currency,
price: Number(price.price),
};
}),
plan.features,
plan.usageBasedPrices
);
}
}
export async function createPlan(
plan: SubscriptionProductDto,
prices: { billingPeriod: SubscriptionBillingPeriod; price: number; currency: string; trialDays?: number }[],
features: SubscriptionFeatureDto[],
usageBasedPrices?: SubscriptionUsageBasedPriceDto[],
t?: TFunction
) {
// Create stripe product
const stripeProduct = await createStripeProduct({ title: plan.translatedTitle ?? plan.title });
// Save to db
const product = await createSubscriptionProduct({
stripeId: stripeProduct?.id ?? "",
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? null,
badge: plan.badge ?? null,
groupTitle: plan.groupTitle ?? null,
groupDescription: plan.groupDescription ?? null,
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 createStripePrice(stripeProduct?.id ?? "", price);
// Save to db
return await createSubscriptionPrice({
...price,
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 createSubscriptionFeature(product.id, feature);
})
);
if (usageBasedPrices) {
await Promise.all(
usageBasedPrices.map(async (usageBasedPrice) => {
pricingLogger.info(
{ op: "createUsageBasedPrice", productId: product.id, billingPeriod: usageBasedPrice.billingPeriod, unit: usageBasedPrice.unit },
"Creating usage-based price",
);
const stripePrice = await createStripeUsageBasedPrice(stripeProduct?.id ?? "", {
...usageBasedPrice,
unitTitle: t ? t(usageBasedPrice.unitTitle) : usageBasedPrice.unitTitle,
});
const createdPrice = await createSubscriptionUsageBasedPrice({
subscriptionProductId: product.id,
stripeId: stripePrice?.id ?? "",
billingPeriod: usageBasedPrice.billingPeriod,
currency: usageBasedPrice.currency,
unit: usageBasedPrice.unit,
unitTitle: usageBasedPrice.unitTitle,
unitTitlePlural: usageBasedPrice.unitTitlePlural,
usageType: usageBasedPrice.usageType,
aggregateUsage: usageBasedPrice.aggregateUsage,
tiersMode: usageBasedPrice.tiersMode,
billingScheme: usageBasedPrice.billingScheme,
});
await Promise.all(
usageBasedPrice.tiers.map(async (tierPrice) => {
await createSubscriptionUsageBasedTier({
subscriptionUsageBasedPriceId: createdPrice.id,
from: tierPrice.from,
to: tierPrice.to !== null && tierPrice.to !== undefined ? Number(tierPrice.to) : null,
perUnitPrice: tierPrice.perUnitPrice !== null && tierPrice.perUnitPrice !== undefined ? Number(tierPrice.perUnitPrice) : null,
flatFeePrice: tierPrice.flatFeePrice !== null && tierPrice.flatFeePrice !== undefined ? Number(tierPrice.flatFeePrice) : null,
});
})
);
})
);
}
}
export async function syncPlan(
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 createStripeProduct({ title: plan.translatedTitle ?? plan.title });
if (!stripeProduct) {
throw new Error("Could not create product");
}
await updateSubscriptionProductStripeId(plan.id, {
stripeId: stripeProduct.id,
});
prices.map(async (price) => {
// Create stripe price
const stripePrice = await createStripePrice(stripeProduct?.id ?? "", price);
if (!stripePrice) {
throw new Error(`Could not create price ${plan.title} - ${price.price}`);
}
// Save to db
await updateSubscriptionPriceStripeId(price.id ?? "", {
stripeId: stripePrice?.id ?? "",
});
});
}
export async function updatePlan(plan: SubscriptionProductDto, features: SubscriptionFeatureDto[]) {
if (!plan.id) {
throw new Error(`Plan ${plan.title} not found on database`);
}
await updateStripeProduct(plan.stripeId, { title: plan.translatedTitle ?? plan.title });
await updateSubscriptionProduct(plan.id, {
order: plan.order,
title: plan.title,
model: plan.model,
description: plan.description ?? null,
badge: plan.badge ?? null,
groupTitle: plan.groupTitle ?? null,
groupDescription: plan.groupDescription ?? null,
public: plan.public,
billingAddressCollection: plan.billingAddressCollection ?? "auto",
hasQuantity: plan.hasQuantity === undefined ? undefined : plan.hasQuantity,
canBuyAgain: plan.canBuyAgain === undefined ? undefined : plan.canBuyAgain,
});
await deleteSubscriptionFeatures(plan.id ?? "");
await clearAllSubscriptionsCache();
return await Promise.all(
features
.sort((a, b) => a.order - b.order)
.map(async (feature) => {
return await createSubscriptionFeature(plan.id ?? "", feature);
})
);
}
export async function deletePlan(plan: SubscriptionProductDto) {
await clearAllSubscriptionsCache();
pricingLogger.info({ op: "deletePlan.flatPrices", planId: plan.id, count: plan.prices?.length ?? 0 }, "Deleting flat-rate prices");
await Promise.all(
plan.prices
.filter((f) => f.stripeId)
.map(async (price) => {
await archiveStripePrice(price.stripeId);
if (price.id) {
await deleteSubscriptionPrice(price.id);
}
return null;
})
);
pricingLogger.info(
{ op: "deletePlan.usageBasedPrices", planId: plan.id, count: plan.usageBasedPrices?.length ?? 0 },
"Deleting usage-based prices",
);
if (plan.usageBasedPrices) {
await Promise.all(
plan.usageBasedPrices?.map(async (price) => {
await archiveStripePrice(price.stripeId);
await Promise.all(
price.tiers.map(async (tier) => {
return deleteSubscriptionUsageBasedTier(tier.id);
})
);
await deleteSubscriptionUsageBasedPrice(price.id);
return null;
})
);
}
pricingLogger.info({ op: "deletePlan.product", planId: plan.id, stripeId: plan.stripeId }, "Deleting Stripe product");
if (plan.stripeId) {
try {
await deleteStripeProduct(plan.stripeId);
} catch (e: any) {
pricingLogger.warn(
{ err: e, op: "deletePlan.product.archive", planId: plan.id, stripeId: plan.stripeId },
"Could not delete Stripe product; archiving instead",
);
await archiveStripeProduct(plan.stripeId);
}
}
if (plan.id) {
await deleteSubscriptionProduct(plan.id);
}
}
export type CheckoutSessionResponse = {
id: string;
customer: {
id: string;
email: string;
name: string;
};
products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[];
status: CheckoutSessionStatus | null;
};
export async function getAcquiredItemsFromCheckoutSession(session_id: string | null): Promise<CheckoutSessionResponse | null> {
const session = await getStripeSession(session_id ?? "");
if (!session || session.status !== "complete") {
return null;
}
const prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[] = [];
try {
let line_items: { price: Stripe.Price; quantity: number | undefined }[] = [];
if (session.line_items) {
session.line_items.data.forEach((item) => {
if (item.price) {
line_items.push({
price: item.price,
quantity: item.quantity ?? undefined,
});
}
});
}
await Promise.all(
line_items.map(async (line_item) => {
const flatPrice = await getSubscriptionPriceByStripeId(line_item.price.id);
const usageBasedPrice = await getSubscriptionUsageBasedPriceByStripeId(line_item.price.id);
const quantity = line_item.quantity ?? undefined;
if (!flatPrice && !usageBasedPrice) {
throw new Error("Price not found: " + line_item.price.id);
}
prices.push({
flatPrice: flatPrice ?? undefined,
usageBasedPrice: usageBasedPrice ?? undefined,
quantity,
});
})
);
} catch (e: any) {
pricingLogger.error({ err: e, op: "getAcquiredItemsFromCheckoutSession" }, "Failed to load acquired items from checkout session");
}
const products: {
id: string;
title: string;
quantity: number;
subscription: string | undefined;
prices: { flatPrice?: SubscriptionPrice; usageBasedPrice?: SubscriptionUsageBasedPrice; quantity?: number }[];
}[] = [];
prices.forEach((item) => {
const productId = item.flatPrice?.subscriptionProductId ?? item.usageBasedPrice?.subscriptionProductId ?? "";
if (!productId) {
return;
}
const product = products.find((p) => p.id === productId);
if (!product) {
products.push({
id: productId,
title: "",
quantity: item.quantity ?? 1,
prices: [item],
subscription: session.subscription?.toString(),
});
} else {
product?.prices.push(item);
}
});
await Promise.all(
products.map(async (product) => {
const subscriptionProduct = await getSubscriptionProduct(product.id);
product.title = subscriptionProduct?.title ?? "";
})
);
const status = await getCheckoutSessionStatus(session.id);
return {
id: session.id,
customer: {
id: session.customer?.toString() ?? "",
name: session.customer_details?.name ?? "",
email: session.customer_details?.email ?? "",
},
products,
status,
};
}
export async function addTenantProductsFromCheckoutSession({
request,
tenantId,
user,
checkoutSession,
createdUserId,
createdTenantId,
t,
}: {
request: Request;
tenantId: string;
user: { id: string; email: string };
checkoutSession: CheckoutSessionResponse;
createdUserId?: string | null;
createdTenantId?: string | null;
t: TFunction;
}) {
clearTenantSubscriptionCache(tenantId);
const appConfiguration = await getAppConfiguration({ request });
const tenant = await getTenant(tenantId);
if (!tenant) {
throw new Error("Tenant not found");
}
const tenantSubscription = await getOrPersistTenantSubscription(tenant.id);
if (!tenantSubscription.stripeCustomerId) {
const customer = await createStripeCustomer(user.email, tenant.name);
if (customer) {
tenantSubscription.stripeCustomerId = customer.id;
await updateTenantSubscriptionCustomerId(tenant.id, {
stripeCustomerId: customer.id,
});
}
}
const existingSessionStatus = await getCheckoutSessionStatus(checkoutSession.id);
if (!checkoutSession) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (checkoutSession.customer.id !== tenantSubscription.stripeCustomerId) {
throw new Error(t("settings.subscription.checkout.invalidCustomer"));
} else if (!existingSessionStatus) {
throw new Error(t("settings.subscription.checkout.invalid"));
} else if (!existingSessionStatus.pending) {
throw new Error(t("settings.subscription.checkout.alreadyProcessed"));
} else {
await updateCheckoutSessionStatus(checkoutSession.id, {
pending: false,
createdUserId,
createdTenantId,
});
if (!appConfiguration.subscription.multiple) {
const hasSubscribed = checkoutSession.products.some((product) => product.subscription);
const activeSubscriptions = await getActiveTenantSubscriptions(tenant.id);
const recurringSubscriptions = activeSubscriptions?.products.filter((f) => f.stripeSubscriptionId) || [];
pricingLogger.info(
{
op: "cancelExistingSubscriptions",
tenantId: tenant.id,
hasSubscribed,
recurringCount: recurringSubscriptions.length,
},
"Cancelling existing subscriptions before new subscribe",
);
if (hasSubscribed && recurringSubscriptions.length > 0) {
await Promise.all(
recurringSubscriptions.map(async (recurringSubscription) => {
pricingLogger.info(
{
op: "cancelSubscription",
tenantId: tenant.id,
subscriptionId: recurringSubscription.id,
productId: recurringSubscription.subscriptionProductId,
},
"Cancelling tenant subscription",
);
return await cancelTenantSubscription(recurringSubscription.id, { tenantId, userId: user.id, t });
})
);
}
}
await Promise.all(
checkoutSession.products.map(async (product) => {
// const existingProduct = await getTenantSubscriptionProduct(tenant.id, product.id);
// if (!existingProduct) {
await addTenantSubscriptionProduct({
tenantSubscriptionId: tenantSubscription.id,
subscriptionProductId: product.id ?? "",
quantity: product.quantity,
stripeSubscriptionId: product.subscription ?? "",
fromCheckoutSessionId: checkoutSession.id,
prices: product.prices.map((price) => {
return {
subscriptionPriceId: price.flatPrice?.id,
subscriptionUsageBasedPriceId: price.usageBasedPrice?.id,
};
}),
});
// } else {
// // is active
// if (!existingProduct.endsAt) {
// await updateTenantSubscriptionProduct(existingProduct.id, {
// quantity: (existingProduct.quantity ?? 1) + 1,
// });
// } else {
// await updateTenantSubscriptionProduct(existingProduct.id, {
// quantity: product.quantity,
// endsAt: null,
// cancelledAt: null,
// });
// }
// }
const subscriptionProduct = await getSubscriptionProduct(product.id);
if (subscriptionProduct) {
function checkUpgradeDowngrade(plan: SubscriptionProductDto) {
const existing = tenantSubscription?.products.find((f) => f)?.subscriptionProduct;
if (existing) {
if (plan.order > existing.order) {
return { upgrade: true };
} else {
return { downgrade: true };
}
}
}
let event: "subscription.subscribed" | "subscription.upgraded" | "subscription.downgraded" = "subscription.subscribed";
if (tenantSubscription.products.length > 0) {
const upgradeDowngrade = checkUpgradeDowngrade(subscriptionProduct);
if (upgradeDowngrade?.upgrade) {
event = "subscription.upgraded";
} else if (upgradeDowngrade?.downgrade) {
event = "subscription.downgraded";
}
}
await EventsService.create({
request,
event,
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: { id: product.id, title: t(subscriptionProduct.title) || subscriptionProduct.title },
session: checkoutSession.id,
},
} satisfies SubscriptionSubscribedDto,
});
await TenantTypesApi.setTenantTypes({ tenantId, subscriptionProduct });
}
})
);
}
}
export async function autosubscribeToTrialOrFreePlan({
request,
t,
tenantId,
userId,
}: {
request: Request;
t: TFunction;
tenantId: string;
userId: string | null;
}) {
pricingLogger.info({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Starting auto-subscribe to trial/free plan");
const tenant = await getTenant(tenantId);
if (!tenant) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant not found; skipping");
return;
}
if (!tenant.subscription?.stripeCustomerId) {
pricingLogger.warn({ op: "autosubscribeToTrialOrFreePlan.start", tenantId }, "Tenant has no Stripe customer id; skipping");
return;
}
const defaultCurrency = currencies.find((f) => f.default)?.value;
if (!defaultCurrency) {
return;
}
const allProducts = await getAllSubscriptionProducts(true);
const productsFree: SubscriptionPriceDto[] = [];
const productsWithTrialDays: SubscriptionPriceDto[] = [];
pricingLogger.debug(
{ op: "autosubscribeToTrialOrFreePlan.products", tenantId, count: allProducts.length },
"Auto-subscribe candidate products loaded",
);
allProducts.forEach((product) => {
if (product.prices.length === 0) {
return;
}
const allPricesAreZero = product.prices.every((price) => price.currency === defaultCurrency && (price.price === undefined || Number(price.price) === 0));
if (allPricesAreZero) {
productsFree.push(product.prices[0]);
}
const firstPriceWithTrialDays = product.prices.find(
(price) => price.currency === defaultCurrency && (price.trialDays > 0 || price.price === undefined || Number(price.price) === 0)
);
if (firstPriceWithTrialDays) {
productsWithTrialDays.push(firstPriceWithTrialDays);
}
});
try {
if (productsWithTrialDays.length > 0) {
pricingLogger.info(
{
op: "autosubscribeToTrialOrFreePlan",
tenantId: tenant.id,
productCount: productsWithTrialDays.length,
productIds: productsWithTrialDays.map((p) => p.subscriptionProductId),
},
"Autosubscribing tenant to trial/free plan",
);
const price = productsWithTrialDays[0];
const trial_end = Math.floor(Date.now() / 1000) + (price.trialDays || 30) * 24 * 60 * 60;
const stripeSubscription = await createStripeSubscription(tenant.subscription.stripeCustomerId, price.stripeId, trial_end);
await addTenantSubscriptionProduct({
tenantSubscriptionId: tenant.subscription.id,
subscriptionProductId: price.subscriptionProductId,
quantity: 1,
stripeSubscriptionId: stripeSubscription.id,
fromCheckoutSessionId: null,
prices: [
{
subscriptionPriceId: price.id,
},
],
});
const user = userId ? await getUser(userId) : null;
await EventsService.create({
request,
event: "subscription.subscribed",
tenantId: tenant.id,
userId: user?.id ?? null,
data: {
user: !user ? null : { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
subscription: {
product: {
id: price.subscriptionProductId,
title: t(price.subscriptionProduct?.title ?? "") || price.subscriptionProduct?.title || "",
},
},
} satisfies SubscriptionSubscribedDto,
});
} else if (productsFree.length > 0) {
// TODO: IMPLEMENT
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.free", tenantId, count: productsFree.length },
"Free products available but auto-subscribe-free path not implemented yet",
);
} else {
pricingLogger.info(
{ op: "autosubscribeToTrialOrFreePlan.none", tenantId },
"No auto-subscription products/plans found",
);
}
} catch (e: any) {
pricingLogger.error({ err: e, op: "autosubscribeToTrialOrFreePlan", tenantId }, "Auto-subscribe failed");
}
}
@@ -0,0 +1,99 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { MemoryAdapter, createSharedStore } from "@toolctrl/shared-store";
vi.mock("~/utils/cache.server", () => {
const map = new Map<string, unknown>();
return {
cache: map,
cachified: vi.fn(),
clearCacheKey: vi.fn((key: string) => map.delete(key)),
clearCacheKeyPrefix: vi.fn((prefix: string) => {
for (const k of map.keys()) if (k.startsWith(prefix)) map.delete(k);
}),
__test_map: map,
};
});
vi.mock("~/shared-store.server", async () => {
const { MemoryAdapter, createSharedStore } = await import("@toolctrl/shared-store");
const adapter = new MemoryAdapter();
const store = createSharedStore({ namespace: "web-test", adapter });
return {
getSharedStore: () => store,
__setSharedStoreFactoryForTests: vi.fn(),
__resetSharedStoreForTests: vi.fn(),
};
});
import {
getSubscriptionCache,
subscribeSubscriptionCache,
__resetSubscriptionCacheForTests,
} from "./subscriptionCache.server";
import * as cacheServer from "~/utils/cache.server";
beforeEach(() => {
__resetSubscriptionCacheForTests();
// clear shared cache.server map between tests
(cacheServer as unknown as { __test_map: Map<string, unknown> }).__test_map.clear();
vi.mocked(cacheServer.clearCacheKey).mockClear();
vi.mocked(cacheServer.clearCacheKeyPrefix).mockClear();
delete process.env.CACHE_INVALIDATION_ENABLED;
delete process.env.CACHE_L1_TTL_SECONDS;
});
afterEach(() => {
__resetSubscriptionCacheForTests();
});
describe("subscription cache (two-tier)", () => {
it("invalidate(tenantId) publishes + clears L2 and triggers local clearCacheKey via subscriber", async () => {
const cache = getSubscriptionCache();
await subscribeSubscriptionCache();
await cache.invalidate("tenant-1");
// Give the in-process pubsub event loop a tick to flush.
await new Promise((r) => setTimeout(r, 10));
expect(vi.mocked(cacheServer.clearCacheKey)).toHaveBeenCalledWith("tenantSubscription:tenant-1");
});
it("wildcard invalidate clears the cachified prefix", async () => {
const cache = getSubscriptionCache();
await subscribeSubscriptionCache();
await cache.invalidate();
await new Promise((r) => setTimeout(r, 10));
expect(vi.mocked(cacheServer.clearCacheKeyPrefix)).toHaveBeenCalledWith("tenantSubscription:");
});
it("respects CACHE_INVALIDATION_ENABLED=false (subscribe is no-op, no publish)", async () => {
process.env.CACHE_INVALIDATION_ENABLED = "false";
__resetSubscriptionCacheForTests();
const cache = getSubscriptionCache();
const dispose = await subscribeSubscriptionCache();
await cache.invalidate("tenant-2");
await new Promise((r) => setTimeout(r, 10));
// subscriber never wired because pubsub disabled → no clearCacheKey from remote path
expect(vi.mocked(cacheServer.clearCacheKey)).not.toHaveBeenCalled();
await dispose();
});
it("subscribeSubscriptionCache is idempotent (returns same disposer)", async () => {
const a = await subscribeSubscriptionCache();
const b = await subscribeSubscriptionCache();
expect(a).toBe(b);
});
it("uses CACHE_L1_TTL_SECONDS override when present", async () => {
process.env.CACHE_L1_TTL_SECONDS = "120";
__resetSubscriptionCacheForTests();
const cache = getSubscriptionCache();
// Smoke: a set/get round-trip works with overridden TTL.
await cache.set("t1", null);
expect(await cache.get("t1")).toBeNull();
});
});
// Silence the unused createSharedStore import — used only to load the package
// (and force its types) for the mock factory above. vitest's mock factory is
// hoisted so the dynamic import shape is the standard pattern here.
void MemoryAdapter;
void createSharedStore;
@@ -0,0 +1,74 @@
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey, clearCacheKeyPrefix } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
/**
* Subscription cache (two-tier). L1 = in-process Map, L2 = SharedStore;
* cross-replica purges via pub/sub on channel
* `shared-store:web:ch:cache:subscription:invalidate`.
*
* Bootstrap (idempotent): call `subscribeSubscriptionCache()` once during
* web boot so this replica listens for invalidation messages emitted by
* the API stripe webhook handler.
*/
const log = createScopedLogger("subscription-cache");
const TTL_SECONDS_DEFAULT = 5 * 60; // 5 minutes — L1 safety-net so a missed pub/sub event self-heals quickly.
let cacheSingleton: TwoTierCache<TenantSubscriptionWithDetails | null> | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
function ttlSecondsFromEnv(): number {
const raw = process.env.CACHE_L1_TTL_SECONDS;
if (!raw) return TTL_SECONDS_DEFAULT;
const parsed = Number(raw);
if (!Number.isFinite(parsed) || parsed <= 0) return TTL_SECONDS_DEFAULT;
return Math.floor(parsed);
}
export function getSubscriptionCache(): TwoTierCache<TenantSubscriptionWithDetails | null> {
if (cacheSingleton) return cacheSingleton;
cacheSingleton = createTwoTierCache<TenantSubscriptionWithDetails | null>({
store: getSharedStore(),
namespace: "subscription",
ttlSeconds: ttlSecondsFromEnv(),
pubsubEnabled: pubsubEnabledFromEnv(),
logger: { warn: (obj, msg) => log.warn(obj, msg), error: (obj, msg) => log.error(obj, msg) },
});
return cacheSingleton;
}
/**
* Start the subscriber for this process. Safe to call repeatedly (idempotent).
* Returns the disposer for tests / graceful shutdown.
*/
export async function subscribeSubscriptionCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
const cache = getSubscriptionCache();
// Bridge: on remote invalidation, also purge the in-process cachified
// LRU keyed `tenantSubscription:<tenantId>` so getActiveTenantSubscriptions
// refetches on the next call.
subscribeDisposer = await cache.subscribe((key) => {
if (!key || key === "*") {
clearCacheKeyPrefix("tenantSubscription:");
} else {
clearCacheKey(`tenantSubscription:${key}`);
}
});
log.info({ namespace: "subscription" }, "subscription cache subscriber started");
return subscribeDisposer;
}
/** Test seam: drop the singleton + disposer so each test gets a fresh cache. */
export function __resetSubscriptionCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -0,0 +1,136 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({ db: {} }));
vi.mock("../../db/entities/entities.db.server", () => ({ findSimpleEntityByName: vi.fn() }));
vi.mock("../../db/stripe/checkoutSessions.db.server", () => ({ createCheckoutSessionStatus: vi.fn(), getCheckoutSessionStatus: vi.fn() }));
vi.mock("../../db/subscriptionProducts.db.server", () => ({ getAllSubscriptionFeatures: vi.fn() }));
vi.mock("@toolctrl/db/subscriptions.server", () => ({
createTenantSubscriptionUsageRecord: vi.fn(),
listTenantSubscriptionIds: vi.fn(),
updateTenantSubscriptionProduct: vi.fn(),
}));
vi.mock("../../db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: vi.fn(), getTenantSubscriptions: vi.fn() }));
vi.mock("~/modules/emails/services/EmailService", () => ({ sendEmail: vi.fn() }));
vi.mock("../../helpers/ApiKeyHelper", () => ({ apiKeyCreditableStatusCodes: [], apiKeyIgnoreEndpoints: [] }));
vi.mock("../../stripe.server", () => ({
cancelStripeSubscription: vi.fn(),
createUsageRecord: vi.fn(),
getStripeSession: vi.fn(),
getStripeSubscription: vi.fn(),
}));
vi.mock("../../url.server", () => ({ getBaseURL: vi.fn() }));
vi.mock("./pricingService", () => ({ getAcquiredItemsFromCheckoutSession: vi.fn() }));
vi.mock("../../cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn(), clearCacheKeyPrefix: vi.fn() }));
// Stable invalidate spy so tests can assert the cross-replica publish path.
const subscriptionCacheInvalidateMock = vi.fn().mockResolvedValue(undefined);
vi.mock("./subscriptionCache.server", () => ({
getSubscriptionCache: () => ({
invalidate: subscriptionCacheInvalidateMock,
get: vi.fn(),
set: vi.fn(),
subscribe: vi.fn(),
flushLocal: vi.fn(),
deleteLocal: vi.fn(),
}),
}));
vi.mock("~/utils/db/subscriptions/tenantSubscriptionProducts.db.server", () => ({
cancelTenantSubscriptionProduct: vi.fn(),
getTenantSubscriptionProductById: vi.fn(),
}));
vi.mock("~/modules/events/services/.server/EventsService", () => ({ default: { create: vi.fn() } }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: vi.fn() }));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn() }));
vi.mock("~/modules/emails/utils/EmailTemplates", () => ({ default: {} }));
vi.mock("~/utils/db/appConfiguration.db.server", () => ({ getAppConfiguration: vi.fn() }));
import {
cancelTenantSubscription,
clearAllSubscriptionsCache,
clearTenantSubscriptionCache,
} from "./subscriptionService";
import { cancelStripeSubscription } from "../../stripe.server";
import { getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { clearCacheKey } from "../../cache.server";
import { listTenantSubscriptionIds } from "@toolctrl/db/subscriptions.server";
describe("cancelTenantSubscription", () => {
it("returns without logging or calling Stripe when the product is not subscribed", async () => {
vi.mocked(getTenantSubscriptionProductById).mockResolvedValueOnce({
id: "tenant-sub-product-id",
stripeSubscriptionId: null,
} as Awaited<ReturnType<typeof getTenantSubscriptionProductById>>);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await cancelTenantSubscription("tenant-sub-product-id", { tenantId: "tenant-id", userId: "user-id" });
expect(consoleLog).not.toHaveBeenCalled();
expect(cancelStripeSubscription).not.toHaveBeenCalled();
consoleLog.mockRestore();
});
});
describe("subscription cache invalidation", () => {
it("clearTenantSubscriptionCache only invalidates the affected tenant key", () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
clearCacheKeyMock.mockClear();
clearTenantSubscriptionCache("tenant-a");
expect(clearCacheKeyMock).toHaveBeenCalledTimes(1);
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-a");
});
it("clearTenantSubscriptionCache does not enumerate other tenants (no global thrash)", () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const listMock = vi.mocked(listTenantSubscriptionIds);
clearCacheKeyMock.mockClear();
listMock.mockClear();
clearTenantSubscriptionCache("tenant-x");
expect(listMock).not.toHaveBeenCalled();
});
it("clearTenantSubscriptionCache publishes a cross-replica invalidation for the tenant", () => {
subscriptionCacheInvalidateMock.mockClear();
clearTenantSubscriptionCache("tenant-b");
// Peer web replicas must drop their L1 too — not just this process.
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1);
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith("tenant-b");
});
it("clearAllSubscriptionsCache broadcasts a wildcard cross-replica invalidation", async () => {
subscriptionCacheInvalidateMock.mockClear();
vi.mocked(listTenantSubscriptionIds).mockResolvedValueOnce(
[] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>,
);
await clearAllSubscriptionsCache();
// No key argument == wildcard flush across every replica's L1.
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledTimes(1);
expect(subscriptionCacheInvalidateMock).toHaveBeenCalledWith();
});
it("clearAllSubscriptionsCache invalidates every cached tenant subscription", async () => {
const clearCacheKeyMock = vi.mocked(clearCacheKey);
const listMock = vi.mocked(listTenantSubscriptionIds);
clearCacheKeyMock.mockClear();
listMock.mockReset();
listMock.mockResolvedValueOnce([
{ id: "sub-1", tenantId: "tenant-1" },
{ id: "sub-2", tenantId: "tenant-2" },
{ id: "sub-3", tenantId: "tenant-3" },
] as Awaited<ReturnType<typeof listTenantSubscriptionIds>>);
await clearAllSubscriptionsCache();
expect(clearCacheKeyMock).toHaveBeenCalledTimes(3);
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-1");
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-2");
expect(clearCacheKeyMock).toHaveBeenCalledWith("tenantSubscription:tenant-3");
});
});
@@ -0,0 +1,618 @@
import { Prisma, SubscriptionPrice } from "@toolctrl/db/prisma-browser";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import currencies from "~/application/pricing/currencies";
import { db } from "../../db.server";
import { findSimpleEntityByName } from "../../db/entities/entities.db.server";
import { createCheckoutSessionStatus, getCheckoutSessionStatus } from "../../db/stripe/checkoutSessions.db.server";
import { getAllSubscriptionFeatures } from "../../db/subscriptionProducts.db.server";
import {
createTenantSubscriptionUsageRecord,
listTenantSubscriptionIds,
updateTenantSubscriptionProduct,
type TenantSubscriptionWithDetails,
} from "@toolctrl/db/subscriptions.server";
import { getTenantSubscription, getTenantSubscriptions } from "../../db/tenantSubscriptions.db.server";
import { sendEmail } from "~/modules/emails/services/EmailService";
import { apiKeyCreditableStatusCodes, apiKeyIgnoreEndpoints } from "../../helpers/ApiKeyHelper";
import { cancelStripeSubscription, getStripeSession, getStripeSubscription } from "../../stripe.server";
import { getBaseURL } from "../../url.server";
import { getAcquiredItemsFromCheckoutSession } from "./pricingService";
import { cachified, clearCacheKey } from "../../cache.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import DateUtils from "~/utils/shared/DateUtils";
import { TFunction } from "i18next";
import { cancelTenantSubscriptionProduct, getTenantSubscriptionProductById } from "~/utils/db/subscriptions/tenantSubscriptionProducts.db.server";
import { SubscriptionCancelledDto } from "~/modules/events/dtos/SubscriptionCancelledDto";
import EventsService from "~/modules/events/services/.server/EventsService";
import { getTenant } from "~/utils/db/tenants.db.server";
import { getUser } from "~/utils/db/users.db.server";
import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
let subscription: TenantSubscriptionWithDetails | null = null;
if (tenantSubscription === undefined) {
subscription = await getActiveTenantSubscriptions(tenantId);
} else {
subscription = tenantSubscription;
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
features
.filter((f) => f.name)
.forEach((feature) => {
const existing = allFeatures.find((f) => f.name === feature.name);
if (!existing) {
allFeatures.push({
order: feature.order,
name: feature.name,
title: feature.title,
type: feature.type,
value: feature.value,
accumulate: feature.accumulate,
});
}
});
allFeatures = allFeatures.sort((a, b) => a.order - b.order);
await Promise.all(
allFeatures.map(async (item) => {
let myFeatures: SubscriptionFeatureDto[] = [];
subscription?.products.forEach((product) => {
const feature = product.subscriptionProduct.features.find((f) => f.name === item.name);
if (feature) {
if (!product.quantity) {
myFeatures.push(feature);
} else {
// per-seat or one-time multiplication
for (let idx = 0; idx < product.quantity; idx++) {
myFeatures.push(feature);
}
}
}
});
const existingSubscriptionFeature = mergeFeatures(myFeatures);
const feature = existingSubscriptionFeature ?? item;
const entity = await findSimpleEntityByName(item.name);
const usage: PlanFeatureUsageDto = {
entity: entity ?? undefined,
order: feature.order,
title: feature.title,
name: feature.name,
type: feature.type,
value: feature.value,
used: 0,
remaining: 0,
enabled: feature.type !== SubscriptionFeatureLimitType.NOT_INCLUDED,
message: "",
};
if (!existingSubscriptionFeature) {
usage.type = SubscriptionFeatureLimitType.NOT_INCLUDED;
usage.enabled = false;
if (subscription?.products && subscription.products.length > 0) {
usage.message = "featureLimits.upgradeSubscription";
} else {
usage.message = "featureLimits.noSubscription";
}
} else {
if (feature.type === SubscriptionFeatureLimitType.NOT_INCLUDED) {
usage.enabled = false;
usage.message = "featureLimits.notIncluded";
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
usage.used = await getUsed(tenantId, feature, subscription);
usage.remaining = usage.value - usage.used;
if (usage.remaining <= 0) {
usage.message = `You've reached the limit (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
usage.used = await getUsed(tenantId, feature, subscription);
usage.remaining = usage.value - usage.used;
usage.period = getUsedPeriod(subscription);
if (usage.remaining <= 0) {
// var now = new Date();
// const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
usage.message = `You've reached the limit this month (${usage.used}/${usage.value}) for ${entity?.titlePlural ?? feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
usage.remaining = "unlimited";
}
}
myUsage.push(usage);
})
);
return myUsage.sort((a, b) => a.order - b.order);
}
function mergeFeatures(features: SubscriptionFeatureDto[]) {
if (features.length === 0) {
return undefined;
}
const mergedFeature: SubscriptionFeatureDto = {
order: features[0].order,
title: features[0].title,
name: features[0].name,
type: SubscriptionFeatureLimitType.NOT_INCLUDED,
value: 0,
accumulate: features[0].accumulate,
};
let firstFeature = true;
features.forEach((feature) => {
if (mergedFeature.type < feature.type) {
mergedFeature.type = feature.type;
}
// console.log({ mergedFeature });
if (mergedFeature.accumulate || firstFeature) {
mergedFeature.value += feature.value;
}
firstFeature = false;
});
return mergedFeature;
}
export async function getPlanFeatureUsage(
tenantId: string,
featureName: string,
tenantSubscription?: TenantSubscriptionWithDetails | null
): Promise<PlanFeatureUsageDto | undefined> {
const usage = await getPlanFeaturesUsage(tenantId, tenantSubscription);
return usage.find((f) => f.name === featureName);
}
function getUsedPeriod(subscription: TenantSubscriptionWithDetails | null) {
const date = new Date(),
y = date.getFullYear(),
m = date.getMonth();
let firstDay = new Date(y, m, 1, 0, 0, 1);
let lastDay = new Date(y, m + 1, 0, 23, 59, 59);
// if it's december, last day is january 0
if (m === 11) {
lastDay = new Date(y + 1, 0, 0, 23, 59, 59);
}
subscription?.products.forEach((product) => {
if (product.currentPeriodStart && product.currentPeriodEnd) {
firstDay = product.currentPeriodStart;
lastDay = product.currentPeriodEnd;
}
});
return {
firstDay,
lastDay,
};
}
async function getUsed(tenantId: string, feature: SubscriptionFeatureDto, subscription: TenantSubscriptionWithDetails | null): Promise<number> {
const { firstDay, lastDay } = await getUsedPeriod(subscription);
if (feature.name === DefaultFeatures.Users) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await db.tenantUser.count({
where: {
tenantId,
createdAt: {
gte: firstDay,
lt: lastDay,
},
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await db.tenantUser.count({
where: {
tenantId,
},
});
}
} else if (feature.name === DefaultFeatures.API) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await db.apiKeyLog.count({
where: {
tenantId,
status: { in: apiKeyCreditableStatusCodes },
endpoint: { notIn: apiKeyIgnoreEndpoints },
createdAt: {
gte: firstDay,
lt: lastDay,
},
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await db.apiKeyLog.count({
where: {
tenantId,
status: { in: apiKeyCreditableStatusCodes },
endpoint: { notIn: apiKeyIgnoreEndpoints },
},
});
}
} else if (feature.name === DefaultFeatures.Credits) {
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
return await getSpentCredits({
tenantId,
createdAt: {
gte: firstDay,
lt: lastDay,
},
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
return await getSpentCredits({ tenantId });
}
} else {
const entity = await findSimpleEntityByName(feature.name);
// if (!entity) {
// // throw new Error("Entity does not exist with plural title: " + feature.name);
// }
if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
const where: Prisma.RowWhereInput = {
tenantId,
entityId: entity?.id ?? "",
createdAt: {
gte: firstDay,
lt: lastDay,
},
};
return db.row.count({
where,
});
} else if (feature.type === SubscriptionFeatureLimitType.MAX) {
const count = await db.row.count({
where: {
tenantId,
entityId: entity?.id ?? "",
},
});
return count;
}
}
return 0;
}
async function getSpentCredits(where: Prisma.CreditWhereInput): Promise<number> {
const spent = await db.credit.aggregate({
where: {
...where,
amount: { lt: 0 },
},
_sum: {
amount: true,
},
});
return Math.abs(spent._sum.amount ?? 0);
}
// export async function getPlanFeatureUsage(tenantId: string, featureName: string): Promise<PlanFeatureUsageDto> {
// const myUsage: PlanFeatureUsageDto[] = [];
// let allFeatures: SubscriptionFeatureDto[] = [];
// const features = await getAllSubscriptionFeatures();
// features.forEach((feature) => {
// const existing = allFeatures.find((f) => f.name === feature.name);
// if (!existing) {
// allFeatures.push({
// order: feature.order,
// name: feature.name,
// title: feature.title,
// type: feature.type,
// value: feature.value,
// });
// }
// });
// allFeatures = allFeatures.sort((a, b) => a.order - b.order);
// allFeatures.forEach((feature) => {
// const featureUsage: PlanFeatureUsageDto = {
// order: feature.order,
// title: feature.title,
// name: feature.name,
// type: feature.type,
// value: feature.value,
// used: 0,
// remaining: 0,
// };
// if (feature.type === SubscriptionFeatureLimitType.MAX) {
// featureUsage.used = 2;
// featureUsage.remaining = featureUsage.value - featureUsage.used;
// } else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
// featureUsage.used = 3;
// featureUsage.remaining = featureUsage.value - featureUsage.used;
// }
// myUsage.push(featureUsage);
// });
// return myUsage;
// }
export async function getActiveTenantSubscriptions(tenantId: string) {
const mySubscription = await cachified({
key: `tenantSubscription:${tenantId}`,
ttl: 1000 * 60 * 60, // 1 hour
getFreshValue: () => getTenantSubscription(tenantId),
});
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
let startOfDay = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
let endOfDay = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
item.currentPeriodStart = DateUtils.getDateStartOfDay(startOfDay);
item.currentPeriodEnd = DateUtils.getDateEndOfDay(endOfDay);
}
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: the Stripe billing-period sync mutates the
// subscription, so peer web replicas must drop their L1 too —
// a bare clearCacheKey would only purge this process.
clearTenantSubscriptionCache(updatedItem.tenantSubscription.tenantId);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
mySubscription.products = mySubscription.products.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
}
return mySubscription;
}
export async function getActiveTenantsSubscriptions() {
const subscriptions = await getTenantSubscriptions();
return await Promise.all(
subscriptions.map(async (mySubscription) => {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
const stripeSubscription = await getStripeSubscription(item.stripeSubscriptionId);
if (stripeSubscription) {
item.currentPeriodStart = new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000);
item.currentPeriodEnd = new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000);
}
}
})
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
return mySubscription;
})
);
}
export async function reportUsage(tenantId: string, unit: string) {
const tenantSubscription = await getActiveTenantSubscriptions(tenantId);
if (!tenantSubscription) {
return;
}
await Promise.all(
tenantSubscription.products.map(async (product) => {
return await Promise.all(
product.prices.map(async (price) => {
if (!product.stripeSubscriptionId) {
return;
}
if (price.subscriptionUsageBasedPrice?.unit === unit) {
const stripeSubscription = await getStripeSubscription(product.stripeSubscriptionId);
const subscriptionItem = stripeSubscription?.items.data.find((f) => f.price.id === price.subscriptionUsageBasedPrice?.stripeId);
if (subscriptionItem) {
// Stripe submission is handled by the meter-based reporter in
// `apps/worker/src/jobs/ai-cost-stripe-report.ts`; this path only
// keeps local bookkeeping for tenant-facing usage history.
await createTenantSubscriptionUsageRecord({
tenantSubscriptionProductPriceId: price.id,
timestamp: Math.floor(Date.now() / 1000),
quantity: 1,
stripeSubscriptionItemId: subscriptionItem.id,
});
}
}
})
);
})
);
}
export async function persistCheckoutSessionStatus({
request,
id,
fromUrl,
fromUserId,
fromTenantId,
}: {
request: Request;
id: string;
fromUrl: string;
fromUserId?: string | null;
fromTenantId?: string | null;
}) {
const existingCheckoutSession = await getCheckoutSessionStatus(id);
if (!existingCheckoutSession) {
const stripeCheckoutSession = await getStripeSession(id);
if (stripeCheckoutSession) {
const session = await createCheckoutSessionStatus({
id: stripeCheckoutSession.id,
email: stripeCheckoutSession.customer_details?.email ?? "",
fromUrl,
fromUserId,
fromTenantId,
});
if (!session.fromUserId && !session.fromTenantId) {
const sessionResponse = await getAcquiredItemsFromCheckoutSession(session.id);
if (sessionResponse && sessionResponse.products.length > 0) {
const mailTranslator = await getMailTranslatorFromRequest(request);
await sendEmail({
request,
to: session.email,
alias: "account-setup",
...EmailTemplates.ACCOUNT_SETUP_EMAIL.parse({
appConfiguration: await getAppConfiguration({ request }),
data: {
email: session.email,
plan: sessionResponse.products[0].title,
action_url: `${getBaseURL(request)}/pricing/${session.id}/success`,
},
t: mailTranslator.t,
locale: mailTranslator.locale,
}),
});
}
}
}
}
}
export async function getMrr(currency: string) {
const activeSubscriptions = await getActiveTenantsSubscriptions();
let summary: { total: number; count: number } = {
total: 0,
count: 0,
};
activeSubscriptions.forEach((s) => {
s.products.forEach((p) => {
summary.count++;
p.prices.forEach((f) => {
summary.total += getPriceInCurrency(f.subscriptionPrice, currency);
});
});
});
return summary;
}
function getPriceInCurrency(subscriptionPrice: SubscriptionPrice | null, currency: string) {
if (!subscriptionPrice) {
return 0;
}
let total = 0;
if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.MONTHLY) {
total = Number(subscriptionPrice.price);
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.YEARLY) {
total = Number(subscriptionPrice.price) / 12;
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.WEEKLY) {
total = Number(subscriptionPrice.price) * 4;
} else if (subscriptionPrice.billingPeriod === SubscriptionBillingPeriod.DAILY) {
total = Number(subscriptionPrice.price) * 30;
}
if (currency !== subscriptionPrice.currency) {
total = convertToCurrency({ from: subscriptionPrice.currency, to: currency, price: total });
}
return total;
}
export 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;
}
/**
* Invalidate the cached subscription for a single tenant. Prefer this over
* `clearAllSubscriptionsCache` whenever the change is tenant-scoped (e.g.
* Stripe webhooks) so we don't thrash every other tenant's cache entry.
*
* Publishes a cross-replica invalidation on the `cache:subscription:invalidate`
* channel via the two-tier cache so peer web replicas drop their L1 too.
* The publish is fire-and-forget — failures are logged but never thrown.
*/
export function clearTenantSubscriptionCache(tenantId: string) {
clearCacheKey(`tenantSubscription:${tenantId}`);
// Best-effort fan-out to peer replicas; never blocks the caller.
void getSubscriptionCache()
.invalidate(tenantId)
.catch(() => {
/* errors are logged inside the helper via its logger */
});
}
/**
* Invalidate every cached tenant subscription. Use only for global changes
* (plan/feature CRUD, bulk migrations). Also broadcasts a wildcard
* invalidation on the subscription pub/sub channel so peer replicas flush
* their L1 in one shot rather than per-tenant.
*/
export async function clearAllSubscriptionsCache() {
const tenantSubs = await listTenantSubscriptionIds();
tenantSubs.forEach((tenantSub) => {
clearCacheKey(`tenantSubscription:${tenantSub.tenantId}`);
});
// Wildcard fan-out — peer replicas flush their L1 entirely.
await getSubscriptionCache().invalidate().catch(() => {
/* logged inside helper */
});
}
export async function cancelTenantSubscription(
tenantSubscriptionProductId: string,
{ tenantId, userId, t }: { tenantId: string; userId: string; t?: TFunction }
) {
const tenantSubscriptionProduct = await getTenantSubscriptionProductById({ id: tenantSubscriptionProductId, tenantId });
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (!tenantSubscriptionProduct.stripeSubscriptionId) {
return;
}
const user = userId ? await getUser(userId) : null;
const tenant = await getTenant(tenantId);
if (user && tenant) {
await EventsService.create({
event: "subscription.cancelled",
tenantId: tenant.id,
userId: user.id,
data: {
user: { id: user.id, email: user.email },
tenant: { id: tenant.id, name: tenant.name },
subscription: {
product: {
id: tenantSubscriptionProduct.subscriptionProductId,
title: t ? t(tenantSubscriptionProduct.subscriptionProduct.title) : tenantSubscriptionProduct.subscriptionProduct.title,
},
},
} satisfies SubscriptionCancelledDto,
});
}
await cancelStripeSubscription(tenantSubscriptionProduct?.stripeSubscriptionId);
const stripeSubscription = await getStripeSubscription(tenantSubscriptionProduct.stripeSubscriptionId);
await cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: stripeSubscription?.items.data[0]?.current_period_end ? new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000) : new Date(),
});
}
@@ -0,0 +1,93 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
vi.mock("@toolctrl/db/subscriptions.server", () => ({
getTenantSubscription: vi.fn(),
}));
vi.mock("@toolctrl/queue", () => ({
setTenantPlanLookup: vi.fn(),
}));
vi.mock("./subscriptionCache.server", () => ({
getSubscriptionCache: vi.fn(),
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
}),
}));
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import { setTenantPlanLookup } from "@toolctrl/queue";
import { getSubscriptionCache } from "./subscriptionCache.server";
import {
__resetTenantPlanLookupForTests,
getCachedTenantPlan,
setSubscriptionToPlanTier,
wireTenantPlanLookup,
} from "./tenantPlanLookup.server";
const getTenantSubscriptionMock = vi.mocked(getTenantSubscription);
const setTenantPlanLookupMock = vi.mocked(setTenantPlanLookup);
const getSubscriptionCacheMock = vi.mocked(getSubscriptionCache);
const cacheGet = vi.fn<[string], Promise<unknown>>();
const cacheSet = vi.fn<[string, unknown], Promise<void>>();
describe("tenant plan lookup", () => {
beforeEach(() => {
getTenantSubscriptionMock.mockReset();
cacheGet.mockReset();
cacheSet.mockReset().mockResolvedValue(undefined);
setTenantPlanLookupMock.mockReset();
getSubscriptionCacheMock.mockReset().mockReturnValue({ get: cacheGet, set: cacheSet } as any);
__resetTenantPlanLookupForTests();
});
afterEach(() => {
__resetTenantPlanLookupForTests();
});
test("returns null when no classifier is registered", async () => {
cacheGet.mockResolvedValue({ id: "sub_1" });
await expect(getCachedTenantPlan("tenant_1")).resolves.toBeNull();
// Cache hit — DB never queried
expect(getTenantSubscriptionMock).not.toHaveBeenCalled();
});
test("fetches subscription from DB on cache miss and primes L2", async () => {
cacheGet.mockResolvedValue(null);
getTenantSubscriptionMock.mockResolvedValue({ id: "sub_1" });
setSubscriptionToPlanTier((sub) => (sub ? "pro" : null));
await expect(getCachedTenantPlan("tenant_1")).resolves.toBe("pro");
expect(getTenantSubscriptionMock).toHaveBeenCalledWith("tenant_1");
expect(cacheSet).toHaveBeenCalledWith("tenant_1", { id: "sub_1" });
});
test("returns null and logs when DB fetch fails", async () => {
cacheGet.mockResolvedValue(null);
getTenantSubscriptionMock.mockRejectedValue(new Error("db down"));
setSubscriptionToPlanTier(() => "enterprise");
await expect(getCachedTenantPlan("tenant_2")).resolves.toBeNull();
});
test("classifier maps subscription to a plan tier", async () => {
cacheGet.mockResolvedValue({ tier: "enterprise" });
setSubscriptionToPlanTier((sub) => {
const tier = (sub as { tier?: string } | null)?.tier;
return tier === "enterprise" ? "enterprise" : tier === "pro" ? "pro" : "free";
});
await expect(getCachedTenantPlan("tenant_ent")).resolves.toBe("enterprise");
});
test("wireTenantPlanLookup registers exactly once", () => {
setTenantPlanLookupMock.mockClear();
wireTenantPlanLookup();
wireTenantPlanLookup();
expect(setTenantPlanLookupMock).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,87 @@
/**
* Tenant plan lookup wiring for BullMQ priority resolution.
*
* The queue package's `resolveJobPriorityForTenant` accepts a pluggable
* `TenantPlanLookup`. This module registers one that reads from the
* subscription cache (two-tier, L1 in-process + L2 SharedStore) so each
* enqueue is a cheap synchronous-ish lookup instead of a DB hit.
*
* Plan-tier mapping is intentionally pluggable: the boilerplate has no
* hard-coded `enterprise|pro|free` field on tenants. Operators wire their
* own classifier via `setSubscriptionToPlanTier`. Until that is set, this
* lookup returns `null` for every tenant, which the resolver then maps to
* NORMAL. Internal jobs (`tenantId: null`) still get CRITICAL.
*
* Bootstrap:
* ```ts
* import { wireTenantPlanLookup } from "~/utils/services/.server/tenantPlanLookup.server";
* wireTenantPlanLookup();
* ```
* Call once during web boot — idempotent.
*/
import type { TenantPlanIdentifier } from "@toolctrl/queue";
import { setTenantPlanLookup } from "@toolctrl/queue";
import type { TenantSubscriptionWithDetails } from "@toolctrl/db/subscriptions.server";
import { getTenantSubscription } from "@toolctrl/db/subscriptions.server";
import { getSubscriptionCache } from "./subscriptionCache.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("tenant-plan-lookup");
export type SubscriptionPlanClassifier = (
subscription: TenantSubscriptionWithDetails | null,
) => TenantPlanIdentifier | null;
let classifier: SubscriptionPlanClassifier = () => null;
let wired = false;
/**
* Replace the active classifier. Operators wire their own mapping
* (e.g. by stripe product id → "enterprise"|"pro"|"free"). Passing the
* default no-op classifier disables plan-based priority and falls back
* to NORMAL for all tenants.
*/
export function setSubscriptionToPlanTier(next: SubscriptionPlanClassifier): void {
classifier = next;
}
/**
* Cached lookup used by both the queue resolver and any caller that wants
* a cheap plan tier for the given tenant.
*/
export async function getCachedTenantPlan(tenantId: string): Promise<TenantPlanIdentifier | null> {
const cache = getSubscriptionCache();
let cached = await cache.get(tenantId);
if (cached === null) {
try {
const fresh = await getTenantSubscription(tenantId);
await cache.set(tenantId, fresh ?? null);
cached = fresh ?? null;
} catch (error) {
log.warn(
{ tenantId, error: error instanceof Error ? error.message : String(error) },
"getCachedTenantPlan: subscription fetch failed; returning null",
);
return null;
}
}
return classifier(cached);
}
/**
* Register the lookup on the queue package. Idempotent — calling twice is
* a no-op so per-request bootstraps don't churn the registration.
*/
export function wireTenantPlanLookup(): void {
if (wired) return;
wired = true;
setTenantPlanLookup((tenantId) => getCachedTenantPlan(tenantId));
log.info({}, "tenant plan lookup wired into queue priority resolver");
}
/** Test seam — drop the wiring + classifier. */
export function __resetTenantPlanLookupForTests(): void {
classifier = () => null;
wired = false;
setTenantPlanLookup(null);
}
@@ -0,0 +1,188 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Params } from "react-router";
vi.mock("../../db.server", () => ({
db: {
tenant: {
findFirst: vi.fn(),
},
},
}));
vi.mock("../../cache.server", () => ({
cachified: vi.fn(),
clearCacheKey: vi.fn(),
}));
import { cachified } from "../../cache.server";
import { db } from "../../db.server";
import { getTenantIdFromUrl, getTenantIdOrNull, resolveTenantLookupSource } from "./urlService";
const env = {
APP_BASE_DOMAIN: "localhost:3000",
WEB_APP_HOST: "app.localhost:3000",
ADMIN_APP_HOST: "admin.localhost:3000",
API_HOST: "api.localhost:3000",
APP_PROTOCOL: "http",
};
function makeRequest(host: string, pathname = "/app/acme") {
return new Request(`http://localhost:3000${pathname}`, {
headers: {
host,
},
});
}
async function expectRedirectToApp(promise: Promise<unknown>) {
try {
await promise;
throw new Error("Expected redirect to /app");
} catch (error) {
expect(error).toBeInstanceOf(Response);
expect((error as Response).status).toBe(302);
expect((error as Response).headers.get("Location")).toBe("http://app.localhost:3000/");
}
}
describe("resolveTenantLookupSource", () => {
beforeEach(() => {
vi.stubEnv("APP_BASE_DOMAIN", env.APP_BASE_DOMAIN);
vi.stubEnv("WEB_APP_HOST", env.WEB_APP_HOST);
vi.stubEnv("ADMIN_APP_HOST", env.ADMIN_APP_HOST);
vi.stubEnv("API_HOST", env.API_HOST);
vi.stubEnv("APP_PROTOCOL", env.APP_PROTOCOL);
});
it("uses explicit params when no request exists to keep route-loader behavior stable", () => {
expect(resolveTenantLookupSource({ params: { tenant: "acme" } })).toEqual({ source: "app-route-param", tenant: "acme" });
expect(resolveTenantLookupSource({ params: {} })).toEqual({ source: "none", tenant: null });
});
it("allows tenant lookup only for app-host requests with params or legacy app paths", () => {
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } })).toEqual({
source: "app-route-param",
tenant: "acme",
});
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/app/acme/dashboard"), params: {} })).toEqual({
source: "app-route-param",
tenant: "acme",
});
});
it.each([
["admin", env.ADMIN_APP_HOST],
["api", env.API_HOST],
["root", env.APP_BASE_DOMAIN],
["unknown", "unknown.localhost:3000"],
])("does not infer tenant context for %s-host /app paths", (_label, host) => {
expect(resolveTenantLookupSource({ request: makeRequest(host, "/app/acme/dashboard"), params: { tenant: "acme" } })).toEqual({
source: "none",
tenant: null,
});
});
it("keeps public app-host routes out of tenant resolution", () => {
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/app"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/login"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest(env.WEB_APP_HOST, "/reset?token=abc"), params: {} })).toEqual({ source: "none", tenant: null });
});
it("does not self-redirect when the app host is also the base domain", () => {
vi.stubEnv("APP_BASE_DOMAIN", "boiler.saas-ctrl.com");
vi.stubEnv("WEB_APP_HOST", "boiler.saas-ctrl.com");
vi.stubEnv("ADMIN_APP_HOST", "admin.boiler.saas-ctrl.com");
vi.stubEnv("API_HOST", "api.boiler.saas-ctrl.com");
vi.stubEnv("APP_PROTOCOL", "https");
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/app"), params: {} })).toEqual({ source: "none", tenant: null });
expect(resolveTenantLookupSource({ request: makeRequest("boiler.saas-ctrl.com", "/login"), params: {} })).toEqual({ source: "none", tenant: null });
});
});
describe("getTenantIdOrNull", () => {
beforeEach(() => {
vi.stubEnv("APP_BASE_DOMAIN", env.APP_BASE_DOMAIN);
vi.stubEnv("WEB_APP_HOST", env.WEB_APP_HOST);
vi.stubEnv("ADMIN_APP_HOST", env.ADMIN_APP_HOST);
vi.stubEnv("API_HOST", env.API_HOST);
vi.stubEnv("APP_PROTOCOL", env.APP_PROTOCOL);
vi.clearAllMocks();
});
it.each([
["admin", env.ADMIN_APP_HOST],
["api", env.API_HOST],
["root", env.APP_BASE_DOMAIN],
["unknown", "unknown.localhost:3000"],
])("returns null without DB lookup for %s-host /app paths", async (_label, host) => {
await expect(getTenantIdOrNull({ request: makeRequest(host, "/app/acme/dashboard"), params: { tenant: "acme" } })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("allows admin-host routes to opt into tenant scope through tenantId query parameters", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdOrNull({ request: makeRequest(env.ADMIN_APP_HOST, "/forms?tenantId=acme"), params: {} })).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
it("keeps admin-host routes global when tenantId query parameters are absent", async () => {
await expect(getTenantIdOrNull({ request: makeRequest(env.ADMIN_APP_HOST, "/forms"), params: {} })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("looks up exactly one tenant-bearing app-host request and returns its id", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } })).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledTimes(1);
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
it("returns null for public app-host routes without DB lookup", async () => {
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/"), params: {} })).resolves.toBeNull();
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/app"), params: {} })).resolves.toBeNull();
await expect(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/login"), params: {} })).resolves.toBeNull();
expect(db.tenant.findFirst).not.toHaveBeenCalled();
});
it("redirects app-host requests with unknown tenants to /app", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce(null);
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await expectRedirectToApp(getTenantIdOrNull({ request: makeRequest(env.WEB_APP_HOST, "/acme/dashboard"), params: { tenant: "acme" } }));
expect(db.tenant.findFirst).toHaveBeenCalledTimes(1);
consoleLog.mockRestore();
});
});
describe("getTenantIdFromUrl", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async ({ getFreshValue }: { getFreshValue: (context?: unknown) => unknown }) => getFreshValue()) as typeof cachified);
});
it("keeps explicit tenant param lookup behavior stable", async () => {
vi.mocked(db.tenant.findFirst).mockResolvedValueOnce({ id: "tenant_1" });
await expect(getTenantIdFromUrl({ tenant: "acme" } as Params)).resolves.toBe("tenant_1");
expect(db.tenant.findFirst).toHaveBeenCalledWith({
where: { OR: [{ slug: "acme" }, { id: "acme" }] },
select: { id: true },
});
});
});
@@ -0,0 +1,133 @@
import { redirect } from "react-router";
import { db } from "../../db.server";
import { Params } from "react-router";
import UrlUtils from "../../app/UrlUtils";
import { getHostRoutingContextFromRequest } from "../../app/HostRouting.server";
import { isWebRoutePath } from "../../app/PublicRouteSegments";
import { cachified, clearCacheKey } from "../../cache.server";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
export type TenantResolverSource = "app-route-param" | "admin-query-param" | "none" | "invalid-app-route";
export type TenantResolverResult =
| { source: "app-route-param"; tenant: string }
| { source: "admin-query-param"; tenant: string }
| { source: "none"; tenant: null }
| { source: "invalid-app-route"; tenant: null };
export function resolveTenantLookupSource({ request, params }: { request?: Request; params: Params }): TenantResolverResult {
if (!request) {
return getTenantResolverResultFromParams(params);
}
const context = getHostRoutingContextFromRequest(request);
if (context === "admin") {
const tenant = normalizeTenantParam(new URL(request.url).searchParams.get("tenantId"));
return tenant ? { source: "admin-query-param", tenant } : { source: "none", tenant: null };
}
if (context !== "app") {
return { source: "none", tenant: null };
}
return getTenantResolverResultForAppRequest(request, params);
}
export async function getTenantIdFromUrl(params: Params) {
const { tenant } = params;
const normalizedTenant = typeof tenant === "string" ? tenant.trim() : "";
if (!normalizedTenant) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdFromUrl(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
let tenantFromParams = await cachified({
key: `tenantIdOrSlug:${normalizedTenant}`,
ttl: 1000 * 60 * 60 * 24,
getFreshValue: () => getTenantByIdOrSlug(normalizedTenant),
});
if (!tenantFromParams) {
tenantFromParams = await getTenantByIdOrSlug(normalizedTenant);
if (tenantFromParams) {
clearCacheKey(`tenant:${normalizedTenant}`);
clearCacheKey(`tenant:${tenantFromParams}`);
clearCacheKey(`tenantIdOrSlug:${normalizedTenant}`);
clearCacheKey(`tenantIdOrSlug:${tenantFromParams}`);
clearCacheKey(`tenantSimple:${tenantFromParams}`);
}
}
if (!tenantFromParams) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdFromUrl(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
return tenantFromParams;
}
export async function getTenantIdOrNull({ request, params }: { request: Request; params: Params }) {
const resolverResult = resolveTenantLookupSource({ request, params });
if (resolverResult.source === "none") {
return null;
}
if (resolverResult.source === "invalid-app-route") {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdOrNull(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
const tenantFromParams = await getTenantByIdOrSlug(resolverResult.tenant);
if (!tenantFromParams) {
// eslint-disable-next-line no-console
console.log("[urlService] getTenantIdOrNull(): Redirecting to app root");
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
return tenantFromParams;
}
export async function getTenantByIdOrSlug(tenant: string | undefined) {
return (
(
await db.tenant.findFirst({
where: { OR: [{ slug: tenant }, { id: tenant }] },
select: { id: true },
})
)?.id ?? ""
);
}
function getTenantResolverResultFromParams(params: Params): TenantResolverResult {
const tenant = normalizeTenantParam(params.tenant);
return tenant ? { source: "app-route-param", tenant } : { source: "none", tenant: null };
}
function getTenantResolverResultForAppRequest(request: Request, params: Params): TenantResolverResult {
const pathname = new URL(request.url).pathname;
if (pathname === "/" || pathname === "/app" || isWebRoutePath(pathname)) {
return { source: "none", tenant: null };
}
const tenant = normalizeTenantParam(params.tenant) ?? getLegacyAppTenantFromPathname(pathname);
if (tenant) {
return { source: "app-route-param", tenant };
}
return { source: "invalid-app-route", tenant: null };
}
function getLegacyAppTenantFromPathname(pathname: string) {
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
const strippedPathname = UrlUtils.stripTrailingSlash(normalizedPathname);
if (strippedPathname === "/app") {
return null;
}
return normalizedPathname.match(/^\/app\/([^/]+)/)?.[1] ?? null;
}
function normalizeTenantParam(tenant: Params["tenant"] | null) {
return typeof tenant === "string" && tenant.trim() ? tenant : null;
}