Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,8 +1,11 @@
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { ActionFunctionArgs, LoaderFunctionArgs, redirect } from "react-router";
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, type MiddlewareFunction } from "react-router";
import { Outlet, useLocation, useNavigate, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import AppLayout from "~/components/app/AppLayout";
import { SubscriptionStatusBanner } from "~/components/screens/billing/SubscriptionStatusBanner";
import SidebarIconsLayout from "~/components/ui/layouts/SidebarIconsLayout";
import { AppSidebar } from "~/application/sidebar/AppSidebar";
import { useAppData } from "~/utils/data/useAppData";
import { loadAppData } from "~/utils/data/.server/appData";
import {
@@ -18,27 +21,48 @@ 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 { getTrustedClientIpOrNull } 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 FeedbackServer, {
FeedbackUserError,
isAllowedFeedbackAttachmentMimeType,
MAX_FEEDBACK_ATTACHMENT_BYTES,
type FeedbackAttachmentInput,
} 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 "@hivegrid/config";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { appTenantDeactivatedPath, appTenantPlanRequiredPath, appTenantSubscriptionRequiredPath } from "~/utils/app/AppTenantStatusPaths";
import { appTenantDeactivatedPath, appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
import { withMetrics } from "~/lib/metrics/ssr";
import { getIsSuperAdminByUserId, requireAuth } from "~/utils/loaders.middleware";
import { 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";
import { buildBillingStatusBannerVm, getTenantBillingReadOnlyState, type BillingStatusBannerVm } from "~/utils/services/.server/billingStatusService";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { TelephonyPushBootstrap } from "~/components/pwa/TelephonyPushBootstrap";
import { useRedirectToast } from "~/hooks/use-save-toast";
import { hasTenantSubscriptionAccess, requiresTenantSubscriptionActivation } from "~/utils/app/SubscriptionAccess";
import { loadTenantRegistrationBillingPreference } from "~/services/billing/registration-billing-preference.server";
export { serverTimingHeaders as headers };
export { appTenantDeactivatedPath, appTenantPlanRequiredPath, appTenantSubscriptionRequiredPath } from "~/utils/app/AppTenantStatusPaths";
export const middleware: MiddlewareFunction<Response>[] = [
async ({ request, params }, next) => {
const userInfo = await getUserInfo(request);
if (!userInfo.userId) return next();
const tenantId = await getTenantIdFromUrl(params);
const membership = await getTenantUserByIds(tenantId, userInfo.userId);
if (!membership) {
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
return runWithRlsContext({ tenantId }, next);
},
];
export function appTenantPath(params: { tenant?: string }, path?: string) {
return appPath({ tenantSlug: params.tenant ?? "", path, mode: "host-aware" });
}
@@ -50,8 +74,12 @@ export function isAppTenantSettingsPath(pathname: string, params: { tenant?: str
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 function isAppTenantSubscriptionActivationPath(pathname: string, params: { tenant?: string }) {
return Boolean(params.tenant) && UrlUtils.stripTrailingSlash(pathname) === UrlUtils.stripTrailingSlash(appTenantPath(params, "settings/billing"));
}
export function isAppTenantWelcomePath(pathname: string, params: { tenant?: string }) {
return Boolean(params.tenant) && UrlUtils.stripTrailingSlash(pathname) === UrlUtils.stripTrailingSlash(appTenantPath(params, "onboarding/welcome"));
}
export const loader = withMetrics("app-tenant", async ({ request, params }: LoaderFunctionArgs) => {
@@ -68,29 +96,26 @@ export const loader = withMetrics("app-tenant", async ({ request, params }: Load
time(getUser(userInfo.userId), "getUser"),
time(getTenantUserByIds(tenantId, userInfo.userId), "getTenantUserByIds"),
]);
const isOperatorAdmin = !!user?.admin || (await time(getIsSuperAdminByUserId(userInfo.userId), "getIsSuperAdminByUserId"));
if (!tenantUser && !isOperatorAdmin) {
if (!tenantUser) {
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
}
if (tenantUser) {
await time(
ensureTenantUserAppRoles({
userId: userInfo.userId,
tenantId,
tenantUserType: tenantUser.type,
}),
"ensureTenantUserAppRoles"
);
}
await time(
ensureTenantUserAppRoles({
userId: userInfo.userId,
tenantId,
tenantUserType: tenantUser.type,
}),
"ensureTenantUserAppRoles"
);
const data = await time(loadAppData({ request, params, t, time, tenantId, userInfo, user, isOperatorAdmin }), "loadAppData");
if (!isOperatorAdmin && user?.defaultTenantId !== tenantId) {
const data = await time(loadAppData({ request, params, t, time, tenantId, userInfo, user, isOperatorAdmin: false }), "loadAppData");
if (user?.defaultTenantId !== tenantId) {
await time(updateUserDefaultTenantId({ defaultTenantId: tenantId }, userInfo.userId), "updateUserDefaultTenantId");
}
// Store IP Address
await time(
createUniqueTenantIpAddress({
ip: getClientIPAddress(request) ?? "Unknown",
ip: getTrustedClientIpOrNull(request) ?? "Unknown",
fromUrl: new URL(request.url).pathname,
tenantId,
userId: userInfo.userId,
@@ -98,31 +123,27 @@ export const loader = withMetrics("app-tenant", async ({ request, params }: Load
"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));
}
const [appConfiguration, registrationBillingPreference] = await Promise.all([
time(getAppConfiguration({ request }), "getAppConfiguration"),
hasTenantSubscriptionAccess(data.mySubscription)
? Promise.resolve(null)
: runWithRlsContext({ tenantId, userId: userInfo.userId }, () =>
time(loadTenantRegistrationBillingPreference(tenantId), "loadTenantRegistrationBillingPreference")
),
]);
const subscriptionActivationRequired = requiresTenantSubscriptionActivation(
appConfiguration.subscription.required || registrationBillingPreference !== null,
data.mySubscription
);
const pathname = new URL(request.url).pathname;
if (subscriptionActivationRequired && !isAppTenantSubscriptionActivationPath(pathname, params)) {
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"),
});
const billingStatusBanner = buildBillingStatusBannerVm({
status: data.mySubscription?.status,
tenantSlug: params.tenant ?? tenantId,
trialEndsAt: data.mySubscription?.trialEndsAt,
});
return Response.json({ ...data, passwordPolicyBanner, billingStatusBanner }, { headers: getServerTimingHeader() });
return Response.json({ ...data, subscriptionActivationRequired }, { headers: getServerTimingHeader() });
});
export const action = async ({ request, params }: ActionFunctionArgs) => {
@@ -137,6 +158,10 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
}
const message = form.get("message")?.toString() || "";
const fromUrl = form.get("fromUrl")?.toString() || "";
// AK-P21 widget: optional category (bug/feature/question) is prefixed into
// the message — the support-ticket contract has no category column.
const category = form.get("category")?.toString() || "";
const categoryLabel = ["bug", "feature", "question"].includes(category) ? t(`feedback.category.${category}`) : "";
const tenantId = await getTenantIdFromUrl(params);
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
@@ -145,17 +170,42 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
if (!message) {
return Response.json({ error: t("feedback.messageRequired") }, { status: 400 });
}
// AK-P21: optional single image attachment (decision 2026-07-21 — upload
// instead of an in-app screenshot capture). Oversized bodies are rejected
// before the bytes are read into memory.
const uploaded = form.get("attachment");
let attachment: FeedbackAttachmentInput | null = null;
if (uploaded && typeof uploaded === "object" && "arrayBuffer" in uploaded && uploaded.size > 0) {
if (uploaded.size > MAX_FEEDBACK_ATTACHMENT_BYTES) {
return Response.json(
{ error: t("feedback.attachment.tooLarge", { megabytes: Math.floor(MAX_FEEDBACK_ATTACHMENT_BYTES / (1024 * 1024)) }) },
{ status: 400 }
);
}
if (!isAllowedFeedbackAttachmentMimeType(uploaded.type)) {
return Response.json({ error: t("feedback.attachment.unsupportedType") }, { status: 400 });
}
attachment = {
filename: uploaded.name || "feedback-attachment",
mimeType: uploaded.type,
bytes: new Uint8Array(await uploaded.arrayBuffer()),
};
}
try {
await FeedbackServer.send({
t,
tenantId,
userId: userInfo.userId,
message,
message: categoryLabel ? `[${categoryLabel}] ${message}` : message,
fromUrl,
attachment,
});
return Response.json({ success: t("feedback.sent") });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
} catch (error) {
if (error instanceof FeedbackUserError) {
return Response.json({ error: t(error.messageKey) }, { status: error.status });
}
return Response.json({ error: t("feedback.unavailable") }, { status: 503 });
}
}
if (action === "create-support-ticket") {
@@ -165,6 +215,9 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
const message = form.get("message")?.toString() || "";
const subject = form.get("subject")?.toString() || "";
const fromUrl = form.get("fromUrl")?.toString() || "";
if (!message.trim()) {
return Response.json({ error: t("feedback.messageRequired") }, { status: 400 });
}
const tenantId = await getTenantIdFromUrl(params);
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
@@ -180,32 +233,27 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
fromUrl,
});
return Response.json({ success: t("helpDesk.tickets.created") });
} catch (e: any) {
return Response.json({ error: e.message }, { status: 400 });
} catch {
return Response.json({ error: t("feedback.unavailable") }, { status: 503 });
}
}
return { error: t("shared.invalidAction") };
};
type AppTenantLoaderExtras = {
passwordPolicyBanner?: { show: boolean; reason?: string };
billingStatusBanner?: BillingStatusBannerVm;
};
export default function AppTenantRoute() {
const appData = useAppData() as ReturnType<typeof useAppData> & AppTenantLoaderExtras;
const appData = useAppData();
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const params = useParams();
const { t } = useTranslation();
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 { appConfiguration, routing, csrf, webPushVapidPublicKey } = useRootData();
const subscriptionActivationRequired =
appData.subscriptionActivationRequired ??
requiresTenantSubscriptionActivation(appConfiguration.subscription.required, appData.mySubscription);
// const [showChat, setShowChat] = useState(false);
useRedirectToast();
useEffect(() => {
if (!appData.currentTenant) {
navigate("/");
@@ -214,48 +262,92 @@ export default function AppTenantRoute() {
}, [appData.currentTenant]);
useEffect(() => {
if (!isAppTenantSettingsPath(location.pathname, params)) {
if (appConfiguration.subscription.required && !hasAppTenantSubscriptionAccess(appData.mySubscription)) {
navigate(appTenantPlanRequiredPath(params));
}
if (subscriptionActivationRequired && !isAppTenantSubscriptionActivationPath(location.pathname, params)) {
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;
const sidebarItems = AppSidebar({
t,
i18n,
tenantId: params.tenant ?? "",
appConfiguration,
routing,
productAccess: appData.productAccess,
});
const workspaceArea = sidebarItems
.flatMap((group) => group.items ?? [])
.find((item) => item.contextItems && item.activePaths?.some((path) => isPathWithin(location.pathname, path)));
const contextItems = (workspaceArea?.contextItems ?? []).filter((item) => !item.permission || getUserHasPermission(appData, item.permission));
const telephonyPushEnabled =
appData.productAccess?.telephony?.allowed === true &&
(["telephony.read_own", "telephony.read_all", "telephony.manage"] as const).some((permission) => getUserHasPermission(appData, permission));
// Get theme config (use preview if active, otherwise use saved)
const themeConfig = isPreviewActive && previewConfig ? previewConfig : parseThemeConfig(appData?.currentTenant?.themeConfig as string | null);
const subscriptionActivationMode = subscriptionActivationRequired && isAppTenantSubscriptionActivationPath(location.pathname, params);
const welcomeMode = isAppTenantWelcomePath(location.pathname, params);
const themeStyle = getThemeStyle({ themeConfig, isDarkMode });
if (subscriptionActivationMode || welcomeMode) {
return (
<div
className="bg-surface-neutral-secondary min-h-screen"
data-ui-id={subscriptionActivationMode ? "ui.billing.activation.shell" : "ui.onboarding.welcome.shell"}
>
<Outlet />
</div>
);
}
return (
<>
<div
className={clsx("tenant-theme bg-secondary min-h-screen", activeTheme && `theme-${activeTheme}`, activeTheme?.endsWith("-scaled") && "theme-scaled")}
style={themeStyle as React.CSSProperties}
>
<TelephonyPushBootstrap
enabled={telephonyPushEnabled}
tenantSlug={appData.currentTenant.slug}
vapidPublicKey={webPushVapidPublicKey}
csrfToken={csrf}
isDev={import.meta.env?.DEV}
/>
<div className="bg-secondary min-h-screen">
<AppLayout layout="app">
{appData.passwordPolicyBanner?.show ? (
<div className="px-4 pt-4 sm:px-6 lg:px-8">
<PasswordPolicyBanner changePasswordHref={changePasswordHref} />
<SubscriptionStatusBanner
vm={appData.billingBanner}
actions={{
onOpenSubscription: getUserHasPermission(appData, "app.settings.subscription.view")
? () => navigate(appTenantPath(params, "settings/billing"))
: undefined,
}}
/>
{contextItems.length > 1 ? (
// A workspace area (e.g. appointments = calendar/bookings/availability) keeps its
// sibling screens in an inner sidebar, the same rail the hr/settings layouts use;
// SidebarIconsLayout falls back to a tab bar below the sm breakpoint.
<div data-ui-id="ui.app.workspace-context-nav">
<SidebarIconsLayout
items={contextItems.map((item) => ({
name: item.title,
href: item.path,
icon: item.icon,
exact: item.exact,
}))}
>
<Outlet />
</SidebarIconsLayout>
</div>
) : null}
{appData.billingStatusBanner?.visible ? (
<div className="px-4 pt-4 sm:px-6 lg:px-8">
<div className="rounded-md border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-50">
{t(appData.billingStatusBanner.messageKey)}
</div>
</div>
) : null}
<Outlet />
) : (
<Outlet />
)}
</AppLayout>
</div>
</>
);
}
function isPathWithin(currentPath: string, routePath: string): boolean {
const current = UrlUtils.stripTrailingSlash(currentPath);
const route = UrlUtils.stripTrailingSlash(routePath);
return current === route || current.startsWith(`${route}/`);
}
export function ErrorBoundary() {
return <ServerError />;
}