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,236 @@
|
||||
import { useEffect } from "react";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect } from "react-router";
|
||||
import { Outlet, useLocation, useNavigate, useParams } from "react-router";
|
||||
import AppLayout from "~/components/app/AppLayout";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { loadAppData } from "~/utils/data/.server/appData";
|
||||
import {
|
||||
getAuthUserWithoutPasswordById as getUser,
|
||||
getTenantMembershipByIds as getTenantUserByIds,
|
||||
updateAuthUserDefaultTenantId as updateUserDefaultTenantId,
|
||||
} from "@toolctrl/db/auth-boundary.server";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import ServerError from "~/components/ui/errors/ServerError";
|
||||
import { createUniqueTenantIpAddress } from "~/utils/db/tenants/tenantIpAddress.db.server";
|
||||
import { getClientIPAddress } from "~/utils/server/IpUtils";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import FeedbackServer from "~/modules/helpDesk/services/Feedback.server";
|
||||
import SupportTicketsServer from "~/modules/helpDesk/services/SupportTickets.server";
|
||||
import clsx from "clsx";
|
||||
import { useThemePreviewStore } from "~/stores/themePreviewStore";
|
||||
import { getThemeStyle, parseThemeConfig } from "~/utils/theme/ThemeConfig";
|
||||
import { loadRequiredWebConfig } from "@toolctrl/config";
|
||||
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
||||
import { appTenantDeactivatedPath, appTenantPlanRequiredPath, appTenantSubscriptionRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
import { withMetrics } from "~/lib/metrics/ssr";
|
||||
import { getIsSuperAdminByUserId, requireAuth } from "~/utils/loaders.middleware";
|
||||
import { ensureTenantUserAppRoles } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { evaluatePasswordPolicyBanner } from "~/services/auth/password-policy-banner.server";
|
||||
import PasswordPolicyBanner from "~/components/app/PasswordPolicyBanner";
|
||||
export { serverTimingHeaders as headers };
|
||||
export { appTenantDeactivatedPath, appTenantPlanRequiredPath, appTenantSubscriptionRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
||||
|
||||
export function appTenantPath(params: { tenant?: string }, path?: string) {
|
||||
return appPath({ tenantSlug: params.tenant ?? "", path, mode: "host-aware" });
|
||||
}
|
||||
|
||||
export function isAppTenantSettingsPath(pathname: string, params: { tenant?: string }) {
|
||||
if (!params.tenant) {
|
||||
return false;
|
||||
}
|
||||
return UrlUtils.stripTrailingSlash(pathname).startsWith(appTenantPath(params, "settings"));
|
||||
}
|
||||
|
||||
function hasAppTenantSubscriptionAccess(subscription: { products?: readonly unknown[] | null; trial?: { active?: boolean | null } | null } | null | undefined) {
|
||||
return (subscription?.products?.length ?? 0) > 0 || subscription?.trial?.active === true;
|
||||
}
|
||||
|
||||
export const loader = withMetrics("app-tenant", async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant");
|
||||
const requestUrl = new URL(request.url);
|
||||
const redirectTo = `${requestUrl.pathname}${requestUrl.search}`;
|
||||
const [{ t }, userInfo] = await Promise.all([time(getTranslations(request), "getTranslations"), time(getUserInfo(request), "getUserInfo")]);
|
||||
if (!userInfo.userId) {
|
||||
const searchParams = new URLSearchParams([["redirectTo", redirectTo]]);
|
||||
throw redirect(`/login?${searchParams}`);
|
||||
}
|
||||
const tenantId = await time(getTenantIdFromUrl(params), "getTenantIdFromUrl");
|
||||
const [user, tenantUser] = await Promise.all([
|
||||
time(getUser(userInfo.userId), "getUser"),
|
||||
time(getTenantUserByIds(tenantId, userInfo.userId), "getTenantUserByIds"),
|
||||
]);
|
||||
const isOperatorAdmin = !!user?.admin || (await time(getIsSuperAdminByUserId(userInfo.userId), "getIsSuperAdminByUserId"));
|
||||
if (!tenantUser && !isOperatorAdmin) {
|
||||
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
|
||||
}
|
||||
if (tenantUser) {
|
||||
await time(
|
||||
ensureTenantUserAppRoles({
|
||||
userId: userInfo.userId,
|
||||
tenantId,
|
||||
tenantUserType: tenantUser.type,
|
||||
}),
|
||||
"ensureTenantUserAppRoles"
|
||||
);
|
||||
}
|
||||
|
||||
const data = await time(loadAppData({ request, params, t, time, tenantId, userInfo, user }), "loadAppData");
|
||||
if (!isOperatorAdmin && user?.defaultTenantId !== tenantId) {
|
||||
await time(updateUserDefaultTenantId({ defaultTenantId: tenantId }, userInfo.userId), "updateUserDefaultTenantId");
|
||||
}
|
||||
// Store IP Address
|
||||
await time(
|
||||
createUniqueTenantIpAddress({
|
||||
ip: getClientIPAddress(request) ?? "Unknown",
|
||||
fromUrl: new URL(request.url).pathname,
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
}),
|
||||
"createUniqueTenantIpAddress"
|
||||
);
|
||||
|
||||
if (!isAppTenantSettingsPath(new URL(request.url).pathname, params)) {
|
||||
const appConfiguration = await time(getAppConfiguration({ request }), "getAppConfiguration");
|
||||
if (appConfiguration.subscription.required && !hasAppTenantSubscriptionAccess(data.mySubscription)) {
|
||||
throw redirect(appTenantPlanRequiredPath(params));
|
||||
}
|
||||
}
|
||||
if (data.currentTenant.deactivatedReason) {
|
||||
throw redirect(appTenantDeactivatedPath(params));
|
||||
}
|
||||
|
||||
// Phase 01 / #27 — surface the password-policy soft-banner when the
|
||||
// session flag is set and the user has not snoozed it via the
|
||||
// pwPolicyRemindAfter cookie. Pure function — easy to unit test.
|
||||
const passwordPolicyBanner = evaluatePasswordPolicyBanner({
|
||||
policyOutdated: userInfo.passwordPolicyOutdated === true,
|
||||
cookieHeader: request.headers.get("cookie"),
|
||||
});
|
||||
|
||||
return Response.json({ ...data, passwordPolicyBanner }, { headers: getServerTimingHeader() });
|
||||
});
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
const { t } = await getTranslations(request);
|
||||
const userInfo = await requireAuth({ request, params });
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
if (action === "add-feedback") {
|
||||
if (!userInfo.userId) {
|
||||
return Response.json({ error: t("feedback.notLoggedIn") }, { status: 400 });
|
||||
}
|
||||
const message = form.get("message")?.toString() || "";
|
||||
const fromUrl = form.get("fromUrl")?.toString() || "";
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
if (!message) {
|
||||
return Response.json({ error: t("feedback.messageRequired") }, { status: 400 });
|
||||
}
|
||||
try {
|
||||
await FeedbackServer.send({
|
||||
t,
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
message,
|
||||
fromUrl,
|
||||
});
|
||||
return Response.json({ success: t("feedback.sent") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
if (action === "create-support-ticket") {
|
||||
if (!userInfo.userId) {
|
||||
return Response.json({ error: t("feedback.notLoggedIn") }, { status: 400 });
|
||||
}
|
||||
const message = form.get("message")?.toString() || "";
|
||||
const subject = form.get("subject")?.toString() || "";
|
||||
const fromUrl = form.get("fromUrl")?.toString() || "";
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
try {
|
||||
await SupportTicketsServer.createInline({
|
||||
t,
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
subject,
|
||||
message,
|
||||
fromUrl,
|
||||
});
|
||||
return Response.json({ success: t("helpDesk.tickets.created") });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
return { error: t("shared.invalidAction") };
|
||||
};
|
||||
|
||||
type AppTenantLoaderExtras = {
|
||||
passwordPolicyBanner?: { show: boolean; reason?: string };
|
||||
};
|
||||
|
||||
export default function AppTenantRoute() {
|
||||
const appData = useAppData() as ReturnType<typeof useAppData> & AppTenantLoaderExtras;
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const params = useParams();
|
||||
const { appConfiguration, userSession } = useRootData();
|
||||
const isDarkMode = userSession?.lightOrDarkMode === "dark";
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
const changePasswordHref = appTenantPath({ tenant: tenantSlug }, "settings/profile");
|
||||
|
||||
const { isPreviewActive, previewTheme, previewConfig } = useThemePreviewStore();
|
||||
// const [showChat, setShowChat] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!appData.currentTenant) {
|
||||
navigate("/");
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [appData.currentTenant]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAppTenantSettingsPath(location.pathname, params)) {
|
||||
if (appConfiguration.subscription.required && !hasAppTenantSubscriptionAccess(appData.mySubscription)) {
|
||||
navigate(appTenantPlanRequiredPath(params));
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [location.pathname]);
|
||||
|
||||
// Use preview theme if preview is active, otherwise use saved theme
|
||||
const activeTheme = isPreviewActive && previewTheme ? previewTheme : appData?.currentTenant?.theme;
|
||||
|
||||
// Get theme config (use preview if active, otherwise use saved)
|
||||
const themeConfig = isPreviewActive && previewConfig ? previewConfig : parseThemeConfig(appData?.currentTenant?.themeConfig as string | null);
|
||||
|
||||
const themeStyle = getThemeStyle({ themeConfig, isDarkMode });
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={clsx("tenant-theme bg-secondary min-h-screen", activeTheme && `theme-${activeTheme}`, activeTheme?.endsWith("-scaled") && "theme-scaled")}
|
||||
style={themeStyle as React.CSSProperties}
|
||||
>
|
||||
<AppLayout layout="app">
|
||||
{appData.passwordPolicyBanner?.show ? (
|
||||
<div className="px-4 pt-4 sm:px-6 lg:px-8">
|
||||
<PasswordPolicyBanner changePasswordHref={changePasswordHref} />
|
||||
</div>
|
||||
) : null}
|
||||
<Outlet />
|
||||
</AppLayout>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
Reference in new issue
Block a user