Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+1010
File diff suppressed because it is too large.
Load diff
+664
@@ -0,0 +1,664 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useActionData, useFetcher, useLoaderData, useNavigate, useRevalidator, useSubmit } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
buildSeatUsageVM,
|
||||
buildSelfServiceSubscriptionManagementPolicyVM,
|
||||
buildSelfServiceSubscriptionPageVM,
|
||||
buildSubscriptionOverviewVM,
|
||||
type SelfServiceSubscriptionPageVM,
|
||||
type SelfServiceCheckoutPaymentMethodsVM,
|
||||
type SelfServiceSubscriptionPricePreviewVM,
|
||||
type SubscriptionOverviewEntitlementInput,
|
||||
type SubscriptionOverviewProductInput,
|
||||
type SubscriptionOverviewVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { defaultBrandLinks } from "@hivegrid/brand";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { computeSeatUsage, getSeatPackage, resolveSeatPackageId } from "@hivegrid/entitlements";
|
||||
import {
|
||||
SelfServiceSubscriptionPage,
|
||||
type SelfServiceSubscriptionPlanAdvice,
|
||||
type SelfServiceSubscriptionSelection,
|
||||
} from "~/components/screens/billing/SelfServiceSubscriptionPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getRegistrationBillingPreference } from "~/utils/db/registration.db.server";
|
||||
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { apiUrl, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { cancelTenantSubscription, getPlanFeaturesUsage } from "~/utils/services/.server/subscriptionService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { requiresTenantSubscriptionActivation } from "~/utils/app/SubscriptionAccess";
|
||||
import { getSubscriptionFeatureTitleKey } from "~/utils/app/SubscriptionFeatureText";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import { createSelfServiceCheckout, SelfServiceCheckoutError } from "~/services/billing/self-service-checkout.server";
|
||||
import { loadTenantRegistrationBillingPreference } from "~/services/billing/registration-billing-preference.server";
|
||||
import { loadRegistrationPlanSelection } from "~/services/billing/registration-plan-selection.server";
|
||||
import { createProductAcquisition, productAcquisitionReturnIdPlaceholder, ProductAcquisitionError } from "~/services/billing/product-acquisition.server";
|
||||
import { loadCheckoutPaymentMethods } from "~/services/billing/payment-methods.server";
|
||||
import { reserveRecurringProductCheckoutLedger } from "~/services/billing/recurring-checkout-policy.server";
|
||||
import {
|
||||
previewSelfServiceSubscription,
|
||||
resolveCurrentRecurringGrossTotalCents,
|
||||
resolveOtherActiveRecurringGrossTotalCents,
|
||||
resolveSelfServicePreferredSelection,
|
||||
SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
|
||||
SelfServiceSubscriptionValidationError,
|
||||
loadSelfServiceSubscriptionServerContext,
|
||||
} from "~/services/billing/self-service-subscription.server";
|
||||
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
vm: SelfServiceSubscriptionPageVM;
|
||||
initialPlanAdvice: SelfServiceSubscriptionPlanAdvice | null;
|
||||
initialEmailMarketingAddOnCode: string | null;
|
||||
};
|
||||
|
||||
export function readRegistrationSeatPreference(searchParams: URLSearchParams): {
|
||||
officeSeatQuantity: number;
|
||||
fieldSeatQuantity: number;
|
||||
} | null {
|
||||
const officeRaw = searchParams.get("office_seats")?.trim() ?? "";
|
||||
const fieldRaw = searchParams.get("field_seats")?.trim() ?? "";
|
||||
if (!officeRaw && !fieldRaw) return null;
|
||||
if (!/^\d{1,5}$/u.test(officeRaw) || !/^\d{1,5}$/u.test(fieldRaw)) return null;
|
||||
const officeSeatQuantity = Number(officeRaw);
|
||||
const fieldSeatQuantity = Number(fieldRaw);
|
||||
if (officeSeatQuantity < 1 || officeSeatQuantity > 10_000 || fieldSeatQuantity < 0 || fieldSeatQuantity > 10_000) return null;
|
||||
return { officeSeatQuantity, fieldSeatQuantity };
|
||||
}
|
||||
|
||||
export function customerPortalSettingsPath(tenantSlug: string): string {
|
||||
return appPath({ tenantSlug, path: "settings/customer-portal", mode: "host-aware" });
|
||||
}
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
preview?: SelfServiceSubscriptionPricePreviewVM;
|
||||
paymentMethods?: SelfServiceCheckoutPaymentMethodsVM;
|
||||
planAdvice?: SelfServiceSubscriptionPlanAdvice;
|
||||
emailMarketingPreview?: {
|
||||
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number];
|
||||
paymentMethods: SelfServiceCheckoutPaymentMethodsVM;
|
||||
};
|
||||
};
|
||||
|
||||
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
||||
|
||||
async function hasPermission(request: Request, permission: DefaultPermission, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, permission, tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && ((error.status >= 300 && error.status < 400) || error.status === 403 || error.status === 404)) return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function toIso(value: Date | string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.settings.subscription");
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await time(getTenantIdFromUrl(params), "getTenantIdFromUrl");
|
||||
await time(verifyUserHasPermission(request, "app.settings.subscription.view", tenantId), "verifyUserHasPermission");
|
||||
|
||||
const userInfo = await time(getUserInfo(request), "getUserInfo");
|
||||
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
|
||||
Promise.all([time(getUser(userInfo.userId), "getUser"), time(getTenant(tenantId), "getTenant")])
|
||||
);
|
||||
if (!user) return badRequest({ error: t("shared.invalidUser") });
|
||||
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
|
||||
|
||||
const title = `${t("billing:selfServiceSubscription.title")} | ${process.env.APP_NAME}`;
|
||||
const contactHref = `${defaultBrandLinks.siteUrl}/kontakt`;
|
||||
const [canUpdate, canDelete, selfServiceContext] = await Promise.all([
|
||||
time(hasPermission(request, "app.settings.subscription.update", tenantId), "verifySubscriptionUpdatePermission"),
|
||||
time(hasPermission(request, "app.settings.subscription.delete", tenantId), "verifySubscriptionDeletePermission"),
|
||||
time(loadSelfServiceSubscriptionServerContext(tenantId), "loadSelfServiceSubscriptionServerContext"),
|
||||
]);
|
||||
const { tenantSubscription, billingState, catalog, minimumSeatQuantity, seatCounts, storageAddOns, emailMarketingAddOns, usage, currentSelection } =
|
||||
selfServiceContext;
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
const requestedSelection = resolveSelfServicePreferredSelection(catalog, searchParams.get("selected_price"), readRegistrationSeatPreference(searchParams));
|
||||
const registrationPreference = tenantSubscription
|
||||
? null
|
||||
: await runWithRlsContext({ tenantId, userId: userInfo.userId }, async () => {
|
||||
const tenantPreference = await time(loadTenantRegistrationBillingPreference(tenantId), "loadTenantRegistrationBillingPreference");
|
||||
if (tenantPreference) return tenantPreference;
|
||||
// Rolling compatibility for accounts completed through the email-
|
||||
// verification path before tenant-scoped preference persistence.
|
||||
return await time(getRegistrationBillingPreference(tenantId, userInfo.userId), "getRegistrationBillingPreference");
|
||||
});
|
||||
const persistedSelection = registrationPreference
|
||||
? resolveSelfServicePreferredSelection(catalog, registrationPreference.selectedSubscriptionPriceId, {
|
||||
officeSeatQuantity: registrationPreference.selectedOfficeSeatQuantity,
|
||||
fieldSeatQuantity: registrationPreference.selectedFieldSeatQuantity,
|
||||
})
|
||||
: null;
|
||||
const preferredSelection = tenantSubscription ? null : (requestedSelection ?? persistedSelection);
|
||||
const initialPlanAdvice = tenantSubscription
|
||||
? null
|
||||
: await time(
|
||||
loadRegistrationPlanSelection(null, {
|
||||
officeSeatQuantity: Math.max(1, preferredSelection?.officeSeatQuantity ?? seatCounts.office),
|
||||
fieldSeatQuantity: Math.max(0, preferredSelection?.fieldSeatQuantity ?? seatCounts.field),
|
||||
}),
|
||||
"loadRegistrationPlanSelection"
|
||||
);
|
||||
let overview: SubscriptionOverviewVM;
|
||||
if (!tenantSubscription) {
|
||||
overview = buildSubscriptionOverviewVM({
|
||||
hasSubscription: false,
|
||||
status: null,
|
||||
seatUsage: { status: "empty" },
|
||||
products: [],
|
||||
entitlements: [],
|
||||
canCancel: false,
|
||||
contactHref,
|
||||
});
|
||||
} else {
|
||||
const features = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
|
||||
time(getPlanFeaturesUsage(tenantId, tenantSubscription), "subscription[getPlanFeaturesUsage]")
|
||||
);
|
||||
const seatPackageId = resolveSeatPackageId(
|
||||
billingState.planCode,
|
||||
currentSelection?.planCode,
|
||||
...tenantSubscription.products.flatMap((product) => [product.planCode, product.subscriptionProduct?.title, product.subscriptionProduct?.code])
|
||||
);
|
||||
const seatPackage = seatPackageId ? getSeatPackage(seatPackageId) : undefined;
|
||||
const seatUsageProjection = seatPackage ? computeSeatUsage({ package: seatPackage, officeUsed: seatCounts.office, fieldUsed: seatCounts.field }) : null;
|
||||
const seatUsage = buildSeatUsageVM({ packageId: seatPackageId, usage: seatUsageProjection, counts: seatCounts });
|
||||
const products: SubscriptionOverviewProductInput[] = tenantSubscription.products.map((product) => {
|
||||
const productPackageId = resolveSeatPackageId(product.planCode, product.subscriptionProduct.code, product.subscriptionProduct.title);
|
||||
return {
|
||||
id: product.id,
|
||||
titleKey: productPackageId ? `settings.subscription.checkout.plans.packages.${productPackageId}.title` : product.subscriptionProduct.title,
|
||||
code: product.planCode ?? product.subscriptionProduct.code,
|
||||
kind: product.subscriptionProduct.kind,
|
||||
acquisition: product.acquisition
|
||||
? {
|
||||
productKind: product.acquisition.productKind,
|
||||
status: product.acquisition.status,
|
||||
lagoSubscriptionId: product.acquisition.lagoSubscriptionId,
|
||||
}
|
||||
: null,
|
||||
quantity: product.quantity ?? product.seatQuantity,
|
||||
cancelledAt: toIso(product.cancelledAt),
|
||||
endsAt: toIso(product.endsAt),
|
||||
currentPeriodStart: toIso(product.currentPeriodStart),
|
||||
currentPeriodEnd: toIso(product.currentPeriodEnd),
|
||||
prices: product.prices
|
||||
.filter((price) => !price.isMetered && price.subscriptionPrice)
|
||||
.map((price) => ({
|
||||
amount: price.subscriptionPrice ? Number(price.subscriptionPrice.price) : null,
|
||||
currency: price.subscriptionPrice?.currency ?? null,
|
||||
billingPeriod: price.subscriptionPrice?.billingPeriod ?? null,
|
||||
quantity: price.quantity,
|
||||
})),
|
||||
};
|
||||
});
|
||||
const entitlements: SubscriptionOverviewEntitlementInput[] = features.map((feature) => ({
|
||||
code: feature.name,
|
||||
titleKey: getSubscriptionFeatureTitleKey(feature),
|
||||
enabled: feature.enabled,
|
||||
value: feature.value,
|
||||
used: feature.used,
|
||||
remaining: feature.remaining,
|
||||
}));
|
||||
overview = buildSubscriptionOverviewVM({
|
||||
hasSubscription: true,
|
||||
status: billingState.status,
|
||||
trialEndsAt: toIso(billingState.trialEndsAt),
|
||||
planCode: billingState.planCode,
|
||||
seatUsage,
|
||||
products,
|
||||
entitlements,
|
||||
canCancel: canUpdate && canDelete,
|
||||
contactHref,
|
||||
});
|
||||
}
|
||||
|
||||
const managementPolicy = buildSelfServiceSubscriptionManagementPolicyVM({
|
||||
planOrder: catalog.plans.map((plan) => plan.code),
|
||||
effectiveAtByChangeKind: SELF_SERVICE_SUBSCRIPTION_EFFECTIVE_AT_POLICY,
|
||||
});
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview,
|
||||
catalog,
|
||||
managementPolicy,
|
||||
minimumSeatQuantity,
|
||||
minimumSeatQuantities: seatCounts,
|
||||
storageAddOns,
|
||||
emailMarketingAddOns,
|
||||
usage,
|
||||
canManage: canUpdate,
|
||||
billingHref: appPath({ tenantSlug: tenant.slug, path: "settings/billing", mode: "host-aware" }),
|
||||
currentSelection,
|
||||
preferredSelection,
|
||||
});
|
||||
|
||||
const requestedEmailMarketingAddOnCode = searchParams.get("email_add_on")?.trim() ?? "";
|
||||
const initialEmailMarketingAddOnCode = emailMarketingAddOns.find((addOn) => addOn.code === requestedEmailMarketingAddOnCode && !addOn.active)?.code ?? null;
|
||||
|
||||
return Response.json({ title, vm, initialPlanAdvice, initialEmailMarketingAddOnCode } satisfies LoaderData, { headers: getServerTimingHeader() });
|
||||
};
|
||||
|
||||
function readPlanAdviceSeatQuantities(form: FormData): {
|
||||
officeSeatQuantity: number;
|
||||
fieldSeatQuantity: number;
|
||||
} {
|
||||
const officeRaw = form.get("office-seat-quantity")?.toString().trim() ?? "";
|
||||
const fieldRaw = form.get("field-seat-quantity")?.toString().trim() ?? "";
|
||||
if (!/^\d{1,5}$/u.test(officeRaw) || !/^\d{1,5}$/u.test(fieldRaw)) {
|
||||
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
|
||||
}
|
||||
const officeSeatQuantity = Number(officeRaw);
|
||||
const fieldSeatQuantity = Number(fieldRaw);
|
||||
if (officeSeatQuantity < 1 || officeSeatQuantity > 10_000 || fieldSeatQuantity < 0 || fieldSeatQuantity > 10_000) {
|
||||
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
|
||||
}
|
||||
return { officeSeatQuantity, fieldSeatQuantity };
|
||||
}
|
||||
|
||||
function readSelection(form: FormData): SelfServiceSubscriptionSelection {
|
||||
const productId = form.get("product-id")?.toString().trim() ?? "";
|
||||
const priceId = form.get("price-id")?.toString().trim() ?? "";
|
||||
const billingPeriodRaw = form.get("billing-period")?.toString().trim() ?? "";
|
||||
const billingPeriod = Number(billingPeriodRaw);
|
||||
const currency = form.get("currency")?.toString().trim() ?? "";
|
||||
const officeSeatQuantityRaw = form.get("office-seat-quantity")?.toString().trim() ?? "";
|
||||
const fieldSeatQuantityRaw = form.get("field-seat-quantity")?.toString().trim() ?? "";
|
||||
const legacySeatQuantityRaw = form.get("seat-quantity")?.toString().trim() ?? "";
|
||||
const usingLegacySeatQuantity = !officeSeatQuantityRaw && !fieldSeatQuantityRaw && Boolean(legacySeatQuantityRaw);
|
||||
const officeSeatQuantity = Number(usingLegacySeatQuantity ? legacySeatQuantityRaw : officeSeatQuantityRaw);
|
||||
const fieldSeatQuantity = Number(usingLegacySeatQuantity ? "0" : fieldSeatQuantityRaw);
|
||||
const storageAddOnCodes = form
|
||||
.getAll("storage-add-on-code")
|
||||
.map((value) => value.toString().trim())
|
||||
.filter(Boolean);
|
||||
if (!productId) throw new SelfServiceSubscriptionValidationError("PLAN_NOT_FOUND");
|
||||
if (!priceId) throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
|
||||
if (!billingPeriodRaw || !Number.isSafeInteger(billingPeriod) || billingPeriod < 0 || !currency) {
|
||||
throw new SelfServiceSubscriptionValidationError("PRICE_NOT_FOUND");
|
||||
}
|
||||
if (
|
||||
(!usingLegacySeatQuantity && (!officeSeatQuantityRaw || !fieldSeatQuantityRaw)) ||
|
||||
!Number.isSafeInteger(officeSeatQuantity) ||
|
||||
!Number.isSafeInteger(fieldSeatQuantity) ||
|
||||
officeSeatQuantity < 0 ||
|
||||
fieldSeatQuantity < 0 ||
|
||||
officeSeatQuantity + fieldSeatQuantity < 1
|
||||
) {
|
||||
throw new SelfServiceSubscriptionValidationError("SEAT_QUANTITY_INVALID");
|
||||
}
|
||||
return { productId, priceId, billingPeriod, currency, officeSeatQuantity, fieldSeatQuantity, storageAddOnCodes };
|
||||
}
|
||||
|
||||
function selectionForm(intent: "preview" | "checkout", selection: SelfServiceSubscriptionSelection, csrf: string): FormData {
|
||||
const form = new FormData();
|
||||
form.set("intent", intent);
|
||||
form.set("csrf", csrf);
|
||||
form.set("product-id", selection.productId);
|
||||
form.set("price-id", selection.priceId);
|
||||
form.set("billing-period", String(selection.billingPeriod));
|
||||
form.set("currency", selection.currency);
|
||||
form.set("office-seat-quantity", String(selection.officeSeatQuantity));
|
||||
form.set("field-seat-quantity", String(selection.fieldSeatQuantity));
|
||||
for (const code of selection.storageAddOnCodes) form.append("storage-add-on-code", code);
|
||||
if (selection.emailMarketingAddOnCode) form.set("email-marketing-add-on-code", selection.emailMarketingAddOnCode);
|
||||
return form;
|
||||
}
|
||||
|
||||
export const action: ActionFunction = async ({ request, params }) => {
|
||||
const { t, locale } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.update", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString() || form.get("action")?.toString();
|
||||
|
||||
try {
|
||||
if (intent === "plan-advice") {
|
||||
const seatQuantities = readPlanAdviceSeatQuantities(form);
|
||||
const planAdvice = await loadRegistrationPlanSelection(null, seatQuantities);
|
||||
return Response.json({ planAdvice } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "preview") {
|
||||
const selection = readSelection(form);
|
||||
const preview = await previewSelfServiceSubscription(tenantId, {
|
||||
productId: selection.productId,
|
||||
priceId: selection.priceId,
|
||||
officeSeatQuantity: selection.officeSeatQuantity,
|
||||
fieldSeatQuantity: selection.fieldSeatQuantity,
|
||||
storageAddOnCodes: selection.storageAddOnCodes,
|
||||
});
|
||||
const tenantSubscription = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => getTenantSubscription(tenantId));
|
||||
const otherRecurringGrossTotalCents = resolveOtherActiveRecurringGrossTotalCents(tenantSubscription);
|
||||
const paymentPolicyAmountCents =
|
||||
otherRecurringGrossTotalCents === null || !Number.isSafeInteger(preview.recurringGrossTotalCents + otherRecurringGrossTotalCents)
|
||||
? null
|
||||
: preview.recurringGrossTotalCents + otherRecurringGrossTotalCents;
|
||||
if (paymentPolicyAmountCents === null) throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
|
||||
const paymentMethods = await loadCheckoutPaymentMethods({
|
||||
amountCents: (preview.changeKind === "new" && preview.trialDays > 0) || preview.effectiveAt === "period_end" ? 0 : preview.recurringGrossTotalCents,
|
||||
policyAmountCents: paymentPolicyAmountCents,
|
||||
currency: preview.selectedPrice.currency,
|
||||
sequenceType: "first",
|
||||
locale: locale ?? "de",
|
||||
requirement: "any",
|
||||
});
|
||||
return Response.json({ preview, paymentMethods } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "checkout") {
|
||||
const selection = readSelection(form);
|
||||
const requestedEmailMarketingAddOnCode = form.get("email-marketing-add-on-code")?.toString().trim() ?? "";
|
||||
const emailMarketingAddOnCode = requestedEmailMarketingAddOnCode
|
||||
? (await loadSelfServiceSubscriptionServerContext(tenantId)).emailMarketingAddOns.find(
|
||||
(addOn) => addOn.code === requestedEmailMarketingAddOnCode && !addOn.active
|
||||
)?.code
|
||||
: null;
|
||||
if (requestedEmailMarketingAddOnCode && !emailMarketingAddOnCode) {
|
||||
return badRequest({ error: t("billing:selfServiceSubscription.emailMarketing.errors.selectionUnavailable") });
|
||||
}
|
||||
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => Promise.all([getUser(userInfo.userId), getTenant(tenantId)]));
|
||||
if (!user) return badRequest({ error: t("shared.invalidUser") });
|
||||
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
|
||||
const checkout = await createSelfServiceCheckout({
|
||||
request,
|
||||
checkoutRequestKey: form.get("checkout-request-key")?.toString() ?? "",
|
||||
tenantId,
|
||||
tenantSlug: tenant.slug,
|
||||
tenantName: tenant.name,
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
userName: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
|
||||
productId: selection.productId,
|
||||
priceId: selection.priceId,
|
||||
billingPeriod: selection.billingPeriod,
|
||||
currency: selection.currency,
|
||||
officeSeatQuantity: selection.officeSeatQuantity,
|
||||
fieldSeatQuantity: selection.fieldSeatQuantity,
|
||||
storageAddOnCodes: selection.storageAddOnCodes,
|
||||
paymentMethod: form.get("payment-method")?.toString() ?? null,
|
||||
paymentLocale: locale ?? "de",
|
||||
postActivationEmailMarketingAddOnCode: emailMarketingAddOnCode,
|
||||
});
|
||||
throw redirect(checkout.checkoutUrl);
|
||||
}
|
||||
|
||||
if (intent === "email-marketing-preview" || intent === "email-marketing-checkout") {
|
||||
const productId = form.get("product-id")?.toString().trim() ?? "";
|
||||
const priceId = form.get("price-id")?.toString().trim() ?? "";
|
||||
const context = await loadSelfServiceSubscriptionServerContext(tenantId);
|
||||
const selected = context.emailMarketingAddOns.find((addOn) => addOn.productId === productId && addOn.priceId === priceId && !addOn.active);
|
||||
if (!selected) {
|
||||
return badRequest({ error: t("billing:selfServiceSubscription.emailMarketing.errors.selectionUnavailable") });
|
||||
}
|
||||
if (intent === "email-marketing-preview") {
|
||||
const currentRecurringGrossTotalCents = resolveCurrentRecurringGrossTotalCents(context, {
|
||||
excludedProductCodes: context.emailMarketingAddOns.map((addOn) => addOn.code),
|
||||
});
|
||||
const paymentPolicyAmountCents =
|
||||
currentRecurringGrossTotalCents === null || !Number.isSafeInteger(currentRecurringGrossTotalCents + selected.grossAmountCents)
|
||||
? null
|
||||
: currentRecurringGrossTotalCents + selected.grossAmountCents;
|
||||
if (paymentPolicyAmountCents === null) {
|
||||
throw new ProductAcquisitionError("PAYMENT_METHOD_UNAVAILABLE");
|
||||
}
|
||||
const paymentMethods = await loadCheckoutPaymentMethods({
|
||||
amountCents: selected.grossAmountCents,
|
||||
policyAmountCents: paymentPolicyAmountCents,
|
||||
currency: selected.currency,
|
||||
sequenceType: "first",
|
||||
locale: locale ?? "de",
|
||||
});
|
||||
return Response.json({ emailMarketingPreview: { addOn: selected, paymentMethods } } satisfies ActionData);
|
||||
}
|
||||
const [user, tenant] = await runWithRlsContext({ tenantId, userId: userInfo.userId }, () => Promise.all([getUser(userInfo.userId), getTenant(tenantId)]));
|
||||
if (!user) return badRequest({ error: t("shared.invalidUser") });
|
||||
if (!tenant) return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
|
||||
const config = loadRequiredWebConfig();
|
||||
const acquisitionInput = {
|
||||
tenantId,
|
||||
tenantName: tenant.name,
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
userName: [user.firstName, user.lastName].filter(Boolean).join(" ") || user.email,
|
||||
productId: selected.productId,
|
||||
priceId: selected.priceId,
|
||||
scopeKey: "tenant",
|
||||
redirectUrl: absolutePublicAppPath(
|
||||
config.routing,
|
||||
`/subscribe/${encodeURIComponent(tenant.slug)}/product/${productAcquisitionReturnIdPlaceholder}/success`
|
||||
),
|
||||
webhookUrl: apiUrl({
|
||||
rootDomain: config.routing.apiHost,
|
||||
protocol: config.routing.protocol,
|
||||
path: "billing/mollie/webhooks",
|
||||
version: "v1",
|
||||
mode: "host-aware",
|
||||
}),
|
||||
paymentMethod: form.get("payment-method")?.toString() ?? null,
|
||||
paymentLocale: locale ?? "de",
|
||||
};
|
||||
const locked = await reserveRecurringProductCheckoutLedger(acquisitionInput, {
|
||||
replacedProductCodes: context.emailMarketingAddOns.map((addOn) => addOn.code),
|
||||
});
|
||||
const checkout = await createProductAcquisition({
|
||||
...acquisitionInput,
|
||||
paymentPolicyAmountCents: locked.paymentPolicyAmountCents,
|
||||
});
|
||||
if (!checkout.checkoutUrl) throw new ProductAcquisitionError("CHECKOUT_URL_MISSING");
|
||||
throw redirect(checkout.checkoutUrl);
|
||||
}
|
||||
|
||||
if (intent === "cancel") {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.delete", tenantId);
|
||||
const tenantSubscriptionProductId = form.get("tenant-subscription-product-id")?.toString() ?? "";
|
||||
await runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
|
||||
cancelTenantSubscription(tenantSubscriptionProductId, { t, tenantId, userId: userInfo.userId })
|
||||
);
|
||||
return Response.json({ success: t("settings.subscription.success.cancelled") });
|
||||
}
|
||||
|
||||
return badRequest({ error: t("billing:selfServiceSubscription.errors.unsupportedAction") });
|
||||
} catch (error) {
|
||||
if (error instanceof Response) throw error;
|
||||
if (error instanceof ProductAcquisitionError) {
|
||||
const providerUnavailable = error.code === "PROVIDER_CONFIGURATION_MISSING" || error.code === "PROVIDER_FAILED";
|
||||
const paymentMethodError = error.code === "PAYMENT_METHOD_INVALID" || error.code === "PAYMENT_METHOD_UNAVAILABLE";
|
||||
return Response.json(
|
||||
{
|
||||
error: t(
|
||||
providerUnavailable
|
||||
? "customerPortal.domain.errors.checkoutUnavailable"
|
||||
: paymentMethodError
|
||||
? `billing:selfServiceSubscription.errors.${error.code}`
|
||||
: "shared.unexpectedError"
|
||||
),
|
||||
},
|
||||
{ status: providerUnavailable ? 503 : 409 }
|
||||
);
|
||||
}
|
||||
if (error instanceof SelfServiceSubscriptionValidationError || error instanceof SelfServiceCheckoutError) {
|
||||
return badRequest({ error: t(error.i18nKey) });
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return badRequest({ error: t("shared.unexpectedError") });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export default function SubscriptionRoute() {
|
||||
const { vm, initialPlanAdvice, initialEmailMarketingAddOnCode } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const planAdviceFetcher = useFetcher<ActionData>();
|
||||
const previewFetcher = useFetcher<ActionData>();
|
||||
const emailMarketingPreviewFetcher = useFetcher<ActionData>();
|
||||
const submit = useSubmit();
|
||||
const navigate = useNavigate();
|
||||
const revalidator = useRevalidator();
|
||||
const { csrf, appConfiguration } = useRootData();
|
||||
const appData = useAppData();
|
||||
const activationMode =
|
||||
appData.subscriptionActivationRequired ?? requiresTenantSubscriptionActivation(appConfiguration.subscription.required, appData.mySubscription);
|
||||
const planAdviceResolver = useRef<{
|
||||
resolve: (result: SelfServiceSubscriptionPlanAdvice) => void;
|
||||
reject: (error: Error) => void;
|
||||
} | null>(null);
|
||||
const previewResolver = useRef<{
|
||||
resolve: (result: { preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }) => void;
|
||||
reject: (error: Error) => void;
|
||||
} | null>(null);
|
||||
const emailMarketingPreviewResolver = useRef<{
|
||||
resolve: (result: { addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number]; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }) => void;
|
||||
reject: (error: Error) => void;
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) toast.error(actionData.error);
|
||||
else if (actionData?.success) toast.success(actionData.success);
|
||||
}, [actionData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (planAdviceFetcher.state !== "idle" || !planAdviceResolver.current) return;
|
||||
const resolver = planAdviceResolver.current;
|
||||
planAdviceResolver.current = null;
|
||||
if (planAdviceFetcher.data?.planAdvice) resolver.resolve(planAdviceFetcher.data.planAdvice);
|
||||
else resolver.reject(new Error(planAdviceFetcher.data?.error ?? "Plan advice unavailable"));
|
||||
}, [planAdviceFetcher.data, planAdviceFetcher.state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (previewFetcher.state !== "idle" || !previewResolver.current) return;
|
||||
const resolver = previewResolver.current;
|
||||
previewResolver.current = null;
|
||||
if (previewFetcher.data?.preview && previewFetcher.data.paymentMethods) {
|
||||
resolver.resolve({ preview: previewFetcher.data.preview, paymentMethods: previewFetcher.data.paymentMethods });
|
||||
} else resolver.reject(new Error(previewFetcher.data?.error ?? "Preview unavailable"));
|
||||
}, [previewFetcher.data, previewFetcher.state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (emailMarketingPreviewFetcher.state !== "idle" || !emailMarketingPreviewResolver.current) return;
|
||||
const resolver = emailMarketingPreviewResolver.current;
|
||||
emailMarketingPreviewResolver.current = null;
|
||||
if (emailMarketingPreviewFetcher.data?.emailMarketingPreview) {
|
||||
resolver.resolve(emailMarketingPreviewFetcher.data.emailMarketingPreview);
|
||||
} else {
|
||||
resolver.reject(new Error(emailMarketingPreviewFetcher.data?.error ?? "Email marketing preview unavailable"));
|
||||
}
|
||||
}, [emailMarketingPreviewFetcher.data, emailMarketingPreviewFetcher.state]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
planAdviceResolver.current?.reject(new Error("Plan advice cancelled"));
|
||||
planAdviceResolver.current = null;
|
||||
previewResolver.current?.reject(new Error("Preview cancelled"));
|
||||
previewResolver.current = null;
|
||||
emailMarketingPreviewResolver.current?.reject(new Error("Email marketing preview cancelled"));
|
||||
emailMarketingPreviewResolver.current = null;
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<SelfServiceSubscriptionPage
|
||||
embedded
|
||||
activationMode={activationMode}
|
||||
initialPlanAdvice={initialPlanAdvice}
|
||||
initialEmailMarketingAddOnCode={initialEmailMarketingAddOnCode}
|
||||
vm={vm}
|
||||
actions={{
|
||||
onPlanAdvice(seatQuantities) {
|
||||
planAdviceResolver.current?.reject(new Error("Plan advice superseded"));
|
||||
return new Promise<SelfServiceSubscriptionPlanAdvice>((resolve, reject) => {
|
||||
planAdviceResolver.current = { resolve, reject };
|
||||
const form = new FormData();
|
||||
form.set("intent", "plan-advice");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("office-seat-quantity", String(seatQuantities.officeSeatQuantity));
|
||||
form.set("field-seat-quantity", String(seatQuantities.fieldSeatQuantity));
|
||||
void planAdviceFetcher.submit(form, { method: "post" });
|
||||
});
|
||||
},
|
||||
onRetry() {
|
||||
revalidator.revalidate();
|
||||
},
|
||||
onOpenBilling() {
|
||||
void navigate(vm.billingHref);
|
||||
},
|
||||
onOpenCustomerPortal: getUserHasPermission(appData, "portal.admin")
|
||||
? () => {
|
||||
void navigate(customerPortalSettingsPath(appData.currentTenant.slug));
|
||||
}
|
||||
: undefined,
|
||||
onPreview(selection) {
|
||||
previewResolver.current?.reject(new Error("Preview superseded"));
|
||||
return new Promise<{ preview: SelfServiceSubscriptionPricePreviewVM; paymentMethods: SelfServiceCheckoutPaymentMethodsVM }>((resolve, reject) => {
|
||||
previewResolver.current = { resolve, reject };
|
||||
void previewFetcher.submit(selectionForm("preview", selection, csrf ?? ""), { method: "post" });
|
||||
});
|
||||
},
|
||||
onCheckout(selection, paymentMethod, checkoutRequestKey) {
|
||||
const form = selectionForm("checkout", selection, csrf ?? "");
|
||||
if (paymentMethod) form.set("payment-method", paymentMethod);
|
||||
form.set("checkout-request-key", checkoutRequestKey);
|
||||
return submit(form, { method: "post" });
|
||||
},
|
||||
onCancel(productId) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "cancel");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("tenant-subscription-product-id", productId);
|
||||
return submit(form, { method: "post" });
|
||||
},
|
||||
onEmailMarketingPreview(addOn) {
|
||||
emailMarketingPreviewResolver.current?.reject(new Error("Email marketing preview superseded"));
|
||||
return new Promise<{
|
||||
addOn: SelfServiceSubscriptionPageVM["emailMarketingAddOns"][number];
|
||||
paymentMethods: SelfServiceCheckoutPaymentMethodsVM;
|
||||
}>((resolve, reject) => {
|
||||
emailMarketingPreviewResolver.current = { resolve, reject };
|
||||
const form = new FormData();
|
||||
form.set("intent", "email-marketing-preview");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("product-id", addOn.productId);
|
||||
form.set("price-id", addOn.priceId);
|
||||
void emailMarketingPreviewFetcher.submit(form, { method: "post" });
|
||||
});
|
||||
},
|
||||
onEmailMarketingCheckout(addOn, paymentMethod) {
|
||||
const form = new FormData();
|
||||
form.set("intent", "email-marketing-checkout");
|
||||
form.set("csrf", csrf ?? "");
|
||||
form.set("product-id", addOn.productId);
|
||||
form.set("price-id", addOn.priceId);
|
||||
if (paymentMethod) form.set("payment-method", paymentMethod);
|
||||
return submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getTranslations: vi.fn(),
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
tenantHasModule: vi.fn(),
|
||||
getTenant: vi.fn(),
|
||||
getTenantSubscription: vi.fn(),
|
||||
listCustomerBillingInvoices: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/billing/BillingPaymentPage", () => ({ BillingPaymentPage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenant: (...args: unknown[]) => mocks.getTenant(...args) }));
|
||||
vi.mock("~/utils/db/tenantSubscriptions.db.server", () => ({ getTenantSubscription: (...args: unknown[]) => mocks.getTenantSubscription(...args) }));
|
||||
vi.mock("~/services/billing/customer-invoices.server", () => ({
|
||||
CustomerBillingInvoiceError: class CustomerBillingInvoiceError extends Error {
|
||||
readonly i18nKey = "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE";
|
||||
},
|
||||
listCustomerBillingInvoices: (...args: unknown[]) => mocks.listCustomerBillingInvoices(...args),
|
||||
}));
|
||||
|
||||
import { loader } from "./invoices";
|
||||
|
||||
async function callLoader() {
|
||||
return loader({
|
||||
request: new Request("https://app.example.test/acme/settings/billing"),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/billing",
|
||||
} as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant billing payment route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1");
|
||||
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
mocks.tenantHasModule.mockResolvedValue(true);
|
||||
mocks.getTenant.mockResolvedValue({ id: "tenant_1", slug: "acme" });
|
||||
mocks.getTenantSubscription.mockResolvedValue({ lastPaymentExternalId: "tr_123" });
|
||||
mocks.listCustomerBillingInvoices.mockResolvedValue([
|
||||
{
|
||||
id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
issuingDate: "2026-07-10",
|
||||
amountCents: 4_900,
|
||||
currency: "EUR",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("requires invoice permission and builds Lago/Mollie payment state", async () => {
|
||||
const data = await callLoader();
|
||||
expect(mocks.verifyUserHasPermission).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.invoices.view", "tenant_1");
|
||||
expect(mocks.verifyUserHasPermission).not.toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.view", expect.any(String));
|
||||
expect(mocks.listCustomerBillingInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", tenantSlug: "acme" });
|
||||
expect(data.vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: { latestPaymentStatus: "succeeded", hasMollieReference: true },
|
||||
});
|
||||
expect(data.vm.status === "ready" ? data.vm.data.invoices[0]?.downloadHref : null).toBe("/acme/settings/subscription/invoices/invoice_1/download");
|
||||
});
|
||||
|
||||
it("returns a localized VM error when Lago cannot list invoices", async () => {
|
||||
mocks.listCustomerBillingInvoices.mockRejectedValueOnce(new Error("upstream unavailable"));
|
||||
const data = await callLoader();
|
||||
expect(data.vm).toEqual({
|
||||
status: "error",
|
||||
error: { messageKey: "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE", code: "INVOICE_LIST_UNAVAILABLE" },
|
||||
});
|
||||
});
|
||||
});
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData, useRevalidator } from "react-router";
|
||||
import { buildBillingPaymentVM, type BillingPaymentVM } from "@hivegrid/view-models";
|
||||
import { BillingPaymentPage } from "~/components/screens/billing/BillingPaymentPage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { CustomerBillingInvoiceError, listCustomerBillingInvoices } from "~/services/billing/customer-invoices.server";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { BILLING_MODULE_KEY } from "~/utils/services/.server/billingStatusService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
type LoaderData = { title: string; vm: BillingPaymentVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
|
||||
if (!hasBillingModule) throw redirect(appTenantPlanRequiredPath(params));
|
||||
const [{ t }, tenant, subscription] = await Promise.all([getTranslations(request), getTenant(tenantId), getTenantSubscription(tenantId)]);
|
||||
if (!tenant) throw new Response(t("settings.subscription.errors.invalidTenant", { tenantId }), { status: 404 });
|
||||
|
||||
const invoiceResult = await listCustomerBillingInvoices({ tenantId, tenantSlug: tenant.slug })
|
||||
.then((invoices) => ({ invoices, errorKey: null }))
|
||||
.catch((error) => ({
|
||||
invoices: [],
|
||||
errorKey: error instanceof CustomerBillingInvoiceError ? error.i18nKey : "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE",
|
||||
}));
|
||||
const vm = buildBillingPaymentVM({
|
||||
invoices: invoiceResult.invoices,
|
||||
lastPaymentExternalId: subscription?.lastPaymentExternalId,
|
||||
errorKey: invoiceResult.errorKey,
|
||||
});
|
||||
return { title: `${t("billing:billingPayment.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData;
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export default function BillingPaymentRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const revalidator = useRevalidator();
|
||||
return (
|
||||
<BillingPaymentPage
|
||||
vm={vm}
|
||||
embedded
|
||||
actions={{
|
||||
onDownloadInvoice: (href) => window.open(href, "_blank", "noopener,noreferrer"),
|
||||
onRetry: () => revalidator.revalidate(),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getTranslations: vi.fn(),
|
||||
getTenantIdFromUrl: vi.fn(),
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
tenantHasModule: vi.fn(),
|
||||
getBillingUsageSummary: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/screens/billing/BillingUsagePage", () => ({ BillingUsagePage: () => null }));
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: (...args: unknown[]) => mocks.verifyUserHasPermission(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
|
||||
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
|
||||
vi.mock("~/utils/services/.server/billingStatusService", () => ({
|
||||
BILLING_MODULE_KEY: "billing",
|
||||
getBillingUsageSummary: (...args: unknown[]) => mocks.getBillingUsageSummary(...args),
|
||||
}));
|
||||
|
||||
import { loader } from "./usage";
|
||||
|
||||
function callLoader() {
|
||||
return loader({
|
||||
request: new Request("https://app.example.test/acme/settings/billing/usage"),
|
||||
params: { tenant: "acme" },
|
||||
context: {},
|
||||
unstable_pattern: "app.$tenant/settings/billing/usage",
|
||||
} as LoaderFunctionArgs);
|
||||
}
|
||||
|
||||
describe("tenant billing usage route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
|
||||
mocks.getTenantIdFromUrl.mockResolvedValue("tenant_1");
|
||||
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
mocks.tenantHasModule.mockResolvedValue(true);
|
||||
mocks.getBillingUsageSummary.mockResolvedValue({
|
||||
periodStart: new Date("2026-08-01T00:00:00.000Z"),
|
||||
periodEnd: new Date("2026-09-01T00:00:00.000Z"),
|
||||
storageUnavailableReason: null,
|
||||
metrics: [
|
||||
{
|
||||
metricCode: "storage_bytes",
|
||||
quantity: 75,
|
||||
quota: 350 * 1024 ** 3,
|
||||
remaining: 350 * 1024 ** 3 - 75,
|
||||
exceeded: false,
|
||||
percentUsed: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("renders the canonical storage allowance from the RLS-bound usage projection", async () => {
|
||||
const data = await callLoader();
|
||||
|
||||
expect(mocks.verifyUserHasPermission).toHaveBeenCalledWith(expect.any(Request), "app.settings.subscription.view", "tenant_1");
|
||||
expect(data.vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: { metrics: [expect.objectContaining({ metricCode: "storage_bytes", quantity: 75, quota: 350 * 1024 ** 3 })] },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps healthy counters visible without claiming unlimited storage when capacity is unavailable", async () => {
|
||||
mocks.getBillingUsageSummary.mockResolvedValueOnce({
|
||||
periodStart: new Date("2026-08-01T00:00:00.000Z"),
|
||||
periodEnd: new Date("2026-09-01T00:00:00.000Z"),
|
||||
storageUnavailableReason: "plan_unknown",
|
||||
metrics: [
|
||||
{
|
||||
metricCode: "automation_runs",
|
||||
quantity: 12,
|
||||
quota: 100,
|
||||
remaining: 88,
|
||||
exceeded: false,
|
||||
percentUsed: 12,
|
||||
},
|
||||
{
|
||||
metricCode: "storage_bytes",
|
||||
quantity: 0,
|
||||
quota: null,
|
||||
remaining: null,
|
||||
exceeded: false,
|
||||
percentUsed: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const data = await callLoader();
|
||||
|
||||
expect(data.vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: {
|
||||
unavailableMetrics: ["storage_bytes"],
|
||||
metrics: [expect.objectContaining({ metricCode: "automation_runs", quantity: 12 })],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { LoaderFunctionArgs, redirect, useLoaderData, useRevalidator } from "react-router";
|
||||
import { buildBillingUsageVM, type BillingUsageVM } from "@hivegrid/view-models";
|
||||
import { BillingUsagePage } from "~/components/screens/billing/BillingUsagePage";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { BILLING_MODULE_KEY, getBillingUsageSummary } from "~/utils/services/.server/billingStatusService";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
|
||||
type LoaderData = { title: string; vm: BillingUsageVM };
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.view", tenantId);
|
||||
const userInfo = await getUserInfo(request);
|
||||
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
|
||||
if (!hasBillingModule) throw redirect(appTenantPlanRequiredPath(params));
|
||||
const [{ t }, summary] = await Promise.all([getTranslations(request), getBillingUsageSummary(tenantId)]);
|
||||
const vm: BillingUsageVM = buildBillingUsageVM({
|
||||
periodStart: summary.periodStart.toISOString(),
|
||||
periodEnd: summary.periodEnd.toISOString(),
|
||||
metrics: summary.metrics,
|
||||
unavailableMetricCodes: summary.storageUnavailableReason ? ["storage_bytes"] : [],
|
||||
});
|
||||
return { title: `${t("billing:usage.title")} | ${process.env.APP_NAME}`, vm } satisfies LoaderData;
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<typeof loader> = ({ data }) => (data && "title" in data ? [{ title: data.title }] : []);
|
||||
|
||||
export default function BillingUsageRoute() {
|
||||
const { vm } = useLoaderData<LoaderData>();
|
||||
const revalidator = useRevalidator();
|
||||
return <BillingUsagePage vm={vm} embedded actions={{ onRetry: () => revalidator.revalidate() }} />;
|
||||
}
|
||||
Reference in new issue
Block a user