Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,4 +1,4 @@
import { Prisma, SubscriptionPrice } from "@toolctrl/db/prisma-browser";
import { Prisma, SubscriptionPrice } from "@hivegrid/db/prisma-browser";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
@@ -6,21 +6,17 @@ import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/Sub
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";
} 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 { 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";
@@ -34,6 +30,11 @@ import EmailTemplates from "~/modules/emails/utils/EmailTemplates";
import { getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
function getActiveTenantSubscriptionProducts(subscription: TenantSubscriptionWithDetails | null): TenantSubscriptionWithDetails["products"] {
const now = Date.now();
return subscription?.products.filter((product) => !product.endsAt || new Date(product.endsAt).getTime() > now) ?? [];
}
export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?: TenantSubscriptionWithDetails | null): Promise<PlanFeatureUsageDto[]> {
let subscription: TenantSubscriptionWithDetails | null = null;
if (tenantSubscription === undefined) {
@@ -43,16 +44,17 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
}
const myUsage: PlanFeatureUsageDto[] = [];
let allFeatures: SubscriptionFeatureDto[] = [];
const features: { name: string; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
const features: { name: string; code?: string | null; order: number; title: string; type: SubscriptionFeatureLimitType; value: number; accumulate: boolean }[] =
await getAllSubscriptionFeatures();
features
.filter((f) => f.name)
.filter((f) => (f.code || f.name) && (f.code || f.name) !== DefaultFeatures.Credits)
.forEach((feature) => {
const existing = allFeatures.find((f) => f.name === feature.name);
const featureName = feature.code || feature.name;
const existing = allFeatures.find((f) => f.name === featureName);
if (!existing) {
allFeatures.push({
order: feature.order,
name: feature.name,
name: featureName,
title: feature.title,
type: feature.type,
value: feature.value,
@@ -65,7 +67,8 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
await Promise.all(
allFeatures.map(async (item) => {
let myFeatures: SubscriptionFeatureDto[] = [];
subscription?.products.forEach((product) => {
const activeProducts = getActiveTenantSubscriptionProducts(subscription);
activeProducts.forEach((product) => {
const feature = product.subscriptionProduct.features.find((f) => f.name === item.name);
if (feature) {
if (!product.quantity) {
@@ -80,9 +83,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
});
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,
@@ -97,7 +98,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
if (!existingSubscriptionFeature) {
usage.type = SubscriptionFeatureLimitType.NOT_INCLUDED;
usage.enabled = false;
if (subscription?.products && subscription.products.length > 0) {
if (activeProducts.length > 0) {
usage.message = "featureLimits.upgradeSubscription";
} else {
usage.message = "featureLimits.noSubscription";
@@ -110,7 +111,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
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.message = `You've reached the limit (${usage.used}/${usage.value}) for ${feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.MONTHLY) {
@@ -121,7 +122,7 @@ export async function getPlanFeaturesUsage(tenantId: string, tenantSubscription?
// 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.message = `You've reached the limit this month (${usage.used}/${usage.value}) for ${feature.name}`;
usage.enabled = false;
}
} else if (feature.type === SubscriptionFeatureLimitType.UNLIMITED) {
@@ -185,7 +186,7 @@ function getUsedPeriod(subscription: TenantSubscriptionWithDetails | null) {
lastDay = new Date(y + 1, 0, 0, 23, 59, 59);
}
subscription?.products.forEach((product) => {
getActiveTenantSubscriptionProducts(subscription).forEach((product) => {
if (product.currentPeriodStart && product.currentPeriodEnd) {
firstDay = product.currentPeriodStart;
lastDay = product.currentPeriodEnd;
@@ -252,33 +253,9 @@ async function getUsed(tenantId: string, feature: SubscriptionFeatureDto, subscr
} 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;
}
}
// Entity-based feature usage was tracked through the generic entity-builder,
// which has been removed. Such features no longer have a row-based usage count.
return 0;
}
@@ -345,7 +322,7 @@ export async function getActiveTenantSubscriptions(tenantId: string) {
if (mySubscription) {
await Promise.all(
mySubscription.products.map(async (item) => {
if (item.stripeSubscriptionId) {
if (item.billingProviderSubscriptionId) {
let currentPeriod =
item.currentPeriodStart && item.currentPeriodEnd
? {
@@ -362,18 +339,11 @@ export async function getActiveTenantSubscriptions(tenantId: string) {
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
// 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);
@@ -392,15 +362,7 @@ export async function getActiveTenantsSubscriptions() {
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.map(async () => undefined)
);
mySubscription.products = mySubscription.products.filter((f) => !f.endsAt || new Date(f.endsAt) > new Date());
return mySubscription;
@@ -417,23 +379,16 @@ export async function reportUsage(tenantId: string, unit: string) {
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,
});
}
await createTenantSubscriptionUsageRecord({
tenantId,
tenantSubscriptionId: tenantSubscription.id,
tenantSubscriptionProductPriceId: price.id,
metricCode: unit,
timestamp: Math.floor(Date.now() / 1000),
quantity: 1,
billingProviderSubscriptionItemId: null,
});
}
})
);
@@ -454,40 +409,11 @@ export async function persistCheckoutSessionStatus({
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,
}),
});
}
}
}
}
void request;
void id;
void fromUrl;
void fromUserId;
void fromTenantId;
}
export async function getMrr(currency: string) {
@@ -545,8 +471,8 @@ export function convertToCurrency({ from, price, to }: { from: string; price: nu
/**
* 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.
* `clearAllSubscriptionsCache` whenever the change is tenant-scoped 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.
@@ -587,9 +513,6 @@ export async function cancelTenantSubscription(
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) {
@@ -609,10 +532,8 @@ export async function cancelTenantSubscription(
} 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(),
endsAt: new Date(),
});
}