Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+114
-61
@@ -1,20 +1,9 @@
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunction, LoaderFunctionArgs, redirect, useLoaderData } from "react-router";
|
||||
import { useActionData } from "react-router";
|
||||
import {
|
||||
createCustomerPortalSession,
|
||||
createStripeSetupSession,
|
||||
deleteStripePaymentMethod,
|
||||
getStripeCustomer,
|
||||
getStripeInvoices,
|
||||
getStripePaymentIntents,
|
||||
getStripePaymentMethods,
|
||||
getStripeUpcomingInvoices,
|
||||
} from "~/utils/stripe.server";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import type Stripe from "stripe";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getOrPersistTenantSubscription, getTenantSubscription } from "~/utils/db/tenantSubscriptions.db.server";
|
||||
import { getTenant } from "~/utils/db/tenants.db.server";
|
||||
@@ -22,7 +11,6 @@ import { cancelTenantSubscription, getPlanFeaturesUsage } from "~/utils/services
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import SubscriptionSettings from "~/modules/users/components/SubscriptionSettings";
|
||||
@@ -30,17 +18,52 @@ import toast from "react-hot-toast";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
||||
import { BILLING_MODULE_KEY } from "~/utils/services/.server/billingStatusService";
|
||||
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { CustomerBillingInvoiceError, listCustomerBillingInvoices } from "~/services/billing/customer-invoices.server";
|
||||
import type { CustomerBillingInvoiceDto } from "~/application/dtos/billing/CustomerBillingInvoiceDto";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { getCurrenciesAndPeriods } from "~/utils/helpers/PricingHelper";
|
||||
import type { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createSelfServiceCheckout, SelfServiceCheckoutError } from "~/services/billing/self-service-checkout.server";
|
||||
export { serverTimingHeaders as headers };
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
customer: Stripe.Customer | Stripe.DeletedCustomer | null;
|
||||
myInvoices: Stripe.Invoice[];
|
||||
myPayments: Stripe.PaymentIntent[];
|
||||
myFeatures: PlanFeatureUsageDto[];
|
||||
myUpcomingInvoices: Stripe.Invoice[];
|
||||
myPaymentMethods: Stripe.PaymentMethod[];
|
||||
myInvoices: CustomerBillingInvoiceDto[];
|
||||
availablePlans: SubscriptionProductDto[];
|
||||
currenciesAndPeriod: ReturnType<typeof getCurrenciesAndPeriods>;
|
||||
canViewInvoices: boolean;
|
||||
canManageSubscription: boolean;
|
||||
invoiceErrorKey: string | null;
|
||||
};
|
||||
|
||||
async function canViewSubscriptionInvoices(request: Request, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && (error.status === 403 || error.status === 404)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function canManageSubscription(request: Request, tenantId: string): Promise<boolean> {
|
||||
try {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.update", tenantId);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof Response && (error.status === 403 || error.status === 404)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.settings.subscription");
|
||||
let { t } = await getTranslations(request);
|
||||
@@ -50,15 +73,12 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const userInfoPromise = time(getUserInfo(request), "getUserInfo");
|
||||
const userPromise = userInfoPromise.then((userInfo) => time(getUser(userInfo.userId), "getUser"));
|
||||
const tenantPromise = time(getTenant(tenantId), "getTenant");
|
||||
const canViewInvoicesPromise = time(
|
||||
verifyUserHasPermission(request, "app.settings.subscription.invoices.view", tenantId).then(
|
||||
() => true,
|
||||
() => false
|
||||
),
|
||||
"verifyInvoicePermission"
|
||||
);
|
||||
|
||||
const [user, tenant, canViewInvoices] = await Promise.all([userPromise, tenantPromise, canViewInvoicesPromise]);
|
||||
const [user, tenant] = await Promise.all([userPromise, tenantPromise]);
|
||||
const userInfo = await userInfoPromise;
|
||||
const hasBillingModule = await tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BILLING_MODULE_KEY });
|
||||
if (!hasBillingModule) {
|
||||
throw redirect(appTenantPlanRequiredPath(params));
|
||||
}
|
||||
if (!user) {
|
||||
return badRequest({ error: t("shared.invalidUser") });
|
||||
}
|
||||
@@ -67,29 +87,34 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
}
|
||||
|
||||
const tenantSubscription = await time(getOrPersistTenantSubscription(tenantId), "getOrPersistTenantSubscription");
|
||||
const { customer, myInvoices, myPayments, myUpcomingInvoices, myPaymentMethods, myFeatures } = await time(
|
||||
promiseHash({
|
||||
customer: canViewInvoices ? getStripeCustomer(tenantSubscription.stripeCustomerId) : Promise.resolve(null),
|
||||
myInvoices: canViewInvoices ? (getStripeInvoices(tenantSubscription.stripeCustomerId) ?? []) : Promise.resolve([] as Stripe.Invoice[]),
|
||||
myPayments: canViewInvoices
|
||||
? (getStripePaymentIntents(tenantSubscription.stripeCustomerId, "succeeded") ?? [])
|
||||
: Promise.resolve([] as Stripe.PaymentIntent[]),
|
||||
myUpcomingInvoices: canViewInvoices
|
||||
? getStripeUpcomingInvoices(tenantSubscription.products.filter((f) => f.stripeSubscriptionId).flatMap((p) => p.stripeSubscriptionId!))
|
||||
: Promise.resolve([] as Stripe.Invoice[]),
|
||||
myPaymentMethods: canViewInvoices ? getStripePaymentMethods(tenantSubscription.stripeCustomerId) : Promise.resolve([] as Stripe.PaymentMethod[]),
|
||||
myFeatures: getPlanFeaturesUsage(tenantId, tenantSubscription),
|
||||
}),
|
||||
"subscription[getStripeData]"
|
||||
);
|
||||
const [canViewInvoices, canUpdateSubscription, availablePlans] = await Promise.all([
|
||||
time(canViewSubscriptionInvoices(request, tenantId), "verifyInvoicePermission"),
|
||||
time(canManageSubscription(request, tenantId), "verifySubscriptionUpdatePermission"),
|
||||
time(getAllSubscriptionProducts(true), "subscription[getPublicProducts]"),
|
||||
]);
|
||||
const [myFeatures, invoiceResult] = await Promise.all([
|
||||
time(getPlanFeaturesUsage(tenantId, tenantSubscription), "subscription[getPlanFeaturesUsage]"),
|
||||
canViewInvoices
|
||||
? time(
|
||||
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",
|
||||
})),
|
||||
"billing[listCustomerInvoices]"
|
||||
)
|
||||
: Promise.resolve({ invoices: [], errorKey: null }),
|
||||
]);
|
||||
const data: LoaderData = {
|
||||
title: `${t("app.navbar.subscription")} | ${process.env.APP_NAME}`,
|
||||
customer,
|
||||
myFeatures,
|
||||
myInvoices,
|
||||
myPayments,
|
||||
myUpcomingInvoices,
|
||||
myPaymentMethods,
|
||||
myInvoices: invoiceResult.invoices,
|
||||
availablePlans: availablePlans as SubscriptionProductDto[],
|
||||
currenciesAndPeriod: getCurrenciesAndPeriods(availablePlans.flatMap((plan) => plan.prices)),
|
||||
canViewInvoices,
|
||||
canManageSubscription: canUpdateSubscription,
|
||||
invoiceErrorKey: invoiceResult.errorKey,
|
||||
};
|
||||
return Response.json(data, { headers: getServerTimingHeader() });
|
||||
};
|
||||
@@ -110,9 +135,9 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
|
||||
const action = form.get("action")?.toString();
|
||||
|
||||
if (!tenantSubscription || !tenantSubscription?.stripeCustomerId) {
|
||||
if (!tenantSubscription) {
|
||||
return badRequest({
|
||||
error: t("settings.subscription.errors.invalidStripeCustomer"),
|
||||
error: t("settings.subscription.errors.invalidSubscription"),
|
||||
});
|
||||
} else if (action === "cancel") {
|
||||
await verifyUserHasPermission(request, "app.settings.subscription.delete", tenantId);
|
||||
@@ -125,18 +150,46 @@ export const action: ActionFunction = async ({ request, params }) => {
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 400 });
|
||||
}
|
||||
} else if (action === "add-payment-method") {
|
||||
const session = await createStripeSetupSession(request, tenantSubscription.stripeCustomerId);
|
||||
return redirect(session?.url ?? "");
|
||||
} else if (action === "delete-payment-method") {
|
||||
await deleteStripePaymentMethod(form.get("id")?.toString() ?? "", tenantSubscription.stripeCustomerId);
|
||||
return Response.json({});
|
||||
} else if (action === "open-customer-portal") {
|
||||
const session = await createCustomerPortalSession(request, tenantSubscription.stripeCustomerId);
|
||||
if (!session?.url) {
|
||||
return badRequest({ error: t("settings.subscription.errors.customerPortalUnavailable") });
|
||||
} else if (action === "subscribe") {
|
||||
const tenant = await getTenant(tenantId);
|
||||
const user = await getUser(userInfo.userId);
|
||||
if (!tenant) {
|
||||
return badRequest({ error: t("settings.subscription.errors.invalidTenant", { tenantId }) });
|
||||
}
|
||||
if (!user) {
|
||||
return badRequest({ error: t("shared.invalidUser") });
|
||||
}
|
||||
const tenantSlugContext = form.get("tenant-slug-context")?.toString();
|
||||
if (tenantSlugContext && tenantSlugContext !== tenant.slug) {
|
||||
return badRequest({ error: t("settings.subscription.checkout.invalid") });
|
||||
}
|
||||
|
||||
try {
|
||||
const checkout = await createSelfServiceCheckout({
|
||||
request,
|
||||
tenantId,
|
||||
tenantSlug: tenant.slug,
|
||||
tenantName: tenant.name,
|
||||
userId: user.id,
|
||||
userEmail: user.email,
|
||||
userName: `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim() || user.email,
|
||||
productId: form.get("product-id")?.toString() ?? "",
|
||||
billingPeriod: Number(form.get("billing-period")?.toString()),
|
||||
currency: form.get("currency")?.toString() ?? "",
|
||||
quantity: Number(form.get("quantity")?.toString() ?? "1"),
|
||||
});
|
||||
return redirect(checkout.checkoutUrl);
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof SelfServiceCheckoutError) {
|
||||
return Response.json({ error: t(error.i18nKey) }, { status: 400 });
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
return Response.json({ error: t("shared.unexpectedError") }, { status: 400 });
|
||||
}
|
||||
return redirect(session.url);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -160,9 +213,9 @@ export default function SubscriptionRoute() {
|
||||
<SubscriptionSettings
|
||||
{...data}
|
||||
mySubscription={appData.mySubscription}
|
||||
currentTenant={appData.currentTenant}
|
||||
permissions={{
|
||||
viewInvoices: getUserHasPermission(appData, "app.settings.subscription.invoices.view") && data.myInvoices.length > 0,
|
||||
viewInvoices: data.canViewInvoices && getUserHasPermission(appData, "app.settings.subscription.invoices.view"),
|
||||
manageSubscription: data.canManageSubscription && getUserHasPermission(appData, "app.settings.subscription.update"),
|
||||
}}
|
||||
/>
|
||||
</EditPageLayout>
|
||||
|
||||
Reference in new issue
Block a user