Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -14,25 +14,30 @@ import {
type TenantSubscriptionWithDetails,
} from "@hivegrid/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 { getBaseURL } from "../../url.server";
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 { 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";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { cancelRecurringProductAcquisition, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
const ADMIN_MRR_TENANT_QUERY_BATCH_SIZE = 10;
function getActiveTenantSubscriptionProducts(subscription: TenantSubscriptionWithDetails | null): TenantSubscriptionWithDetails["products"] {
const now = Date.now();
return subscription?.products.filter((product) => !product.endsAt || new Date(product.endsAt).getTime() > now) ?? [];
return (
subscription?.products.filter(
(product) =>
!product.cancelledAt &&
(!product.currentPeriodStart || new Date(product.currentPeriodStart).getTime() <= now) &&
(!product.endsAt || new Date(product.endsAt).getTime() > now)
) ?? []
);
}
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
@@ -44,8 +49,15 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; code?: string | null; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
const features: {
name: string;
code?: string | null;
order: number;
title: string;
type: SubscriptionFeatureLimitType;
value: number;
accumulate: boolean;
}[] = await getAllSubscriptionFeatures();
features
.filter((f) => (f.code || f.name) && (f.code || f.name) !== DefaultFeatures.Credits)
.forEach((feature) => {
@@ -314,57 +326,62 @@ async function getSpentCredits(where: Prisma.CreditWhereInput): Promise<number>
// }
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.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
start: DateUtils.getDateStartOfDay(item.currentPeriodStart),
end: DateUtils.getDateEndOfDay(item.currentPeriodEnd),
// This service is also called outside the app route middleware. Bind the
// tenant here so forced RLS never turns a valid subscription into a silent
// null result on staging/production while preserving an inherited user id.
return await runWithRlsContext({ tenantId }, async () => {
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.billingProviderSubscriptionId) {
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 updatedItem = await updateTenantSubscriptionProduct(
{ id: item.id, tenantId: mySubscription.tenantId },
{
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
}
: undefined;
const today = new Date();
let todayIsInCurrentPeriod = false;
if (currentPeriod) {
todayIsInCurrentPeriod = today >= item.currentPeriodStart! && today <= item.currentPeriodEnd!;
);
// Cross-replica purge: 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);
}
}
if (currentPeriod && todayIsInCurrentPeriod) {
item.currentPeriodStart = currentPeriod.start;
item.currentPeriodEnd = currentPeriod.end;
} else {
const updatedItem = await updateTenantSubscriptionProduct({ id: item.id, tenantId: mySubscription.tenantId }, {
currentPeriodStart: item.currentPeriodStart,
currentPeriodEnd: item.currentPeriodEnd,
});
// Cross-replica purge: 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;
})
);
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
}
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 () => undefined)
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
await Promise.all(mySubscription.products.map(async () => undefined));
mySubscription.products = getActiveTenantSubscriptionProducts(mySubscription);
return mySubscription;
})
);
@@ -401,23 +418,28 @@ export async function persistCheckoutSessionStatus({
id,
fromUrl,
fromUserId,
fromTenantId,
tenantId,
}: {
request: Request;
id: string;
fromUrl: string;
fromUserId?: string | null;
fromTenantId?: string | null;
tenantId: string;
}) {
void request;
void id;
void fromUrl;
void fromUserId;
void fromTenantId;
void tenantId;
}
export async function getMrr(currency: string) {
const activeSubscriptions = await getActiveTenantsSubscriptions();
export async function getMrr(currency: string, tenantIds: string[]) {
const activeSubscriptions = (await getTenantSubscriptionsInRlsBatches(tenantIds))
.filter((subscription): subscription is TenantSubscriptionWithDetails => subscription !== null)
.map((subscription) => ({
...subscription,
products: subscription.products.filter((product) => !product.endsAt || new Date(product.endsAt) > new Date()),
}));
let summary: { total: number; count: number } = {
total: 0,
count: 0,
@@ -433,6 +455,15 @@ export async function getMrr(currency: string) {
return summary;
}
async function getTenantSubscriptionsInRlsBatches(tenantIds: string[]): Promise<(TenantSubscriptionWithDetails | null)[]> {
const subscriptions: (TenantSubscriptionWithDetails | null)[] = [];
for (let index = 0; index < tenantIds.length; index += ADMIN_MRR_TENANT_QUERY_BATCH_SIZE) {
const batch = tenantIds.slice(index, index + ADMIN_MRR_TENANT_QUERY_BATCH_SIZE);
subscriptions.push(...(await Promise.all(batch.map((tenantId) => runWithRlsContext({ tenantId }, () => getTenantSubscription(tenantId))))));
}
return subscriptions;
}
function getPriceInCurrency(subscriptionPrice: SubscriptionPrice | null, currency: string) {
if (!subscriptionPrice) {
return 0;
@@ -500,9 +531,11 @@ export async function clearAllSubscriptionsCache() {
clearCacheKey(`tenantSubscription:${tenantSub.tenantId}`);
});
// Wildcard fan-out — peer replicas flush their L1 entirely.
await getSubscriptionCache().invalidate().catch(() => {
/* logged inside helper */
});
await getSubscriptionCache()
.invalidate()
.catch(() => {
/* logged inside helper */
});
}
export async function cancelTenantSubscription(
@@ -513,27 +546,36 @@ export async function cancelTenantSubscription(
if (!tenantSubscriptionProduct) {
throw new Error("Subscription product not found");
}
if (tenantSubscriptionProduct.subscriptionProduct.kind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition) {
throw new ProductAcquisitionError("ACQUISITION_NOT_FOUND");
}
if (tenantSubscriptionProduct.acquisition.productKind !== "recurring_add_on") {
throw new ProductAcquisitionError("PRODUCT_KIND_INVALID");
}
if (!tenantSubscriptionProduct.acquisition.lagoSubscriptionId?.trim()) {
throw new ProductAcquisitionError("IDEMPOTENCY_CONFLICT");
}
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 cancelTenantSubscriptionProduct(tenantSubscriptionProduct.id, tenantId, {
cancelledAt: new Date(),
endsAt: new Date(),
if (!user || !tenant) throw new Error("Subscription cancellation actor or tenant not found");
const eventData = {
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 cancelRecurringProductAcquisition({
tenantId,
actorUserId: user.id,
tenantSubscriptionProductId: tenantSubscriptionProduct.id,
eventData,
});
clearTenantSubscriptionCache(tenantId);
}