Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,515 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Fragment, useEffect, useRef, useState } from "react";
|
||||
import plans from "~/application/pricing/plans.server";
|
||||
import { ActionFunction, Link, LoaderFunctionArgs, MetaFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { Form, Outlet, useSubmit, useNavigation } from "react-router";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import {
|
||||
getAllSubscriptionProducts,
|
||||
getAllSubscriptionProductsWithTenants,
|
||||
getSubscriptionProduct,
|
||||
updateSubscriptionProduct,
|
||||
} from "@toolctrl/db/subscriptions.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { createPlans, deletePlan, syncPlan } from "~/utils/services/.server/pricingService";
|
||||
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { createAdminLog } from "~/utils/db/logs.db.server";
|
||||
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
|
||||
import { SubscriptionFeatureDto } from "~/application/dtos/subscriptions/SubscriptionFeatureDto";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useAdminData } from "~/utils/data/useAdminData";
|
||||
import InputSelect from "~/components/ui/input/InputSelect";
|
||||
import WarningBanner from "~/components/ui/banners/WarningBanner";
|
||||
import { isStripeTestMode } from "~/utils/stripe.server";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
|
||||
import toast from "react-hot-toast";
|
||||
import { getPossibleBillingPeriods } from "~/utils/helpers/PricingHelper";
|
||||
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
|
||||
import clsx from "clsx";
|
||||
import TrashIcon from "~/components/ui/icons/TrashIcon";
|
||||
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
|
||||
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
||||
import BackButtonWithTitle from "~/components/ui/buttons/BackButtonWithTitle";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
export const meta: MetaFunction<typeof loader> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
isStripeTest: boolean;
|
||||
items: SubscriptionProductDto[];
|
||||
};
|
||||
|
||||
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("admin.pricing.title")} | ${process.env.APP_NAME}`,
|
||||
isStripeTest: isStripeTestMode(),
|
||||
items: await getAllSubscriptionProductsWithTenants(),
|
||||
};
|
||||
|
||||
if (data.items.length === 0) {
|
||||
data.items = plans;
|
||||
}
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export type PricingPlansActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
items?: Awaited<ReturnType<typeof getAllSubscriptionProducts>>;
|
||||
};
|
||||
const badRequest = (data: PricingPlansActionData) => Response.json(data, { status: 400 });
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.pricing.update");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "create-all-plans") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.create");
|
||||
const model = Number(form.get("model")) as PricingModel;
|
||||
const items = await getAllSubscriptionProducts();
|
||||
if (items.length > 0) {
|
||||
return Response.json({
|
||||
items,
|
||||
});
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
plans
|
||||
.filter((f) => f.model === model || model === PricingModel.ALL)
|
||||
.map(async (plan) => {
|
||||
plan.translatedTitle = t(plan.title);
|
||||
plan.usageBasedPrices?.forEach((usageBasedPrice) => {
|
||||
usageBasedPrice.unitTitle = t(usageBasedPrice.unitTitle);
|
||||
usageBasedPrice.unitTitlePlural = t(usageBasedPrice.unitTitlePlural);
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
try {
|
||||
await createPlans(plans.filter((f) => f.model === model || model === PricingModel.ALL));
|
||||
await createAdminLog(request, "admin.pricing.createdPlans", plans.map((f) => t(f.title)).join(", "));
|
||||
|
||||
return Response.json({
|
||||
items: await getAllSubscriptionProducts(),
|
||||
});
|
||||
} catch (e: any) {
|
||||
return badRequest({ error: e?.toString() });
|
||||
}
|
||||
} else if (action === "sync-plan-with-payment-provider") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await getSubscriptionProduct(id);
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
try {
|
||||
item.translatedTitle = t(item.title);
|
||||
await syncPlan(
|
||||
item,
|
||||
item.prices.map((price) => {
|
||||
return {
|
||||
id: price.id,
|
||||
billingPeriod: price.billingPeriod,
|
||||
currency: price.currency,
|
||||
price: Number(price.price),
|
||||
};
|
||||
})
|
||||
);
|
||||
return Response.json({
|
||||
items: await getAllSubscriptionProducts(),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else if (action === "toggle") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const item = await getSubscriptionProduct(id);
|
||||
if (!item) {
|
||||
return badRequest({ error: t("admin.pricing.errors.planNotFound") });
|
||||
}
|
||||
try {
|
||||
await updateSubscriptionProduct(id, {
|
||||
public: !item.public,
|
||||
});
|
||||
return Response.json({
|
||||
success: t("admin.pricing.actions.visibilityChanged", {
|
||||
status: t(!item.public ? "admin.pricing.status.public" : "admin.pricing.status.private"),
|
||||
}),
|
||||
});
|
||||
} catch (error: any) {
|
||||
return badRequest({ error: error.message });
|
||||
}
|
||||
} else if (action === "bulk-delete") {
|
||||
await verifyUserHasPermission(request, "admin.pricing.delete");
|
||||
const ids = form.getAll("ids[]");
|
||||
const items = await getAllSubscriptionProducts();
|
||||
const itemsToDelete = items.filter((f) => ids.includes(f.id?.toString() ?? ""));
|
||||
await Promise.all(
|
||||
itemsToDelete.map(async (item) => {
|
||||
if (item.tenantProducts && item.tenantProducts.length > 0) {
|
||||
throw new Error(t("admin.pricing.errors.activeSubscriptions", { plans: t(item.title) }));
|
||||
}
|
||||
await createAdminLog(request, "admin.pricing.deletedPlan", item.id!);
|
||||
})
|
||||
);
|
||||
await Promise.all(
|
||||
itemsToDelete.map(async (item) => {
|
||||
await deletePlan(item);
|
||||
})
|
||||
);
|
||||
return Response.json({ success: t("shared.deleted") });
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminPricingRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<PricingPlansActionData>();
|
||||
const adminData = useAdminData();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const loading = navigation.state === "submitting";
|
||||
|
||||
const [selectedItems, setSelectedItems] = useState<SubscriptionProductDto[]>([]);
|
||||
|
||||
const [model, setModel] = useState<PricingModel>(PricingModel.FLAT_RATE);
|
||||
const [items, setItems] = useState<SubscriptionProductDto[]>([]);
|
||||
const [, setAllFeatures] = useState<SubscriptionFeatureDto[]>([]);
|
||||
useEffect(() => {
|
||||
updateItems(data.items);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data.items, model]);
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
}
|
||||
updateItems(actionData?.items ?? data.items);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [actionData]);
|
||||
|
||||
function updateItems(items: SubscriptionProductDto[]) {
|
||||
if (items.filter((f) => f.id).length > 0) {
|
||||
setItems(items);
|
||||
} else {
|
||||
setItems(items.filter((f) => f.model === model || model === PricingModel.ALL));
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const allFeatures: SubscriptionFeatureDto[] = [];
|
||||
items.forEach((item) => {
|
||||
item.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,
|
||||
accumulate: feature.accumulate,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
setAllFeatures(allFeatures.sort((a, b) => a.order - b.order));
|
||||
}, [items]);
|
||||
|
||||
// const sortedItems = () => {
|
||||
// return items.sort((x, y) => {
|
||||
// return x?.order > y?.order ? 1 : -1;
|
||||
// });
|
||||
// };
|
||||
|
||||
function createAllPlans() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "create-all-plans");
|
||||
form.set("model", model.toString());
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
// function syncPlanWithPaymentProvider(item: SubscriptionProductDto) {
|
||||
// const form = new FormData();
|
||||
// form.set("action", "sync-plan-with-payment-provider");
|
||||
// form.set("id", item.id?.toString() ?? "");
|
||||
// submit(form, {
|
||||
// method: "post",
|
||||
// });
|
||||
// }
|
||||
// function createPlan(item: SubscriptionProductDto) {
|
||||
// const form = new FormData();
|
||||
// form.set("action", "create");
|
||||
// form.set("order", item.order);
|
||||
// form.set("order", item.description);
|
||||
// employees.forEach((item) => {
|
||||
// form.append("employees[]", JSON.stringify(item));
|
||||
// });
|
||||
// submit(form, {
|
||||
// method: "post",
|
||||
// });
|
||||
// }
|
||||
|
||||
function createdPlans() {
|
||||
return data.items.filter((f) => f.id).length;
|
||||
}
|
||||
|
||||
// function getFeatureValue(item: SubscriptionProductDto, name: string) {
|
||||
// return item.features.find((f) => f.name === name);
|
||||
// }
|
||||
|
||||
function onToggle(item: SubscriptionProductDto) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "toggle");
|
||||
form.set("id", item.id?.toString() ?? "");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<EditPageLayout
|
||||
title={<BackButtonWithTitle href={adminPath("settings", { mode: "host-aware" })}>{t("admin.pricing.title")}</BackButtonWithTitle>}
|
||||
buttons={
|
||||
<>
|
||||
<Form method="post" className="flex h-9 items-center space-x-2">
|
||||
{selectedItems.length > 0 && (
|
||||
<DeleteIconButton
|
||||
items={selectedItems}
|
||||
onClick={() => {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "bulk-delete");
|
||||
selectedItems.forEach((item) => {
|
||||
form.append("ids[]", item.id?.toString() ?? "");
|
||||
});
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<ButtonSecondary
|
||||
disabled={data.items.length === 0}
|
||||
to={adminPath("settings/pricing/features?" + selectedItems.map((f) => "id=" + f.id).join("&"), { mode: "host-aware" })}
|
||||
>
|
||||
{selectedItems.length === 0 ? (
|
||||
<span>{t("admin.pricing.features.actions.setFeatures")}</span>
|
||||
) : (
|
||||
<span>{t("admin.pricing.features.actions.setFeaturesForSelection", { count: selectedItems.length })}</span>
|
||||
)}
|
||||
</ButtonSecondary>
|
||||
{selectedItems.length === 0 && (
|
||||
<Fragment>
|
||||
{/* <ButtonSecondary disabled={loading} to=".">
|
||||
{t("shared.reload")}
|
||||
</ButtonSecondary> */}
|
||||
|
||||
<ButtonPrimary to="new" disabled={loading || !getUserHasPermission(adminData, "admin.pricing.create")}>
|
||||
{t("shared.new")}
|
||||
</ButtonPrimary>
|
||||
</Fragment>
|
||||
)}
|
||||
</Form>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-6">
|
||||
{createdPlans() === 0 && (
|
||||
<WarningBanner title={t("shared.warning")} text={t("admin.pricing.thesePricesAreFromFiles")}>
|
||||
<div className="mt-2 flex items-center space-x-2">
|
||||
<div className="w-44">
|
||||
<InputSelect
|
||||
name="model"
|
||||
title={t("models.subscriptionProduct.model")}
|
||||
withLabel={false}
|
||||
value={model}
|
||||
setValue={(e) => {
|
||||
setModel(Number(e));
|
||||
}}
|
||||
options={[
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE]),
|
||||
value: PricingModel.FLAT_RATE,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.PER_SEAT]),
|
||||
value: PricingModel.PER_SEAT,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.USAGE_BASED]),
|
||||
value: PricingModel.USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.FLAT_RATE_USAGE_BASED]),
|
||||
value: PricingModel.FLAT_RATE_USAGE_BASED,
|
||||
},
|
||||
{
|
||||
name: t("pricing." + PricingModel[PricingModel.ONCE]),
|
||||
value: PricingModel.ONCE,
|
||||
},
|
||||
{
|
||||
name: t("shared.all"),
|
||||
value: PricingModel.ALL,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<ButtonSecondary
|
||||
type="button"
|
||||
onClick={createAllPlans}
|
||||
disabled={loading || createdPlans() > 0 || !getUserHasPermission(adminData, "admin.pricing.create")}
|
||||
className="bg-yellow-500 text-yellow-900 hover:bg-yellow-400"
|
||||
>
|
||||
{t("admin.pricing.generateFromFiles")}
|
||||
</ButtonSecondary>
|
||||
</div>
|
||||
</WarningBanner>
|
||||
)}
|
||||
|
||||
<TableSimple
|
||||
selectedRows={selectedItems}
|
||||
onSelected={(items) => setSelectedItems(items)}
|
||||
items={items}
|
||||
headers={[
|
||||
{
|
||||
name: "level",
|
||||
title: t("models.subscriptionProduct.level"),
|
||||
value: (i) => <div className="text-muted-foreground text-xs">{i.order}</div>,
|
||||
},
|
||||
{
|
||||
name: "title",
|
||||
title: t("models.subscriptionProduct.title"),
|
||||
value: (item) => (
|
||||
<div className="group flex items-center gap-1">
|
||||
<Link to={"edit/" + item.id} className="group-hover:underline">
|
||||
{t(item.title)}
|
||||
</Link>
|
||||
{item.badge && <div className="border-border bg-theme-50 text-theme-800 ml-1 rounded-md border px-1 py-0.5 text-xs">{t(item.badge)}</div>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "model",
|
||||
title: t("models.subscriptionProduct.model"),
|
||||
value: (item) => (
|
||||
<div className="flex flex-col">
|
||||
<div>{t("pricing." + PricingModel[item.model])} </div>
|
||||
{item.model !== PricingModel.ONCE && (
|
||||
<div className="text-muted-foreground text-xs">
|
||||
{getPossibleBillingPeriods(item.prices)
|
||||
.map((billingPeriod) => t("pricing." + SubscriptionBillingPeriod[billingPeriod]).toLowerCase())
|
||||
.join(", ")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
// ...allFeatures.map((feature) => {
|
||||
// return {
|
||||
// name: feature.name,
|
||||
// title: feature.name,
|
||||
// value: (item: SubscriptionProductDto) => <PlanFeatureValue item={getFeatureValue(item, feature.name)} />,
|
||||
// };
|
||||
// }),
|
||||
{
|
||||
name: "subscriptions",
|
||||
title: t("models.subscriptionProduct.plural"),
|
||||
value: (item) => (
|
||||
<div className="text-muted-foreground lowercase">
|
||||
{t("admin.pricing.subscriptionCount", {
|
||||
count: item.tenantProducts?.length ?? 0,
|
||||
formattedCount: formatters.number(item.tenantProducts?.length ?? 0),
|
||||
})}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "active",
|
||||
title: t("models.subscriptionProduct.status"),
|
||||
value: (item) => (
|
||||
<>
|
||||
{item.active ? (
|
||||
<>
|
||||
<button type="button" onClick={() => onToggle(item)} className="hover:underline">
|
||||
{item.public ? (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.public")} color={Colors.TEAL} underline />
|
||||
) : (
|
||||
<SimpleBadge title={t("models.subscriptionProduct.custom")} color={Colors.ORANGE} underline />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<SimpleBadge title={t("shared.inactive")} color={Colors.RED} />
|
||||
)}
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "actions",
|
||||
title: t("shared.actions"),
|
||||
value: (item) => (
|
||||
<div className="flex items-center space-x-2">
|
||||
<ButtonTertiary disabled={!item.id} to={"edit/" + item.id}>
|
||||
{t("shared.edit")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Outlet />
|
||||
</EditPageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteIconButton({ onClick, items }: { onClick: () => void; items: SubscriptionProductDto[] }) {
|
||||
const { t } = useTranslation();
|
||||
const navigation = useNavigation();
|
||||
const confirmModal = useRef<RefConfirmModal>(null);
|
||||
function onDeleting() {
|
||||
const hasWithSub = items.some((f) => (f.tenantProducts?.length ?? 0) > 0);
|
||||
if (hasWithSub) {
|
||||
toast.error(t("admin.pricing.errors.activeSubscriptions", { plans: items.map((f) => t(f.title ?? "")).join(", ") }));
|
||||
} else {
|
||||
confirmModal.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Fragment>
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
"hover:bg-secondary/90 focus:bg-secondary/90 group flex items-center rounded-md border border-transparent px-4 py-2 focus:ring-2 focus:ring-gray-400 focus:ring-offset-1 focus:outline-hidden",
|
||||
navigation.state === "submitting" && navigation.formData?.get("action") === "bulk-delete" && "base-spinner"
|
||||
)}
|
||||
disabled={navigation.state !== "idle"}
|
||||
onClick={onDeleting}
|
||||
>
|
||||
<TrashIcon className="group-hover:text-muted-foreground h-4 w-4 text-gray-300" />
|
||||
</button>
|
||||
<ConfirmModal ref={confirmModal} onYes={onClick} destructive />
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user