Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+85
-20
@@ -1,46 +1,111 @@
|
||||
import type { LoaderFunctionArgs } from "react-router";
|
||||
import type { AdminDashboardVM } from "@hivegrid/view-models";
|
||||
import {
|
||||
isAdminRoleKey,
|
||||
isAdminPermissionName,
|
||||
type AdminPermissionName,
|
||||
type AdminRoleKey,
|
||||
} from "@hivegrid/db/admin-permissions";
|
||||
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import { adminGetAllTenantsWithUsage, type TenantWithUsage } from "~/utils/db/tenants.db.server";
|
||||
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
|
||||
import PeriodHelper from "~/utils/helpers/PeriodHelper";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";
|
||||
import { getAdminDashboardOverview, getAdminDashboardStats, type AdminDashboardOverview } from "~/utils/services/adminDashboardService";
|
||||
import type { Stat } from "~/application/dtos/stats/Stat";
|
||||
import type { PaginationDto } from "~/application/dtos/data/PaginationDto";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
|
||||
import { loadPersonalizedAdminDashboard } from "~/services/admin/admin-dashboard-personalization.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
|
||||
export type AdminDashboardLoaderData = {
|
||||
title: string;
|
||||
stats: Stat[];
|
||||
tenants: {
|
||||
items: TenantWithUsage[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
dashboard: AdminDashboardVM;
|
||||
superOverview: {
|
||||
stats: Stat[];
|
||||
overview: AdminDashboardOverview;
|
||||
tenants: {
|
||||
items: TenantWithUsage[];
|
||||
pagination: PaginationDto;
|
||||
};
|
||||
} | null;
|
||||
};
|
||||
|
||||
type AdminDashboardDataArgs = Pick<LoaderFunctionArgs, "request" | "params">;
|
||||
|
||||
export async function loadAdminDashboardRouteData({ request, params }: AdminDashboardDataArgs) {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.dashboard");
|
||||
const urlSearchParams = new URL(request.url).searchParams;
|
||||
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
|
||||
|
||||
const { t } = await time(getTranslations(request), "getTranslations");
|
||||
const { stats, tenants } = await time(
|
||||
promiseHash({
|
||||
stats: time(
|
||||
getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
|
||||
"admin.dashboard.details.getAdminDashboardStats"
|
||||
),
|
||||
tenants: time(adminGetAllTenantsWithUsage(undefined, currentPagination), "admin.dashboard.details.adminGetAllTenantsWithUsage"),
|
||||
const { t, locale } = await time(getTranslations(request), "getTranslations");
|
||||
const { dashboard, superOverview } = await time(
|
||||
runAsAdminIdentity(request, ADMIN_AREA_ACCESS.dashboard, async (session) => {
|
||||
const [permissionNames, roleRows] = await Promise.all([
|
||||
listAdminPermissionNames(session.adminUserId),
|
||||
db.adminUserRole.findMany({
|
||||
where: {
|
||||
adminUserId: session.adminUserId,
|
||||
role: { active: true },
|
||||
},
|
||||
select: { role: { select: { systemKey: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
}),
|
||||
]);
|
||||
const permissions = permissionNames.filter(isAdminPermissionName);
|
||||
const roleKeys = roleRows
|
||||
.map((row) => row.role.systemKey)
|
||||
.filter((roleKey): roleKey is AdminRoleKey =>
|
||||
Boolean(roleKey && isAdminRoleKey(roleKey))
|
||||
);
|
||||
const dashboard = await loadPersonalizedAdminDashboard({
|
||||
adminUserId: session.adminUserId,
|
||||
roleKeys,
|
||||
permissions: permissions as AdminPermissionName[],
|
||||
locale,
|
||||
});
|
||||
const superOverview = roleKeys.includes("super_admin")
|
||||
? await loadSuperAdminOverview(request, t, time)
|
||||
: null;
|
||||
return { dashboard, superOverview };
|
||||
}),
|
||||
"admin.dashboard.details"
|
||||
"admin.dashboard.personalized"
|
||||
);
|
||||
|
||||
const data: AdminDashboardLoaderData = {
|
||||
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
|
||||
stats,
|
||||
tenants,
|
||||
dashboard,
|
||||
superOverview,
|
||||
};
|
||||
return { data, headers: getServerTimingHeader() };
|
||||
}
|
||||
|
||||
async function loadSuperAdminOverview(
|
||||
request: Request,
|
||||
t: (key: string) => string,
|
||||
time: <T>(promise: Promise<T>, name: string) => Promise<T>
|
||||
) {
|
||||
const currentPagination = getPaginationFromCurrentUrl(
|
||||
new URL(request.url).searchParams
|
||||
);
|
||||
return time(
|
||||
promiseHash({
|
||||
stats: time(
|
||||
getAdminDashboardStats({
|
||||
t,
|
||||
gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }),
|
||||
}),
|
||||
"admin.dashboard.details.getAdminDashboardStats"
|
||||
),
|
||||
overview: time(
|
||||
getAdminDashboardOverview(),
|
||||
"admin.dashboard.details.getAdminDashboardOverview"
|
||||
),
|
||||
tenants: time(
|
||||
adminGetAllTenantsWithUsage(undefined, currentPagination),
|
||||
"admin.dashboard.details.adminGetAllTenantsWithUsage"
|
||||
),
|
||||
}),
|
||||
"admin.dashboard.super"
|
||||
);
|
||||
}
|
||||
+7
-6
@@ -6,19 +6,20 @@ function readAdminDataSource() {
|
||||
return readRepoFile("apps/web/app/utils/data/.server/adminData.ts");
|
||||
}
|
||||
|
||||
describe("admin data MFA enforcement boundary", () => {
|
||||
describe("admin data Authentik MFA assurance boundary", () => {
|
||||
test("does not import MFA secret or recovery-code storage directly", () => {
|
||||
const source = readAdminDataSource();
|
||||
|
||||
expect(source).not.toMatch(/mfaRecoveryCode|totpSecret|encryptedTotpSecret/i);
|
||||
});
|
||||
|
||||
test("routes shared admin loader through the MFA enforcement boundary", () => {
|
||||
test("accepts only a validated tenantless AdminSession", () => {
|
||||
const source = readAdminDataSource();
|
||||
|
||||
expect(source).toContain("getUserTotpStatus");
|
||||
expect(source).toContain("checkMfaStepUpState");
|
||||
expect(source).toContain("enforceAdminMfa");
|
||||
expect(source).toMatch(/if \(!mfaEnforcement\.allowed\) \{\s*throw redirect\(mfaEnforcement\.redirectTo\);\s*\}/);
|
||||
expect(source).toContain("getValidatedServerSession");
|
||||
expect(source).toContain('"adminUser" in validatedSession');
|
||||
expect(source).toContain("validatedSession.adminUser");
|
||||
expect(source).not.toContain("getUserTotpStatus");
|
||||
expect(source).not.toContain("enforceAdminMfa");
|
||||
});
|
||||
});
|
||||
+58
-62
@@ -1,81 +1,77 @@
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import OnboardingService from "~/modules/onboarding/services/OnboardingService";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
|
||||
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getPermissionsByUser, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { getUserTotpStatus } from "~/utils/db/users.db.server";
|
||||
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
|
||||
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getUserInfo, getUserSession } from "~/utils/session.server";
|
||||
import { AdminLoaderData } from "../useAdminData";
|
||||
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { TFunction } from "i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { redirect } from "react-router";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
|
||||
export async function loadAdminData({ request, t }: { request: Request; t: TFunction }, time: TimeFunction) {
|
||||
import { adminGetAllActiveTenants } from "@hivegrid/db/auth-boundary.server";
|
||||
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import type { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { getUserInfo, getValidatedServerSession } from "~/utils/session.server";
|
||||
import type { AdminLoaderData } from "../useAdminData";
|
||||
|
||||
export async function loadAdminData({ request, t: _t }: { request: Request; t: TFunction }, time: TimeFunction) {
|
||||
const userInfo = await time(getUserInfo(request), "getUserInfo");
|
||||
const url = new URL(request.url);
|
||||
if (UrlUtils.stripTrailingSlash(url.pathname) === `/admin`) {
|
||||
if (UrlUtils.stripTrailingSlash(url.pathname) === "/admin") {
|
||||
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
}
|
||||
const user = await time(getUser(userInfo?.userId), "getUser");
|
||||
const redirectTo = url.pathname + url.search;
|
||||
if (!userInfo || !user) {
|
||||
let searchParams = new URLSearchParams([["redirect", redirectTo]]);
|
||||
if (!userInfo.userId) {
|
||||
const searchParams = new URLSearchParams([["redirect", url.pathname + url.search]]);
|
||||
throw redirect(`/login?${searchParams}`);
|
||||
}
|
||||
|
||||
if (!user.admin) {
|
||||
throw Response.json({ error: t("admin.errors.adminOnly") }, { status: 401 });
|
||||
const validatedSession = await time(getValidatedServerSession(request, userInfo), "getValidatedAdminSession");
|
||||
if (!validatedSession || !("adminUser" in validatedSession)) {
|
||||
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
}
|
||||
const admin = validatedSession.adminUser;
|
||||
|
||||
const session = await time(getUserSession(request), "getUserSession");
|
||||
const totpStatus = await time(getUserTotpStatus(user.id), "getUserTotpStatus");
|
||||
const stepUp = checkMfaStepUpState(session, user.id);
|
||||
const mfaEnforcement = enforceAdminMfa({
|
||||
requestUrl: url,
|
||||
userId: user.id,
|
||||
isAdmin: Boolean(user.admin),
|
||||
totpStatus,
|
||||
stepUp,
|
||||
redirectMode: "host-aware",
|
||||
});
|
||||
if (!mfaEnforcement.allowed) {
|
||||
throw redirect(mfaEnforcement.redirectTo);
|
||||
}
|
||||
|
||||
const myTenants = await time(getMyTenants(user.id), "getMyTenants");
|
||||
|
||||
const { allPermissions, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
|
||||
promiseHash({
|
||||
allPermissions: getPermissionsByUser(userInfo.userId, null),
|
||||
superAdminRole: getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin),
|
||||
allRoles: getAllRolesWithoutPermissions("admin"),
|
||||
myGroups: getMyGroups(user.id, null),
|
||||
onboardingSession: OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: null, request }),
|
||||
}),
|
||||
const { permissions, roles, myTenants } = await time(
|
||||
runWithRlsContext({ userId: admin.id }, async () => ({
|
||||
permissions: await listAdminPermissionNames(admin.id),
|
||||
roles: await db.adminRole.findMany({
|
||||
where: { active: true },
|
||||
select: { id: true, name: true, description: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
myTenants: await adminGetAllActiveTenants(),
|
||||
})),
|
||||
"loadAdminData.getDetails"
|
||||
);
|
||||
const isSuperAdmin = await runWithRlsContext({ userId: admin.id }, () =>
|
||||
db.adminUserRole.findFirst({
|
||||
where: { adminUserId: admin.id, role: { systemKey: "super_admin", active: true } },
|
||||
select: { adminUserId: true },
|
||||
})
|
||||
);
|
||||
|
||||
const data: AdminLoaderData = {
|
||||
user,
|
||||
user: {
|
||||
id: admin.id,
|
||||
email: admin.email,
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
avatar: admin.avatar,
|
||||
phone: null,
|
||||
admin: { userId: admin.id },
|
||||
defaultTenantId: null,
|
||||
createdAt: validatedSession.createdAt,
|
||||
locale: admin.locale,
|
||||
lightOrDarkMode: null,
|
||||
},
|
||||
myTenants,
|
||||
currentTenant: null,
|
||||
// roles,
|
||||
allRoles,
|
||||
permissions: allPermissions.map((f) => f as DefaultPermission),
|
||||
isSuperUser: !!superAdminRole,
|
||||
isSuperAdmin: !!superAdminRole,
|
||||
myGroups,
|
||||
lng: user?.locale ?? userInfo.lng,
|
||||
onboardingSession,
|
||||
tenantTypes: await getAllTenantTypes(),
|
||||
allRoles: roles,
|
||||
permissions: permissions as DefaultPermission[],
|
||||
isSuperUser: isSuperAdmin !== null,
|
||||
isSuperAdmin: isSuperAdmin !== null,
|
||||
myGroups: [],
|
||||
lng: admin.locale ?? userInfo.lng,
|
||||
onboardingSession: null,
|
||||
};
|
||||
return data;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
|
||||
const state = vi.hoisted(() => ({ superAdmin: false }));
|
||||
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "de" })) }));
|
||||
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
|
||||
getAuthUserWithoutPasswordById: vi.fn(async () => ({
|
||||
id: "user_1",
|
||||
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
|
||||
locale: "de",
|
||||
})),
|
||||
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Member tenant" }]),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
adminGetAllActiveTenantSimple: vi.fn(async () => [
|
||||
{ id: "tenant_1", slug: "acme", name: "Member tenant" },
|
||||
{ id: "tenant_2", slug: "global", name: "Global tenant" },
|
||||
]),
|
||||
getTenantSimple: vi.fn(async () => ({ id: "tenant_1", slug: "acme", name: "Member tenant", deactivatedReason: null })),
|
||||
getTenantUserType: vi.fn(async () => ({ type: TenantUserType.MEMBER })),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
|
||||
vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn(async () => []) }));
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn(async () => []) }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getPermissionsByUser: vi.fn(async () => []),
|
||||
getUserRoleInAdmin: vi.fn(async () => (state.superAdmin ? { id: "superadmin_assignment" } : null)),
|
||||
getUserRoleInTenant: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(async () => []) }));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
|
||||
getPlanFeatureUsage: vi.fn(async () => undefined),
|
||||
}));
|
||||
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
|
||||
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({ resolveTenantProductAccessBatch: vi.fn(async () => []) }));
|
||||
|
||||
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { adminGetAllActiveTenantSimple } from "~/utils/db/tenants.db.server";
|
||||
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { loadAppData } from "./appData";
|
||||
|
||||
function load() {
|
||||
return loadAppData({
|
||||
request: new Request("https://app.example.test/acme/dashboard"),
|
||||
params: { tenant: "acme" },
|
||||
t: ((key: string) => key) as never,
|
||||
});
|
||||
}
|
||||
|
||||
describe("loadAppData operator boundary", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
state.superAdmin = false;
|
||||
});
|
||||
|
||||
it("keeps Authentik staff tenant-scoped despite having an AdminUser identity", async () => {
|
||||
const data = await load();
|
||||
|
||||
expect(data.isSuperAdmin).toBe(false);
|
||||
expect(data.currentRole).toBe(TenantUserType.MEMBER);
|
||||
expect(data.myTenants).toHaveLength(1);
|
||||
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
|
||||
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
|
||||
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
|
||||
});
|
||||
|
||||
it("grants global tenant enumeration and product bypass only to the SuperAdmin RBAC role", async () => {
|
||||
state.superAdmin = true;
|
||||
|
||||
const data = await load();
|
||||
|
||||
expect(data.isSuperAdmin).toBe(true);
|
||||
expect(data.currentRole).toBe(TenantUserType.ADMIN);
|
||||
expect(data.myTenants).toHaveLength(2);
|
||||
expect(adminGetAllActiveTenantSimple).toHaveBeenCalledOnce();
|
||||
expect(getTenantsForUser).not.toHaveBeenCalled();
|
||||
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: true }));
|
||||
});
|
||||
});
|
||||
+17
-13
@@ -18,9 +18,8 @@ function deferred<T>(): Deferred<T> {
|
||||
const mocks = vi.hoisted(() => {
|
||||
const postDetails = {
|
||||
tenantUser: deferred<{ type: TenantUserType }>(),
|
||||
tenantTypes: deferred<unknown[]>(),
|
||||
credits: deferred<unknown>(),
|
||||
productAccess: deferred<{ allowed: boolean }>(),
|
||||
productAccess: deferred<Array<readonly [string, { allowed: boolean }]>>(),
|
||||
};
|
||||
return { postDetails };
|
||||
});
|
||||
@@ -28,7 +27,11 @@ const mocks = vi.hoisted(() => {
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "en" })) }));
|
||||
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
|
||||
getAuthUserWithoutPasswordById: vi.fn(async () => ({ id: "user_1", admin: false, locale: "en" })),
|
||||
getAuthUserWithoutPasswordById: vi.fn(async () => ({
|
||||
id: "user_1",
|
||||
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
|
||||
locale: "en",
|
||||
})),
|
||||
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Acme" }]),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({
|
||||
@@ -44,20 +47,20 @@ vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getUserRoleInAdmin: vi.fn(async () => null),
|
||||
getUserRoleInTenant: vi.fn(async () => null),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(() => mocks.postDetails.tenantTypes.promise) }));
|
||||
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({
|
||||
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
|
||||
getPlanFeatureUsage: vi.fn(() => mocks.postDetails.credits.promise),
|
||||
}));
|
||||
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
|
||||
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({
|
||||
resolveTenantProductAccess: vi.fn(() => mocks.postDetails.productAccess.promise),
|
||||
resolveTenantProductAccessBatch: vi.fn(() => mocks.postDetails.productAccess.promise),
|
||||
}));
|
||||
|
||||
import { getTenantUserType } from "~/utils/db/tenants.db.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { adminGetAllActiveTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
|
||||
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
|
||||
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { loadAppData } from "./appData";
|
||||
|
||||
async function flushAsyncWork() {
|
||||
@@ -75,19 +78,20 @@ describe("loadAppData performance", () => {
|
||||
await flushAsyncWork();
|
||||
|
||||
expect(getTenantUserType).toHaveBeenCalledWith("user_1", "tenant_1");
|
||||
expect(getAllTenantTypes).toHaveBeenCalled();
|
||||
expect(getPlanFeatureUsage).toHaveBeenCalledWith("tenant_1", "ai-credits");
|
||||
expect(resolveTenantProductAccess).toHaveBeenCalled();
|
||||
expect(resolveTenantProductAccessBatch).toHaveBeenCalledTimes(1);
|
||||
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
|
||||
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
|
||||
|
||||
mocks.postDetails.tenantUser.resolve({ type: TenantUserType.MEMBER });
|
||||
mocks.postDetails.tenantTypes.resolve([]);
|
||||
mocks.postDetails.credits.resolve(undefined);
|
||||
mocks.postDetails.productAccess.resolve({ allowed: true });
|
||||
mocks.postDetails.productAccess.resolve([["dashboard", { allowed: true }]]);
|
||||
|
||||
await expect(result).resolves.toMatchObject({
|
||||
currentRole: TenantUserType.MEMBER,
|
||||
tenantTypes: [],
|
||||
isSuperAdmin: false,
|
||||
productAccess: expect.any(Object),
|
||||
});
|
||||
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
|
||||
});
|
||||
});
|
||||
+2
-1
@@ -15,9 +15,10 @@ vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn()
|
||||
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getPermissionsByUser: vi.fn(),
|
||||
getUserRoleInAdmin: vi.fn(),
|
||||
getUserRoleInAdmin: vi.fn(async () => null),
|
||||
getUserRoleInTenant: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
|
||||
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
|
||||
vi.mock("~/utils/services/.server/subscriptionService", () => ({ getActiveTenantSubscriptions: vi.fn(), getPlanFeatureUsage: vi.fn() }));
|
||||
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn() } }));
|
||||
|
||||
+11
@@ -9,4 +9,15 @@ describe("loadAppData tenant role lookup", () => {
|
||||
expect(source).toContain("getTenantUserType(userInfo.userId, tenantId)");
|
||||
expect(source).not.toContain("getTenantUserType(tenantId, userInfo.userId)");
|
||||
});
|
||||
|
||||
test("builds the shell billing banner from normalized subscription data", () => {
|
||||
const source = readRepoFile("apps/web/app/utils/data/.server/appData.ts");
|
||||
|
||||
expect(source).toContain("billingBanner = buildSubscriptionBannerVM({");
|
||||
expect(source).toContain("status: normalizeBillingSubscriptionStatus(mySubscription?.status");
|
||||
expect(source).toContain("frozenAt: mySubscription?.frozenAt");
|
||||
expect(source).toContain("cancelledAt: mySubscription?.cancelledAt");
|
||||
expect(source).toContain("trialEndsAt: mySubscription?.trialEndsAt");
|
||||
expect(source).toContain("billingBanner,");
|
||||
});
|
||||
});
|
||||
+46
-25
@@ -9,12 +9,14 @@ import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { normalizeBillingSubscriptionStatus } from "@hivegrid/db/billing-domain.server";
|
||||
import { buildSubscriptionBannerVM } from "@hivegrid/view-models";
|
||||
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
|
||||
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getPermissionsByUser, getUserRoleInTenant, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getUserEffectiveSeatType } from "~/utils/db/permissions/seatType.db.server";
|
||||
import { adminGetAllActiveTenantSimple, getTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
|
||||
import { getAuthUserWithoutPasswordById as getUser, getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
|
||||
@@ -25,7 +27,7 @@ import { CreditTypes } from "~/modules/usage/dtos/CreditType";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import { TFunction } from "i18next";
|
||||
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
|
||||
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
|
||||
import { WALKING_SKELETON_MODULE_KEY } from "~/modules/walkingSkeleton/constants";
|
||||
|
||||
// Every feature key the AppSidebar gates on via hasFeatureAccess() MUST be
|
||||
@@ -43,8 +45,11 @@ const tenantNavigationFeatureKeys = [
|
||||
featureKeys.tasks,
|
||||
featureKeys.hr,
|
||||
featureKeys.integrations,
|
||||
featureKeys.telephony,
|
||||
featureKeys.chat,
|
||||
featureKeys.booking,
|
||||
featureKeys.forms,
|
||||
featureKeys.billing,
|
||||
featureKeys.search,
|
||||
featureKeys.automation,
|
||||
featureKeys.emailMarketing,
|
||||
@@ -52,6 +57,8 @@ const tenantNavigationFeatureKeys = [
|
||||
featureKeys.api,
|
||||
featureKeys.workflowEngine,
|
||||
featureKeys.credits,
|
||||
// Not a sidebar entry: gates the topbar "Mit KI verbinden" launcher (VD-MCP).
|
||||
featureKeys.mcp,
|
||||
] as const satisfies readonly FeatureKey[];
|
||||
|
||||
// R-P1c: Konnektor-Demo-Modul (kein Entitlement-FeatureKey) — speist das Sidebar-Gate der
|
||||
@@ -86,13 +93,25 @@ export async function loadAppData({
|
||||
);
|
||||
|
||||
const url = new URL(request.url);
|
||||
const { user, currentTenant } = await time(
|
||||
const operatorAdminPromise: Promise<boolean> =
|
||||
preloadedIsOperatorAdmin !== undefined
|
||||
? Promise.resolve(preloadedIsOperatorAdmin)
|
||||
: userInfo?.userId
|
||||
? getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin).then((role) => Boolean(role))
|
||||
: Promise.resolve(false);
|
||||
const {
|
||||
user,
|
||||
currentTenant,
|
||||
operatorAdmin: operatorAdminValue,
|
||||
} = await time(
|
||||
promiseHash({
|
||||
user: preloadedUser ? Promise.resolve(preloadedUser) : getUser(userInfo?.userId),
|
||||
currentTenant: getTenantSimple(tenantId),
|
||||
operatorAdmin: operatorAdminPromise,
|
||||
}),
|
||||
"loadAppData.getUserAndTenant"
|
||||
);
|
||||
const operatorAdmin = operatorAdminValue === true;
|
||||
|
||||
const redirectTo = url.pathname + url.search;
|
||||
if (!userInfo || !user) {
|
||||
@@ -111,52 +130,53 @@ export async function loadAppData({
|
||||
if (UrlUtils.stripTrailingSlash(url.pathname) === UrlUtils.stripTrailingSlash(appPath({ tenantSlug: tenantPathSegment, mode: "host-aware" }))) {
|
||||
throw redirect(`${appPath({ tenantSlug: currentTenant.slug, path: "dashboard", mode: "host-aware" })}${url.search}`);
|
||||
}
|
||||
const operatorAdmin = Boolean(user.admin) || Boolean(preloadedIsOperatorAdmin);
|
||||
let { myTenants, mySubscription, allPermissions, superUserRole, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
|
||||
let { myTenants, mySubscription, allPermissions, superUserRole, allRoles, myGroups, onboardingSession, effectiveSeatType } = await time(
|
||||
promiseHash({
|
||||
myTenants: time(operatorAdmin ? adminGetAllActiveTenantSimple() : getMyTenants(user.id), "loadAppData.getDetails.getMyTenants"),
|
||||
mySubscription: time(getActiveTenantSubscriptions(tenantId), "loadAppData.getDetails.getActiveTenantSubscriptions"),
|
||||
allPermissions: time(getPermissionsByUser(userInfo.userId, tenantId), "loadAppData.getDetails.getPermissionsByUser"),
|
||||
superUserRole: time(getUserRoleInTenant(userInfo.userId, tenantId, DefaultAppRoles.SuperUser), "loadAppData.getDetails.getUserRoleInTenant"),
|
||||
superAdminRole: time(getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin), "loadAppData.getDetails.getUserRoleInAdmin"),
|
||||
allRoles: time(getAllRolesWithoutPermissions("app"), "loadAppData.getDetails.getAllRolesWithoutPermissions"),
|
||||
myGroups: time(getMyGroups(user.id, currentTenant.id), "loadAppData.getDetails.getMyGroups"),
|
||||
onboardingSession: time(
|
||||
OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: currentTenant.id, request }),
|
||||
"loadAppData.getDetails.OnboardingService.getUserActiveOnboarding"
|
||||
),
|
||||
effectiveSeatType: time(getUserEffectiveSeatType(userInfo.userId, tenantId), "loadAppData.getDetails.getUserEffectiveSeatType"),
|
||||
}),
|
||||
"loadAppData.getDetails"
|
||||
);
|
||||
|
||||
const { tenantUser, tenantTypes, credits, productAccessEntries } = await time(
|
||||
const { tenantUser, credits, productAccessEntries } = await time(
|
||||
promiseHash({
|
||||
tenantUser: time(getTenantUserType(userInfo.userId, tenantId), "loadAppData.postDetails.getTenantUserType"),
|
||||
tenantTypes: time(getAllTenantTypes(), "loadAppData.postDetails.getAllTenantTypes"),
|
||||
credits:
|
||||
CreditTypes.length > 0
|
||||
? time(getPlanFeatureUsage(tenantId, DefaultFeatures.Credits), "loadAppData.postDetails.getPlanFeatureUsage")
|
||||
: Promise.resolve(undefined as PlanFeatureUsageDto | undefined),
|
||||
productAccessEntries: time(
|
||||
Promise.all(
|
||||
[...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys].map(async (featureKey) => [
|
||||
featureKey,
|
||||
await resolveTenantProductAccess({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
featureKey,
|
||||
subscription: mySubscription,
|
||||
tenantRolePermissionNames: allPermissions,
|
||||
bypassTenantRolePermission: operatorAdmin || !!superAdminRole,
|
||||
}),
|
||||
] as const)
|
||||
),
|
||||
"loadAppData.postDetails.resolveTenantProductAccess"
|
||||
resolveTenantProductAccessBatch({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
featureKeys: [...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys],
|
||||
subscription: mySubscription,
|
||||
tenantRolePermissionNames: allPermissions,
|
||||
bypassTenantRolePermission: operatorAdmin,
|
||||
}),
|
||||
"loadAppData.postDetails.resolveTenantProductAccessBatch"
|
||||
),
|
||||
}),
|
||||
"loadAppData.postDetails"
|
||||
);
|
||||
const currentRole = operatorAdmin ? TenantUserType.ADMIN : tenantUser?.type ?? TenantUserType.MEMBER;
|
||||
const currentRole = operatorAdmin ? TenantUserType.ADMIN : (tenantUser?.type ?? TenantUserType.MEMBER);
|
||||
const billingBanner = buildSubscriptionBannerVM({
|
||||
status: normalizeBillingSubscriptionStatus(mySubscription?.status, {
|
||||
frozenAt: mySubscription?.frozenAt,
|
||||
cancelledAt: mySubscription?.cancelledAt,
|
||||
}),
|
||||
hasSubscription: mySubscription !== null,
|
||||
trialEndsAt: mySubscription?.trialEndsAt,
|
||||
});
|
||||
const data: AppLoaderData = {
|
||||
// i18n: i18n.translations,
|
||||
user,
|
||||
@@ -164,17 +184,18 @@ export async function loadAppData({
|
||||
currentTenant,
|
||||
currentRole,
|
||||
mySubscription,
|
||||
billingBanner,
|
||||
// roles,
|
||||
allRoles,
|
||||
permissions: allPermissions.map((f) => f as DefaultPermission),
|
||||
myGroups,
|
||||
isSuperUser: !!superUserRole,
|
||||
isSuperAdmin: !!superAdminRole,
|
||||
isSuperAdmin: operatorAdmin,
|
||||
lng: user?.locale ?? userInfo.lng,
|
||||
onboardingSession,
|
||||
tenantTypes,
|
||||
credits,
|
||||
productAccess: Object.fromEntries(productAccessEntries),
|
||||
effectiveSeatType,
|
||||
};
|
||||
return data;
|
||||
}
|
||||
+95
-30
@@ -4,7 +4,8 @@ import { Params } from "react-router";
|
||||
import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto";
|
||||
import { ImpersonatingSessionDto } from "~/application/dtos/session/ImpersonatingSessionDto";
|
||||
import { CookieCategory } from "~/application/cookies/CookieCategory";
|
||||
import { remixI18Next, i18nCookie } from "~/locale/i18next.server";
|
||||
import { enabledLocales, remixI18Next, i18nCookie } from "~/locale/i18next.server";
|
||||
import { resolveEnabledLocale } from "~/locale/i18n";
|
||||
import { resolveAnrede } from "~/locale/anrede.server";
|
||||
import { getCurrentEnabledFlagNames } from "~/utils/services/.server/featureFlagsRequest.server";
|
||||
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
|
||||
@@ -13,12 +14,20 @@ import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
|
||||
import AnalyticsService from "~/utils/helpers/.server/AnalyticsService";
|
||||
import CookieHelper from "~/utils/helpers/CookieHelper";
|
||||
import { promiseHash } from "~/utils/promises/promiseHash";
|
||||
import { getUserInfo, getUserSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
|
||||
import { getUserInfo, getUserSession, getValidatedServerSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
|
||||
import { getAbsoluteApiUrl, getAbsoluteUrl, getBaseURL, getDomainName } from "~/utils/url.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { AppRootData } from "../useRootData";
|
||||
import { CSP_NONCE_REQUEST_HEADER, buildDocumentContentSecurityPolicy, getRequestCspNonce } from "~/utils/security/contentSecurityPolicy";
|
||||
import { getRequestDocumentContentSecurityPolicyOptions } from "~/utils/security/requestContentSecurityPolicy.server";
|
||||
|
||||
const rootDataLogger = createScopedLogger("root-data");
|
||||
const browserBuildEnv = ((import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}) as Record<string, string | undefined>;
|
||||
|
||||
export async function loadRootData({ request, params }: { request: Request; params: Params }) {
|
||||
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "root");
|
||||
const appConfigurationPromise = time(getAppConfiguration({ request }), "getAppConfiguration");
|
||||
const localePromise = remixI18Next.getLocale(request);
|
||||
const { userInfo, session, analyticsSession } = await time(
|
||||
promiseHash({
|
||||
userInfo: getUserInfo(request),
|
||||
@@ -27,27 +36,91 @@ export async function loadRootData({ request, params }: { request: Request; para
|
||||
}),
|
||||
"loadRootData.session"
|
||||
);
|
||||
const user = userInfo.userId ? await getUser(userInfo.userId) : null;
|
||||
const currentTenant = params.tenant ? await getTenantByIdOrSlug(params.tenant) : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
|
||||
const [validatedSession, routeTenant] = await Promise.all([
|
||||
userInfo.userId && !userInfo.impersonatingFromUserId ? getValidatedServerSession(request, userInfo) : Promise.resolve(null),
|
||||
params.tenant ? getTenantByIdOrSlug(params.tenant) : Promise.resolve(null),
|
||||
]);
|
||||
const user =
|
||||
validatedSession && "user" in validatedSession
|
||||
? validatedSession.user
|
||||
: validatedSession && "adminUser" in validatedSession
|
||||
? {
|
||||
id: validatedSession.adminUser.id,
|
||||
email: validatedSession.adminUser.email,
|
||||
firstName: validatedSession.adminUser.firstName,
|
||||
lastName: validatedSession.adminUser.lastName,
|
||||
avatar: validatedSession.adminUser.avatar,
|
||||
phone: null,
|
||||
admin: { userId: validatedSession.adminUser.id },
|
||||
defaultTenantId: null,
|
||||
createdAt: validatedSession.createdAt,
|
||||
locale: validatedSession.adminUser.locale,
|
||||
lightOrDarkMode: null,
|
||||
}
|
||||
: userInfo.userId
|
||||
? await getUser(userInfo.userId)
|
||||
: null;
|
||||
const currentTenant = params.tenant ? routeTenant : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
|
||||
|
||||
const existingCsrf = session.get("csrf");
|
||||
const csrf = typeof existingCsrf === "string" && existingCsrf.length > 0 ? existingCsrf : setCSRFToken(session);
|
||||
|
||||
let analytics: AnalyticsInfoDto | undefined = undefined;
|
||||
const appConfiguration = await time(getAppConfiguration({ request }), "getAppConfiguration");
|
||||
const [appConfiguration, detectedLocale] = await Promise.all([appConfigurationPromise, localePromise]);
|
||||
const locale = resolveEnabledLocale({
|
||||
enabledLocales,
|
||||
userLocale: user?.locale,
|
||||
cookieLocale: detectedLocale,
|
||||
acceptLanguage: request.headers.get("Accept-Language"),
|
||||
});
|
||||
const hasAnalyticsConsent = CookieHelper.hasConsent(userInfo, CookieCategory.ANALYTICS);
|
||||
if (appConfiguration.analytics.enabled && hasAnalyticsConsent) {
|
||||
try {
|
||||
analytics = await AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null });
|
||||
} catch (e: any) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(e.message);
|
||||
}
|
||||
}
|
||||
const analyticsPromise: Promise<AnalyticsInfoDto | undefined> =
|
||||
appConfiguration.analytics.enabled && hasAnalyticsConsent
|
||||
? AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null }).catch((error: unknown) => {
|
||||
rootDataLogger.warn({ err: { name: error instanceof Error ? error.name : "Error" } }, "analytics request enrichment failed");
|
||||
return undefined;
|
||||
})
|
||||
: Promise.resolve(undefined);
|
||||
|
||||
const impersonatingSessionPromise: Promise<ImpersonatingSessionDto | null> =
|
||||
userInfo.impersonatingFromAdminUserId && userInfo.impersonatingFromAdminEmail && userInfo.userId?.length > 0
|
||||
? getUser(userInfo.userId).then((toUser) =>
|
||||
toUser
|
||||
? {
|
||||
fromUser: { id: userInfo.impersonatingFromAdminUserId!, email: userInfo.impersonatingFromAdminEmail! },
|
||||
toUser: { id: toUser.id, email: toUser.email },
|
||||
}
|
||||
: null
|
||||
)
|
||||
: userInfo.impersonatingFromUserId && userInfo.userId?.length > 0
|
||||
? Promise.all([getUser(userInfo.impersonatingFromUserId), getUser(userInfo.userId)]).then(([fromUser, toUser]) =>
|
||||
fromUser && toUser ? { fromUser, toUser } : null
|
||||
)
|
||||
: Promise.resolve(null);
|
||||
const anredePromise = resolveAnrede(request, currentTenant);
|
||||
const featureFlagsPromise = appConfiguration.featureFlags.enabled ? getCurrentEnabledFlagNames({ request, params }) : Promise.resolve([] as string[]);
|
||||
const sessionCookiePromise = commitSession(session);
|
||||
|
||||
const [resolvedAnalytics, impersonatingSession, anrede, featureFlags, sessionCookie] = await Promise.all([
|
||||
analyticsPromise,
|
||||
impersonatingSessionPromise,
|
||||
anredePromise,
|
||||
featureFlagsPromise,
|
||||
sessionCookiePromise,
|
||||
]);
|
||||
let analytics = resolvedAnalytics;
|
||||
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
const headers = new Headers();
|
||||
const cspNonce = getRequestCspNonce(request);
|
||||
if (cspNonce) {
|
||||
headers.set(CSP_NONCE_REQUEST_HEADER, cspNonce);
|
||||
headers.set(
|
||||
"Content-Security-Policy",
|
||||
buildDocumentContentSecurityPolicy(cspNonce, undefined, getRequestDocumentContentSecurityPolicyOptions(request, webConfig, process.env, browserBuildEnv))
|
||||
);
|
||||
}
|
||||
let userAnalyticsId = analyticsSession.get("userAnalyticsId");
|
||||
headers.append("Set-Cookie", await commitSession(session));
|
||||
headers.append("Set-Cookie", sessionCookie);
|
||||
if (hasAnalyticsConsent) {
|
||||
if (!userAnalyticsId) {
|
||||
userAnalyticsId = generateAnalyticsUserId();
|
||||
@@ -62,27 +135,16 @@ export async function loadRootData({ request, params }: { request: Request; para
|
||||
headers.append("Set-Cookie", await destroyAnalyticsSession(analyticsSession));
|
||||
}
|
||||
|
||||
let impersonatingSession: ImpersonatingSessionDto | null = null;
|
||||
if (userInfo.impersonatingFromUserId && userInfo.userId?.length > 0) {
|
||||
const fromUser = await getUser(userInfo.impersonatingFromUserId);
|
||||
const toUser = await getUser(userInfo.userId);
|
||||
if (fromUser && toUser) {
|
||||
impersonatingSession = { fromUser, toUser };
|
||||
}
|
||||
}
|
||||
|
||||
const locale = await remixI18Next.getLocale(request);
|
||||
// Formality axis (du/Sie). Default "du" → `effectiveLng(locale, "du") === locale`,
|
||||
// so the language handed to `useChangeLanguage` in root.tsx is unchanged and
|
||||
// rendering stays byte-identical. The tenant's persisted default applies when
|
||||
// no explicit cookie/param is present.
|
||||
const anrede = await resolveAnrede(request, currentTenant);
|
||||
const webConfig = loadRequiredWebConfig();
|
||||
const data: AppRootData = {
|
||||
metatags: [{ title: webConfig.appName }],
|
||||
user,
|
||||
currentTenant,
|
||||
locale,
|
||||
enabledLocales,
|
||||
anrede,
|
||||
theme: userInfo.theme || appConfiguration.app.theme,
|
||||
serverUrl: getBaseURL(request),
|
||||
@@ -90,7 +152,7 @@ export async function loadRootData({ request, params }: { request: Request; para
|
||||
apiBaseUrl: getAbsoluteApiUrl(request, "/"),
|
||||
routing: webConfig.routing,
|
||||
domainName: getDomainName(request),
|
||||
userSession: userInfo,
|
||||
userSession: { ...userInfo, lng: locale },
|
||||
authenticated: userInfo.userId?.length > 0,
|
||||
debug: webConfig.nodeEnv === "development",
|
||||
chatWebsiteId: webConfig.crisp.chatWebsiteId,
|
||||
@@ -98,7 +160,9 @@ export async function loadRootData({ request, params }: { request: Request; para
|
||||
csrf,
|
||||
analytics,
|
||||
analyticsToken: appConfiguration.analytics.enabled && hasAnalyticsConsent ? webConfig.analytics.token : undefined,
|
||||
featureFlags: appConfiguration.featureFlags.enabled ? await getCurrentEnabledFlagNames({ request, params }) : [],
|
||||
webPushVapidPublicKey: webConfig.webPush.vapidPublicKey,
|
||||
cspNonce,
|
||||
featureFlags,
|
||||
impersonatingSession,
|
||||
};
|
||||
|
||||
@@ -110,7 +174,8 @@ export async function loadRootData({ request, params }: { request: Request; para
|
||||
...userInfo,
|
||||
metrics: appConfiguration.metrics,
|
||||
},
|
||||
new URL(request.url).pathname + new URL(request.url).search
|
||||
new URL(request.url).pathname + new URL(request.url).search,
|
||||
{ request }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { useMatches } from "react-router";
|
||||
import type { SeatType } from "@hivegrid/db/prisma-browser";
|
||||
import type { SubscriptionBannerVM } from "@hivegrid/view-models";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
import { TenantSimple } from "../db/tenants.db.server";
|
||||
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
|
||||
@@ -7,7 +9,16 @@ import { AppOrAdminData } from "./useAppOrAdminData";
|
||||
export type AppLoaderData = AppOrAdminData & {
|
||||
currentTenant: TenantSimple;
|
||||
mySubscription: TenantSubscriptionWithDetails | null;
|
||||
/**
|
||||
* Root-route decision for the focused first-purchase gate. A persisted
|
||||
* signup selection keeps a new tenant locked even where subscriptions are
|
||||
* not globally required (for example staging demo environments).
|
||||
*/
|
||||
subscriptionActivationRequired?: boolean;
|
||||
billingBanner: SubscriptionBannerVM;
|
||||
currentRole: TenantUserType;
|
||||
/** Effective seat type of the current user in this tenant (office vs field, Fundament C). */
|
||||
effectiveSeatType: SeatType;
|
||||
};
|
||||
|
||||
export function useAppData(): AppLoaderData {
|
||||
|
||||
@@ -6,7 +6,6 @@ import { AdminLoaderData } from "./useAdminData";
|
||||
import { GroupWithDetails } from "../db/permissions/groups.db.server";
|
||||
import { OnboardingSessionWithDetails } from "~/modules/onboarding/db/onboardingSessions.db.server";
|
||||
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import { TenantTypeWithDetails } from "../db/tenants/tenantTypes.db.server";
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import type { ProductAccessDecision } from "@hivegrid/entitlements";
|
||||
|
||||
@@ -23,7 +22,6 @@ export type AppOrAdminData = {
|
||||
myGroups: GroupWithDetails[];
|
||||
lng?: string;
|
||||
onboardingSession: OnboardingSessionWithDetails | null;
|
||||
tenantTypes: TenantTypeWithDetails[];
|
||||
credits?: PlanFeatureUsageDto | undefined;
|
||||
productAccess?: Record<string, ProductAccessDecision>;
|
||||
};
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ export function useDashboardData(): DashboardLoaderData {
|
||||
return (useMatches().find((f) => f.id === "routes/app.$tenant/dashboard")?.data ?? {}) as DashboardLoaderData;
|
||||
}
|
||||
|
||||
export async function loadDashboardData({ request, params }: { request: Request; params: Params }): Promise<DashboardLoaderData> {
|
||||
export async function loadDashboardData({ request: _request, params }: { request: Request; params: Params }): Promise<DashboardLoaderData> {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
const data: DashboardLoaderData = {
|
||||
users: await getTenantUsersCount(tenantId),
|
||||
|
||||
@@ -8,5 +8,5 @@ export type MembersLoaderData = {
|
||||
};
|
||||
|
||||
export function useMembersData(params: Params): MembersLoaderData {
|
||||
return (useMatches().find((f) => f.pathname === UrlUtils.currentTenantUrl(params, "settings/members"))?.data ?? {}) as MembersLoaderData;
|
||||
return (useMatches().find((f) => f.pathname === UrlUtils.currentTenantUrl(params, "settings/team"))?.data ?? {}) as MembersLoaderData;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto"
|
||||
import { UserWithoutPassword } from "../db/users.db.server";
|
||||
import { TenantSimple } from "../db/tenants.db.server";
|
||||
import type { PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
|
||||
import type { Anrede } from "@hivegrid/i18n";
|
||||
import type { Anrede, SupportedLocale } from "@hivegrid/i18n";
|
||||
|
||||
export type AppRootData = {
|
||||
metatags: MetaTagsDto;
|
||||
@@ -15,6 +15,7 @@ export type AppRootData = {
|
||||
currentTenant: TenantSimple | null;
|
||||
theme: string;
|
||||
locale: string;
|
||||
enabledLocales: readonly SupportedLocale[];
|
||||
anrede: Anrede;
|
||||
serverUrl: string;
|
||||
publicBaseUrl: string;
|
||||
@@ -29,6 +30,8 @@ export type AppRootData = {
|
||||
csrf?: string;
|
||||
analytics?: AnalyticsInfoDto;
|
||||
analyticsToken?: string;
|
||||
webPushVapidPublicKey?: string;
|
||||
cspNonce?: string;
|
||||
featureFlags: string[];
|
||||
impersonatingSession: ImpersonatingSessionDto | null;
|
||||
};
|
||||
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// Breadcrumb helper unit test — the parent-nav-crumb rule that decides whether
|
||||
// the responsible sidebar entry is prefixed to the loader-derived trail.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { shouldShowParentNavCrumb, type BreadcrumbTrailEntry } from "./useTitleData";
|
||||
|
||||
const CONTACTS_TRAIL: BreadcrumbTrailEntry[] = [
|
||||
{ label: "Kontakte", href: "/app/acme/contacts" },
|
||||
{ label: "Tags", href: "/app/acme/contacts/admin/tags" },
|
||||
];
|
||||
|
||||
describe("shouldShowParentNavCrumb", () => {
|
||||
it("drops a nav crumb whose target the trail already points at under a different name", () => {
|
||||
// The CRM sidebar entry links to the contact list; the trail names that very
|
||||
// page "Kontakte". A "CRM" crumb would be a second crumb for one route.
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/contacts",
|
||||
navTitle: "CRM",
|
||||
currentPathname: "/app/acme/contacts/admin/tags",
|
||||
currentCrumbLabel: "Tags",
|
||||
trail: CONTACTS_TRAIL,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("ignores a trailing slash when comparing the nav target with the trail", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/contacts/",
|
||||
navTitle: "CRM",
|
||||
currentPathname: "/app/acme/contacts/admin/tags",
|
||||
currentCrumbLabel: "Tags",
|
||||
trail: CONTACTS_TRAIL,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("drops a nav crumb that the trail already carries under the same label", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/other",
|
||||
navTitle: "Kontakte",
|
||||
currentPathname: "/app/acme/contacts/admin/tags",
|
||||
currentCrumbLabel: "Tags",
|
||||
trail: CONTACTS_TRAIL,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("drops the nav crumb when it is the current page", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/contacts",
|
||||
navTitle: "CRM",
|
||||
currentPathname: "/app/acme/contacts/",
|
||||
currentCrumbLabel: "Kontakte",
|
||||
trail: [{ label: "Kontakte", href: "/app/acme/contacts" }],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a nav crumb that names a section the trail does not cover", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/bookings/pages",
|
||||
navTitle: "Buchungsseiten",
|
||||
currentPathname: "/app/acme/bookings/pages/p1/edit",
|
||||
currentCrumbLabel: "Editor",
|
||||
trail: [{ label: "Editor", href: "/app/acme/bookings/pages/p1/edit" }],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("drops the nav crumb when the current page has its own row in the inner sub-sidenav", () => {
|
||||
// /leads-statistics is a sibling entry under the Leads area. The rail
|
||||
// already shows that context, so a "Leads" crumb would invent a level.
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/leads",
|
||||
navTitle: "Leads",
|
||||
currentPathname: "/app/acme/leads-statistics",
|
||||
currentCrumbLabel: "Lead-Statistiken",
|
||||
trail: [{ label: "Lead-Statistiken", href: "/app/acme/leads-statistics" }],
|
||||
navContextPaths: ["/app/acme/leads", "/app/acme/leads-statistics"],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the nav crumb for a sub-page that has no row of its own in the rail", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/leads",
|
||||
navTitle: "Leads",
|
||||
currentPathname: "/app/acme/leads/l1",
|
||||
currentCrumbLabel: "Karin Lehmann",
|
||||
trail: [{ label: "Karin Lehmann", href: "/app/acme/leads/l1" }],
|
||||
navContextPaths: ["/app/acme/leads", "/app/acme/leads-statistics"],
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("drops the nav crumb when the trail already links to a row of the inner sub-sidenav", () => {
|
||||
// Booking detail below the "Buchungen" row of the Termine rail: the trail
|
||||
// names that row itself, so the area crumb would add a third level for a
|
||||
// path the user walked in two steps.
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "/app/acme/calendar",
|
||||
navTitle: "Termine",
|
||||
currentPathname: "/app/acme/bookings/b1",
|
||||
currentCrumbLabel: "Buchung",
|
||||
trail: [
|
||||
{ label: "Buchungen", href: "/app/acme/bookings" },
|
||||
{ label: "Buchung", href: "/app/acme/bookings/b1" },
|
||||
],
|
||||
navContextPaths: ["/app/acme/calendar", "/app/acme/bookings", "/app/acme/availability"],
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("drops the nav crumb when the entry has no path to link to", () => {
|
||||
expect(
|
||||
shouldShowParentNavCrumb({
|
||||
navPath: "",
|
||||
navTitle: "CRM",
|
||||
currentPathname: "/app/acme/contacts/admin/tags",
|
||||
currentCrumbLabel: "Tags",
|
||||
trail: CONTACTS_TRAIL,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import { useMatches } from "react-router";
|
||||
|
||||
function cleanTitle(raw: unknown): string {
|
||||
return typeof raw === "string" ? (raw.split("|")[0]?.trim() ?? "") : "";
|
||||
}
|
||||
|
||||
export function useTitleData(): string {
|
||||
try {
|
||||
const titles = useMatches()
|
||||
@@ -9,8 +13,98 @@ export function useTitleData(): string {
|
||||
if (!titles || titles.length === 0) {
|
||||
return "";
|
||||
}
|
||||
return titles[titles.length - 1].split("|")[0].trim() ?? "";
|
||||
return cleanTitle(titles[titles.length - 1]);
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export type BreadcrumbTrailEntry = { label: string; href: string };
|
||||
|
||||
function normalizeCrumbPath(path: string): string {
|
||||
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Should the responsible sidebar entry be rendered as an extra parent crumb in
|
||||
* front of the loader-derived trail?
|
||||
*
|
||||
* No, if it is the current page, or if the trail already covers it — either by
|
||||
* label or by target path. The path check matters because a nav entry may carry
|
||||
* a section name ("CRM") while the trail names the page it links to
|
||||
* ("Kontakte"): rendering both yields two crumbs for one route, and the section
|
||||
* crumb then looks like a level that does not exist.
|
||||
*
|
||||
* Also no, when the current page is itself one of the entry's `contextItems` —
|
||||
* i.e. it has its own row in the inner sub-sidenav. That rail already shows
|
||||
* which area the page belongs to, so repeating the area as a crumb adds a level
|
||||
* the user never navigated through (e.g. "Leads > Lead-Statistiken", where
|
||||
* "Leads" just leads back to a sibling of the current page).
|
||||
*
|
||||
* And no, when the trail itself already links to one of those `contextItems`.
|
||||
* A sub-page below such a row is reached through the row, not through the nav
|
||||
* entry, so the trail already names the path the user took — the nav crumb only
|
||||
* adds the rail's own area on top ("Termine > Buchungen > Buchung" for what is
|
||||
* really "Buchungen > Buchung").
|
||||
*/
|
||||
export function shouldShowParentNavCrumb(args: {
|
||||
navPath: string | null | undefined;
|
||||
navTitle: string;
|
||||
currentPathname: string;
|
||||
currentCrumbLabel: string;
|
||||
trail: readonly BreadcrumbTrailEntry[];
|
||||
navContextPaths?: readonly (string | undefined)[];
|
||||
}): boolean {
|
||||
if (!args.navPath) return false;
|
||||
const navPath = normalizeCrumbPath(args.navPath);
|
||||
const currentPath = normalizeCrumbPath(args.currentPathname);
|
||||
if (navPath === currentPath) return false;
|
||||
const contextPaths = (args.navContextPaths ?? []).filter((path): path is string => Boolean(path)).map(normalizeCrumbPath);
|
||||
if (contextPaths.includes(currentPath)) return false;
|
||||
if (args.trail.some((crumb) => contextPaths.includes(normalizeCrumbPath(crumb.href ?? "")))) return false;
|
||||
if (args.navTitle === args.currentCrumbLabel) return false;
|
||||
return !args.trail.some((crumb) => crumb.label === args.navTitle || normalizeCrumbPath(crumb.href ?? "") === navPath);
|
||||
}
|
||||
|
||||
function pushCrumb(trail: BreadcrumbTrailEntry[], entry: BreadcrumbTrailEntry): void {
|
||||
if (!entry.label) return;
|
||||
// Collapse consecutive duplicates (layout + index route often share a title,
|
||||
// and an ancestor may repeat the parent it points at).
|
||||
if (trail.length > 0 && trail[trail.length - 1].label === entry.label) {
|
||||
trail[trail.length - 1] = entry;
|
||||
return;
|
||||
}
|
||||
trail.push(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadcrumb trail derived from route matches that expose a loader `title`
|
||||
* (or `meta.title`). Each entry links to its match's pathname, so sub-pages
|
||||
* get a clickable path back to their parent page.
|
||||
*
|
||||
* A match may also expose `breadcrumbAncestors: { label, href }[]` in its
|
||||
* loader data — extra crumbs inserted before the match's own crumb. Sub-areas
|
||||
* without their own sidebar entry (e.g. the booking-page editor under
|
||||
* /bookings/pages) use this to name the list page they were reached through,
|
||||
* since the flat route convention gives them no shared layout to hang a crumb on.
|
||||
*/
|
||||
export function useBreadcrumbTrail(): BreadcrumbTrailEntry[] {
|
||||
try {
|
||||
const trail: BreadcrumbTrailEntry[] = [];
|
||||
for (const match of useMatches()) {
|
||||
const data = match.data as any;
|
||||
const ancestors = Array.isArray(data?.breadcrumbAncestors) ? (data.breadcrumbAncestors as BreadcrumbTrailEntry[]) : [];
|
||||
for (const ancestor of ancestors) {
|
||||
if (typeof ancestor?.label === "string" && typeof ancestor?.href === "string") {
|
||||
pushCrumb(trail, { label: ancestor.label, href: ancestor.href });
|
||||
}
|
||||
}
|
||||
const label = cleanTitle(data?.title ?? data?.meta?.title);
|
||||
if (!label) continue;
|
||||
pushCrumb(trail, { label, href: match.pathname });
|
||||
}
|
||||
return trail;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user