246 lines
9.4 KiB
TypeScript
246 lines
9.4 KiB
TypeScript
import { LoaderFunctionArgs, MetaFunction, useLoaderData } from "react-router";
|
|
import { Link, useNavigate, useOutlet } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
|
|
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
|
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
|
import TenantBadge from "~/components/core/tenants/TenantBadge";
|
|
import DateCell from "~/components/ui/dates/DateCell";
|
|
import InputFilters from "~/components/ui/input/InputFilters";
|
|
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
|
|
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
|
|
import TableSimple from "~/components/ui/tables/TableSimple";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
|
|
import {
|
|
getAllSubscriptionProducts,
|
|
getAllTenantSubscriptionProducts,
|
|
type TenantSubscriptionProductWithTenant,
|
|
} from "@hivegrid/db/subscriptions.server";
|
|
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
|
|
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
|
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
|
import { MISSING_NUMBER_PLACEHOLDER, toFiniteNumber, useLocaleFormatters } from "~/locale/format";
|
|
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
|
|
|
export const meta: MetaFunction<typeof loader> = ({ data }) => data?.metatags || [];
|
|
|
|
// Prisma `Decimal` columns do not reach the browser as numbers: the loader
|
|
// serialization keeps their structural shape, so a client-side `Number(price)`
|
|
// evaluates to `NaN` and the tier column renders "NaN €". Normalize the amount
|
|
// server-side, which is also where every other price surface converts it.
|
|
function toSerializableSubscriptionProduct(item: TenantSubscriptionProductWithTenant) {
|
|
return {
|
|
...item,
|
|
prices: item.prices.map((price) => ({
|
|
...price,
|
|
subscriptionPrice: price.subscriptionPrice ? { ...price.subscriptionPrice, price: Number(price.subscriptionPrice.price) } : null,
|
|
})),
|
|
};
|
|
}
|
|
|
|
type SubscriptionListItem = ReturnType<typeof toSerializableSubscriptionProduct>;
|
|
|
|
type LoaderData = {
|
|
metatags: MetaTagsDto;
|
|
items: SubscriptionListItem[];
|
|
pagination: PaginationDto;
|
|
filterableProperties: FilterablePropertyDto[];
|
|
};
|
|
export const loader = async ({ request }: LoaderFunctionArgs) => {
|
|
await verifyUserHasPermission(request, "admin.accounts.view");
|
|
let { t } = await getTranslations(request);
|
|
const [subscriptionProducts, tenantOptions] = await Promise.all([getAllSubscriptionProducts(), adminGetAllTenantsIdsAndNames()]);
|
|
|
|
const filterableProperties: FilterablePropertyDto[] = [
|
|
{
|
|
name: "status",
|
|
title: t("shared.status"),
|
|
manual: true,
|
|
options: [
|
|
{ value: "active", name: t("admin.accounts.subscriptions.filters.status.active") },
|
|
{ value: "ended", name: t("admin.accounts.subscriptions.filters.status.ended") },
|
|
{ value: "active-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeCancelled") },
|
|
{ value: "active-not-cancelled", name: t("admin.accounts.subscriptions.filters.status.activeNotCancelled") },
|
|
],
|
|
},
|
|
{
|
|
name: "subscriptionProductId",
|
|
title: t("models.subscriptionProduct.object"),
|
|
manual: true,
|
|
options: subscriptionProducts.map((f) => {
|
|
return {
|
|
value: f.id ?? "",
|
|
name: t(f.title),
|
|
};
|
|
}),
|
|
},
|
|
{
|
|
name: "tenantId",
|
|
title: t("models.tenant.object"),
|
|
manual: true,
|
|
options: tenantOptions.map((tenant) => {
|
|
return {
|
|
value: tenant.id,
|
|
name: tenant.name,
|
|
};
|
|
}),
|
|
},
|
|
];
|
|
const filters = getFiltersFromCurrentUrl(request, filterableProperties);
|
|
const urlSearchParams = new URL(request.url).searchParams;
|
|
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
|
const getFilterValue = (name: string) => filters.properties.find((property) => property.name === name)?.value?.toString();
|
|
const requestedTenantId = getFilterValue("tenantId");
|
|
const targetTenants = requestedTenantId ? tenantOptions.filter((tenant) => tenant.id === requestedTenantId) : tenantOptions;
|
|
const tenantPages = await Promise.all(
|
|
targetTenants.map((tenant) =>
|
|
runWithRlsContext({ tenantId: tenant.id }, () =>
|
|
getAllTenantSubscriptionProducts({
|
|
status: getFilterValue("status"),
|
|
subscriptionProductId: getFilterValue("subscriptionProductId"),
|
|
tenantId: tenant.id,
|
|
})
|
|
)
|
|
)
|
|
);
|
|
const allItems = tenantPages.flatMap((page) => page.items).sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
|
|
const offset = currentPagination.pageSize * (currentPagination.page - 1);
|
|
const items = allItems.slice(offset, offset + currentPagination.pageSize).map(toSerializableSubscriptionProduct);
|
|
const pagination: PaginationDto = {
|
|
...currentPagination,
|
|
totalItems: allItems.length,
|
|
totalPages: Math.ceil(allItems.length / currentPagination.pageSize),
|
|
};
|
|
|
|
const data: LoaderData = {
|
|
metatags: [{ title: `${t("models.subscription.plural")} | ${process.env.APP_NAME}` }],
|
|
items,
|
|
pagination,
|
|
filterableProperties,
|
|
};
|
|
return data;
|
|
};
|
|
|
|
export default function () {
|
|
const { t } = useTranslation();
|
|
const formatters = useLocaleFormatters();
|
|
const data = useLoaderData<LoaderData>();
|
|
const outlet = useOutlet();
|
|
const navigate = useNavigate();
|
|
const notAvailable = t("shared.notAvailable");
|
|
|
|
return (
|
|
<EditPageLayout
|
|
title={t("models.subscription.plural")}
|
|
buttons={
|
|
<>
|
|
<InputFilters filters={data.filterableProperties} withSearch={false} />
|
|
</>
|
|
}
|
|
>
|
|
<TableSimple
|
|
items={data.items}
|
|
pagination={data.pagination}
|
|
headers={[
|
|
{
|
|
name: "tenant",
|
|
title: t("models.tenant.object"),
|
|
value: (i) => <TenantBadge item={i.tenantSubscription.tenant} />,
|
|
},
|
|
{
|
|
name: "subscriptionProduct",
|
|
title: t("models.subscriptionProduct.object"),
|
|
value: () => "",
|
|
className: "w-full",
|
|
formattedValue: (product) => (
|
|
<span>
|
|
<div key={product.id}>
|
|
<div>
|
|
{t(product.subscriptionProduct.title)}{" "}
|
|
{product.prices
|
|
.map((f) => {
|
|
const amount = toFiniteNumber(f.subscriptionPrice?.price);
|
|
const amountLabel =
|
|
amount === null ? MISSING_NUMBER_PLACEHOLDER : formatters.currency(amount, f.subscriptionPrice?.currency || "USD");
|
|
return `${amountLabel} - ${SubscriptionUtils.getBillingPeriodDescription(t, f.subscriptionPrice?.billingPeriod ?? 0)}`;
|
|
})
|
|
.join(", ")}
|
|
</div>
|
|
</div>
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
name: "period",
|
|
title: t("models.subscription.period"),
|
|
value: (i) => (
|
|
<div>
|
|
{i.currentPeriodStart && i.currentPeriodEnd ? (
|
|
<div className="flex items-center space-x-1">
|
|
<DateCell date={i.currentPeriodStart} displays={["mdy"]} />
|
|
<div aria-hidden="true">-</div>
|
|
<DateCell date={i.currentPeriodEnd} displays={["mdy"]} />
|
|
</div>
|
|
) : (
|
|
<div>{notAvailable}</div>
|
|
)}
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
name: "cancelledAt",
|
|
title: t("models.subscription.cancelledAt"),
|
|
value: (i) => <div>{i.cancelledAt ? <DateCell date={i.cancelledAt} displays={["mdy"]} /> : notAvailable}</div>,
|
|
},
|
|
{
|
|
name: "endsAt",
|
|
title: t("models.subscription.endsAt"),
|
|
value: (i) => (
|
|
<div>
|
|
{i.endsAt ? (
|
|
<div>
|
|
{new Date() < new Date(i.endsAt) ? (
|
|
<div className="text-orange-500">
|
|
{t("settings.subscription.ends")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
|
</div>
|
|
) : (
|
|
<div className="text-red-500">
|
|
{t("settings.subscription.endedAt")} {formatters.date(i.endsAt, { dateStyle: "medium" })}
|
|
</div>
|
|
)}
|
|
</div>
|
|
) : (
|
|
notAvailable
|
|
)}
|
|
</div>
|
|
),
|
|
},
|
|
{
|
|
name: "actions",
|
|
title: t("shared.actions"),
|
|
value: (i) => (
|
|
<Link to={`${i.id}`} className="hover:underline">
|
|
{t("shared.edit")}
|
|
</Link>
|
|
),
|
|
},
|
|
]}
|
|
/>
|
|
|
|
<SlideOverWideEmpty
|
|
open={!!outlet}
|
|
onClose={() => {
|
|
navigate(".", { replace: true });
|
|
}}
|
|
className="sm:max-w-sm"
|
|
overflowYScroll={true}
|
|
>
|
|
<div className="-mx-1 -mt-3">
|
|
<div className="space-y-4">{outlet}</div>
|
|
</div>
|
|
</SlideOverWideEmpty>
|
|
</EditPageLayout>
|
|
);
|
|
}
|