354 lines
15 KiB
TypeScript
354 lines
15 KiB
TypeScript
import { useEffect } from "react";
|
|
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 {
|
|
getAuthUserWithoutPasswordById as getUser,
|
|
getTenantMembershipByIds as getTenantUserByIds,
|
|
updateAuthUserDefaultTenantId as updateUserDefaultTenantId,
|
|
} from "@hivegrid/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 { 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, {
|
|
FeedbackUserError,
|
|
isAllowedFeedbackAttachmentMimeType,
|
|
MAX_FEEDBACK_ATTACHMENT_BYTES,
|
|
type FeedbackAttachmentInput,
|
|
} from "~/modules/helpDesk/services/Feedback.server";
|
|
import SupportTicketsServer from "~/modules/helpDesk/services/SupportTickets.server";
|
|
import { loadRequiredWebConfig } from "@hivegrid/config";
|
|
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
|
import { appTenantDeactivatedPath, appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
|
|
import { withMetrics } from "~/lib/metrics/ssr";
|
|
import { requireAuth } from "~/utils/loaders.middleware";
|
|
import { ensureTenantUserAppRoles } from "~/utils/db/permissions/userRoles.db.server";
|
|
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" });
|
|
}
|
|
|
|
export function isAppTenantSettingsPath(pathname: string, params: { tenant?: string }) {
|
|
if (!params.tenant) {
|
|
return false;
|
|
}
|
|
return UrlUtils.stripTrailingSlash(pathname).startsWith(appTenantPath(params, "settings"));
|
|
}
|
|
|
|
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) => {
|
|
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"),
|
|
]);
|
|
if (!tenantUser) {
|
|
throw redirect(absoluteAppRootPath(loadRequiredWebConfig().routing));
|
|
}
|
|
await time(
|
|
ensureTenantUserAppRoles({
|
|
userId: userInfo.userId,
|
|
tenantId,
|
|
tenantUserType: tenantUser.type,
|
|
}),
|
|
"ensureTenantUserAppRoles"
|
|
);
|
|
|
|
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: getTrustedClientIpOrNull(request) ?? "Unknown",
|
|
fromUrl: new URL(request.url).pathname,
|
|
tenantId,
|
|
userId: userInfo.userId,
|
|
}),
|
|
"createUniqueTenantIpAddress"
|
|
);
|
|
|
|
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));
|
|
}
|
|
|
|
return Response.json({ ...data, subscriptionActivationRequired }, { 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() || "";
|
|
// 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) {
|
|
return Response.json({ error: t("billing:status.readOnly") }, { status: 423 });
|
|
}
|
|
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: categoryLabel ? `[${categoryLabel}] ${message}` : message,
|
|
fromUrl,
|
|
attachment,
|
|
});
|
|
return Response.json({ success: t("feedback.sent") });
|
|
} 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") {
|
|
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() || "";
|
|
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) {
|
|
return Response.json({ error: t("billing:status.readOnly") }, { status: 423 });
|
|
}
|
|
try {
|
|
await SupportTicketsServer.createInline({
|
|
t,
|
|
tenantId,
|
|
userId: userInfo.userId,
|
|
subject,
|
|
message,
|
|
fromUrl,
|
|
});
|
|
return Response.json({ success: t("helpDesk.tickets.created") });
|
|
} catch {
|
|
return Response.json({ error: t("feedback.unavailable") }, { status: 503 });
|
|
}
|
|
}
|
|
return { error: t("shared.invalidAction") };
|
|
};
|
|
|
|
export default function AppTenantRoute() {
|
|
const appData = useAppData();
|
|
const { t, i18n } = useTranslation();
|
|
const navigate = useNavigate();
|
|
const location = useLocation();
|
|
const params = useParams();
|
|
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("/");
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [appData.currentTenant]);
|
|
|
|
useEffect(() => {
|
|
if (subscriptionActivationRequired && !isAppTenantSubscriptionActivationPath(location.pathname, params)) {
|
|
navigate(appTenantPlanRequiredPath(params));
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [location.pathname]);
|
|
|
|
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));
|
|
|
|
const subscriptionActivationMode = subscriptionActivationRequired && isAppTenantSubscriptionActivationPath(location.pathname, params);
|
|
const welcomeMode = isAppTenantWelcomePath(location.pathname, params);
|
|
|
|
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 (
|
|
<>
|
|
<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">
|
|
<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>
|
|
) : (
|
|
<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 />;
|
|
}
|