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

@@ -0,0 +1,115 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`tenant settings route manifest > pins every settings URL to its route file 1`] = `
[
"/:tenant/settings -> routes/app.$tenant/settings.tsx",
"/:tenant/settings/account -> routes/app.$tenant/settings/account.tsx",
"/:tenant/settings/api -> routes/app.$tenant/settings/api/index.tsx",
"/:tenant/settings/api/keys -> routes/app.$tenant/settings/api/keys.tsx",
"/:tenant/settings/api/keys/:id -> routes/app.$tenant/settings/api/keys/$id.tsx",
"/:tenant/settings/api/keys/new -> routes/app.$tenant/settings/api/keys/new.tsx",
"/:tenant/settings/api/logs -> routes/app.$tenant/settings/api/logs.tsx",
"/:tenant/settings/audit-export -> routes/app.$tenant/settings/audit-export.tsx",
"/:tenant/settings/billing -> routes/app.$tenant/settings/billing.tsx",
"/:tenant/settings/billing (index) -> routes/app.$tenant/settings/billing/index.tsx",
"/:tenant/settings/billing/invoices -> routes/app.$tenant/settings/billing/invoices.tsx",
"/:tenant/settings/billing/usage -> routes/app.$tenant/settings/billing/usage.tsx",
"/:tenant/settings/chat/audit -> routes/app.$tenant/settings/chat/audit.tsx",
"/:tenant/settings/chat/audit/:id -> routes/app.$tenant/settings/chat/audit.$id.tsx",
"/:tenant/settings/chat/audit/:id/attachments/:fileId/:variant -> routes/app.$tenant/settings/chat/audit.$id.attachments.$fileId.$variant.tsx",
"/:tenant/settings/compliance -> routes/app.$tenant/settings/compliance.tsx",
"/:tenant/settings/compliance (index) -> routes/app.$tenant/settings/compliance/index.tsx",
"/:tenant/settings/compliance/audit-export -> routes/app.$tenant/settings/compliance/audit-export.tsx",
"/:tenant/settings/compliance/avv -> routes/app.$tenant/settings/compliance/avv.tsx",
"/:tenant/settings/compliance/chat -> routes/app.$tenant/settings/compliance/chat.tsx",
"/:tenant/settings/compliance/chat/:id -> routes/app.$tenant/settings/compliance/chat.$id.tsx",
"/:tenant/settings/compliance/data-export -> routes/app.$tenant/settings/compliance/data-export.tsx",
"/:tenant/settings/compliance/events -> routes/app.$tenant/settings/compliance/events.tsx",
"/:tenant/settings/compliance/events/:id -> routes/app.$tenant/settings/compliance/events.$id.tsx",
"/:tenant/settings/compliance/subprocessors -> routes/app.$tenant/settings/compliance/subprocessors.tsx",
"/:tenant/settings/compliance/tenant-deletion -> routes/app.$tenant/settings/compliance/tenant-deletion.tsx",
"/:tenant/settings/credits -> routes/app.$tenant/settings/credits.tsx",
"/:tenant/settings/customer-portal -> routes/app.$tenant/settings/customer-portal.tsx",
"/:tenant/settings/customer-portal (index) -> routes/app.$tenant/settings/customer-portal/index.tsx",
"/:tenant/settings/customer-portal/domain -> routes/app.$tenant/settings/customer-portal/domain.tsx",
"/:tenant/settings/customer-portal/email-templates -> routes/app.$tenant/settings/customer-portal/email-templates.tsx",
"/:tenant/settings/groups -> routes/app.$tenant/settings/groups.tsx",
"/:tenant/settings/groups/:id -> routes/app.$tenant/settings/groups/$id.tsx",
"/:tenant/settings/groups/new -> routes/app.$tenant/settings/groups/new.tsx",
"/:tenant/settings/integrations -> routes/app.$tenant/settings/integrations.tsx",
"/:tenant/settings/integrations (index) -> routes/app.$tenant/settings/integrations/_index.tsx",
"/:tenant/settings/integrations/:app -> routes/app.$tenant/settings/integrations/$app._index.tsx",
"/:tenant/settings/integrations/:app/:connectionId/syncs -> routes/app.$tenant/settings/integrations/$app.$connectionId.syncs._index.tsx",
"/:tenant/settings/integrations/:app/:connectionId/syncs/:runId -> routes/app.$tenant/settings/integrations/$app.$connectionId.syncs.$runId.tsx",
"/:tenant/settings/integrations/api -> routes/app.$tenant/settings/integrations/api/index.tsx",
"/:tenant/settings/integrations/api/keys -> routes/app.$tenant/settings/integrations/api/keys.tsx",
"/:tenant/settings/integrations/api/keys/:id -> routes/app.$tenant/settings/integrations/api/keys/$id.tsx",
"/:tenant/settings/integrations/api/keys/new -> routes/app.$tenant/settings/integrations/api/keys/new.tsx",
"/:tenant/settings/integrations/api/logs -> routes/app.$tenant/settings/integrations/api/logs.tsx",
"/:tenant/settings/integrations/calendar -> routes/app.$tenant/settings/integrations/calendar._index.tsx",
"/:tenant/settings/integrations/calendar/:id -> routes/app.$tenant/settings/integrations/calendar.$id.tsx",
"/:tenant/settings/integrations/email -> routes/app.$tenant/settings/integrations/email._index.tsx",
"/:tenant/settings/integrations/kwp/import -> routes/app.$tenant/settings/integrations/kwp/import.tsx",
"/:tenant/settings/integrations/plugins -> routes/app.$tenant/settings/integrations/plugins.tsx",
"/:tenant/settings/integrations/plugins/:id -> routes/app.$tenant/settings/integrations/plugins.$id.tsx",
"/:tenant/settings/integrations/plugins/:id/audit -> routes/app.$tenant/settings/integrations/plugins.$id.audit.tsx",
"/:tenant/settings/integrations/telephony -> routes/app.$tenant/settings/integrations/telephony.tsx",
"/:tenant/settings/logs -> routes/app.$tenant/settings/logs/index.tsx",
"/:tenant/settings/logs/events -> routes/app.$tenant/settings/logs/events.tsx",
"/:tenant/settings/logs/events-export -> routes/app.$tenant/settings/logs/events-export.ts",
"/:tenant/settings/logs/events/:id -> routes/app.$tenant/settings/logs/events.$id.tsx",
"/:tenant/settings/logs/export -> routes/app.$tenant/settings/logs/export.ts",
"/:tenant/settings/members -> routes/app.$tenant/settings/members.tsx",
"/:tenant/settings/members/edit/:id -> routes/app.$tenant/settings/members/edit.$id.tsx",
"/:tenant/settings/members/groups/:id -> routes/app.$tenant/settings/members/groups/$id.tsx",
"/:tenant/settings/members/groups/new -> routes/app.$tenant/settings/members/groups/new.tsx",
"/:tenant/settings/members/new -> routes/app.$tenant/settings/members/new.tsx",
"/:tenant/settings/notifications -> routes/app.$tenant/settings/notifications.tsx",
"/:tenant/settings/onboarding/demo-data -> routes/app.$tenant/settings/onboarding/demo-data.tsx",
"/:tenant/settings/plugins -> routes/app.$tenant/settings/plugins.tsx",
"/:tenant/settings/plugins/:id -> routes/app.$tenant/settings/plugins.$id.tsx",
"/:tenant/settings/plugins/:id/audit -> routes/app.$tenant/settings/plugins.$id.audit.tsx",
"/:tenant/settings/policies -> routes/app.$tenant/settings/policies.tsx",
"/:tenant/settings/privacy -> routes/app.$tenant/settings/privacy.tsx",
"/:tenant/settings/privacy/avv -> routes/app.$tenant/settings/privacy.avv.tsx",
"/:tenant/settings/privacy/delete/confirm/:token -> routes/app.$tenant/settings/privacy.delete.confirm.$token.tsx",
"/:tenant/settings/privacy/deletion -> routes/app.$tenant/settings/privacy.deletion.tsx",
"/:tenant/settings/privacy/export -> routes/app.$tenant/settings/privacy.export.tsx",
"/:tenant/settings/privacy/export/:jobId/download -> routes/app.$tenant/settings/privacy.export.$jobId.download.ts",
"/:tenant/settings/privacy/subprocessors -> routes/app.$tenant/settings/privacy.subprocessors.tsx",
"/:tenant/settings/profile -> routes/app.$tenant/settings/profile.tsx",
"/:tenant/settings/profile (index) -> routes/app.$tenant/settings/profile/index.tsx",
"/:tenant/settings/profile/appearance -> routes/app.$tenant/settings/profile/appearance.tsx",
"/:tenant/settings/profile/data -> routes/app.$tenant/settings/profile/data.tsx",
"/:tenant/settings/profile/notifications -> routes/app.$tenant/settings/profile/notifications.tsx",
"/:tenant/settings/profile/security -> routes/app.$tenant/settings/profile/security.tsx",
"/:tenant/settings/roles-and-permissions -> routes/app.$tenant/settings/roles-and-permissions.tsx",
"/:tenant/settings/roles-and-permissions (index) -> routes/app.$tenant/settings/roles-and-permissions/index.tsx",
"/:tenant/settings/roles-and-permissions/permissions -> routes/app.$tenant/settings/roles-and-permissions/permissions.tsx",
"/:tenant/settings/roles-and-permissions/roles -> routes/app.$tenant/settings/roles-and-permissions/roles.tsx",
"/:tenant/settings/roles-and-permissions/roles/:id -> routes/app.$tenant/settings/roles-and-permissions/roles/$id.tsx",
"/:tenant/settings/roles-and-permissions/roles/new -> routes/app.$tenant/settings/roles-and-permissions/roles/new.tsx",
"/:tenant/settings/roles-and-permissions/users -> routes/app.$tenant/settings/roles-and-permissions/users.tsx",
"/:tenant/settings/security -> routes/app.$tenant/settings/security.tsx",
"/:tenant/settings/subscription -> routes/app.$tenant/settings/subscription.tsx",
"/:tenant/settings/subscription (index) -> routes/app.$tenant/settings/subscription/index.tsx",
"/:tenant/settings/subscription/invoices/:invoiceId/download -> routes/app.$tenant/settings/subscription/invoices.$invoiceId.download.tsx",
"/:tenant/settings/team -> routes/app.$tenant/settings/team.tsx",
"/:tenant/settings/team (index) -> routes/app.$tenant/settings/team/index.tsx",
"/:tenant/settings/team/groups -> routes/app.$tenant/settings/team/groups.tsx",
"/:tenant/settings/team/groups/:id -> routes/app.$tenant/settings/team/groups/$id.tsx",
"/:tenant/settings/team/groups/new -> routes/app.$tenant/settings/team/groups/new.tsx",
"/:tenant/settings/team/members/edit/:id -> routes/app.$tenant/settings/team/members/edit.$id.tsx",
"/:tenant/settings/team/members/groups/:id -> routes/app.$tenant/settings/team/members/groups/$id.tsx",
"/:tenant/settings/team/members/groups/new -> routes/app.$tenant/settings/team/members/groups/new.tsx",
"/:tenant/settings/team/members/new -> routes/app.$tenant/settings/team/members/new.tsx",
"/:tenant/settings/team/roles -> routes/app.$tenant/settings/team/roles.tsx",
"/:tenant/settings/team/roles/:id -> routes/app.$tenant/settings/team/roles/$id.tsx",
"/:tenant/settings/team/roles/new -> routes/app.$tenant/settings/team/roles/new.tsx",
"/:tenant/settings/usage -> routes/app.$tenant/settings/usage.tsx",
"/:tenant/settings/workspace -> routes/app.$tenant/settings/workspace.tsx",
"/:tenant/settings/workspace (index) -> routes/app.$tenant/settings/workspace/index.tsx",
"/:tenant/settings/workspace/demo-data -> routes/app.$tenant/settings/workspace/demo-data.tsx",
"/:tenant/settings/workspace/policies -> routes/app.$tenant/settings/workspace/policies.tsx",
]
`;
@@ -7,7 +7,10 @@ const MAX_EXPORT_PAGE_SIZE = 100000;
const PAGE_SIZE_OPTIONS = [5, 10, 25, 50, 100];
const VERSION = "1.7.0";
export const DARK_MODE_IN_APP = true;
// HiveGrid ships without a dark theme for now: disabling this hides the
// light/dark toggle in the profile dropdowns (SubframeAppShell + nav-user)
// and keeps the app/admin area from applying the `dark` root class (root.tsx).
export const DARK_MODE_IN_APP = false;
// export const DARK_SIDEBAR_IN_LIGHT_MODE = true;
export default {
@@ -1,133 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { repoPathExists } from "~/utils/testing/repoPaths";
type FeatureManifest = {
id: string;
classification: string;
pruning: {
action: string;
};
};
const rootDir = process.cwd();
const docs = {
migrationStatus: "docs/architecture-migration-status.md",
featureInventory: "docs/feature-inventory.md",
manifestReadme: "docs/feature-manifests/README.md",
agentEntrypoints: "docs/agent-entrypoints.md",
} as const;
const requiredArchitectureClosureSources = [
"docs/architecture-migration-status.md",
"docs/feature-inventory.md",
"docs/feature-manifests/",
];
const documentedS04Evidence = ["apps/web/app/utils/build/bundleScan.ts", "apps/web/app/utils/build/manualChunks.ts"];
const requiredS04Evidence = [...documentedS04Evidence, "apps/web/app/utils/build/viteConfigIntegration.test.ts"];
function readProjectFile(filePath: string) {
return fs.readFileSync(path.join(rootDir, filePath), "utf8");
}
function readManifest(fileName: string) {
return JSON.parse(readProjectFile(path.join("docs/feature-manifests", fileName))) as FeatureManifest;
}
describe("Architecture Closure closure documentation", () => {
it("keeps architecture status anchored to boundaries, pruning manifests and S04 evidence", () => {
const status = readProjectFile(docs.migrationStatus);
expect(status).toContain("## Architecture Closure final closure status");
expect(status).toMatch(/handoff contract/i);
expect(status).toContain("apps/api");
expect(status).toContain("apps/worker");
expect(status).toContain("packages/db");
expect(status).toContain("packages/mail");
expect(status).toContain("docs/feature-manifests/");
expect(status).toContain("docs/feature-inventory.md");
expect(status).toContain("core`, `plugin-candidate`, `remove-candidate");
documentedS04Evidence.forEach((evidencePath) => {
expect(status, evidencePath).toContain(evidencePath);
});
});
it("keeps the feature inventory aligned with Architecture Closure status and pruning actions", () => {
const inventory = readProjectFile(docs.featureInventory);
expect(inventory).toContain("docs/architecture-migration-status.md");
expect(inventory).toContain("docs/feature-manifests/");
expect(inventory).toContain("`core` bleibt die aktive Boilerplate-Basis");
expect(inventory).toContain("`product-core` beschreibt Blueprint-, Plan-, Custom-Plan-, Tenant-Override- und Tenant-Rollen-Gates");
expect(inventory).toContain("`plugin-candidate` beschreibt nur noch Extraktionsvertraege");
expect(inventory).toContain("`remove-candidate` beschreibt Loesch- oder Review-Vertraege");
expect(inventory).toContain("API-Split");
expect(inventory).toContain("Worker/API/Mail-Split");
});
it("documents the executor-facing manifest contract and source alignment", () => {
const readme = readProjectFile(docs.manifestReadme);
requiredArchitectureClosureSources.forEach((sourcePath) => {
expect(readme, sourcePath).toContain(sourcePath);
});
expect(readme).toContain("current API, worker, package, pruning, and bundle handoff status");
expect(readme).toContain("machine-readable Core/Plugin/Removal contract");
expect(readme).toContain("ownership, dependencies, configuration, provider, worker, UAT, and pruning boundaries");
expect(readme).toContain("pruning.action");
expect(readme).toContain("keep`, `extract-plugin`, `remove`, or `review");
});
it("points agents at every canonical Architecture Closure planning source before feature work", () => {
const entrypoints = readProjectFile(docs.agentEntrypoints);
expect(entrypoints).toContain("Architecture Closure closure/status contract");
expect(entrypoints).toContain("docs/architecture-migration-status.md");
expect(entrypoints).toContain("docs/feature-inventory.md");
expect(entrypoints).toContain("docs/feature-manifests/*.json");
expect(entrypoints).toContain("before planning implementation, extraction, or removal work");
});
it("keeps the complete S04 bundle evidence set present for future verification", () => {
requiredS04Evidence.forEach((evidencePath) => {
expect(repoPathExists(evidencePath), evidencePath).toBe(true);
});
});
});
describe("Architecture Closure feature manifest pruning contract", () => {
const manifestDir = path.join(rootDir, "docs/feature-manifests");
const manifestFiles = fs
.readdirSync(manifestDir)
.filter((file) => file.endsWith(".json") && file !== "schema.json")
.sort();
it("keeps every non-schema feature manifest JSON-parseable", () => {
expect(manifestFiles.length).toBeGreaterThan(0);
manifestFiles.forEach((file) => {
expect(() => JSON.parse(readProjectFile(path.join("docs/feature-manifests", file))), file).not.toThrow();
});
});
it("exposes the canonical core/plugin/removal pruning actions", () => {
expect(readManifest("core.json")).toMatchObject({
id: "core",
classification: "core",
pruning: { action: "keep" },
});
expect(readManifest("plugin-candidates.json")).toMatchObject({
id: "plugin-candidates",
classification: "plugin-candidate",
pruning: { action: "extract-plugin" },
});
expect(readManifest("remove-candidates.json")).toMatchObject({
id: "remove-candidates",
classification: "remove-candidate",
pruning: { action: "remove" },
});
});
});
@@ -1,71 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const rootDir = process.cwd();
const docs = {
handoffSummary: "docs/archive/architecture-handoff-summary.md",
agentEntrypoints: "docs/agent-entrypoints.md",
} as const;
const requiredCanonicalSources = [
"docs/architecture-migration-status.md",
"docs/feature-inventory.md",
"docs/feature-manifests/README.md",
"docs/feature-manifests/*.json",
"docs/agent-entrypoints.md",
"apps/web/app/application/architectureClosureDocs.test.ts",
"apps/web/app/application/featureManifests.test.ts",
];
const requiredGateCommands = [
"pnpm exec vitest run apps/web/app/application/architectureClosureDocs.test.ts apps/web/app/application/featureManifests.test.ts",
"pnpm exec eslint --ext .tsx,.ts",
"pnpm typecheck",
];
function readProjectFile(filePath: string) {
return fs.readFileSync(path.join(rootDir, filePath), "utf8");
}
describe("Architecture Closure handoff summary contract", () => {
it("keeps the executor-facing handoff summary present", () => {
expect(fs.existsSync(path.join(rootDir, docs.handoffSummary))).toBe(true);
});
it("anchors the handoff to every canonical closure source", () => {
const handoff = readProjectFile(docs.handoffSummary);
requiredCanonicalSources.forEach((sourcePath) => {
expect(handoff, sourcePath).toContain(sourcePath);
});
});
it("documents Architecture Closure requirement coverage and prior-slice closure continuity", () => {
const handoff = readProjectFile(docs.handoffSummary);
expect(handoff).toContain("R001");
expect(handoff).toContain("R002");
expect(handoff).toMatch(/S04 bundle\/performance continuity/i);
expect(handoff).toMatch(/sequential follow-up order/i);
expect(handoff).toMatch(/avoiding any assumption that downstream feature slices can run in parallel/i);
});
it("preserves the non-E2E full gate and manual build follow-up wording", () => {
const handoff = readProjectFile(docs.handoffSummary);
requiredGateCommands.forEach((command) => {
expect(handoff, command).toContain(command);
});
expect(handoff).toMatch(/No E2E, browser, Cypress, or Playwright execution/i);
expect(handoff).toMatch(/pnpm build.*optional manual follow-up/i);
expect(handoff).toMatch(/not an Auto-Mode completion gate/i);
});
it("keeps the agent entrypoint pointed at the Architecture Closure handoff in closure/status context", () => {
const entrypoints = readProjectFile(docs.agentEntrypoints);
expect(entrypoints).toContain("Architecture Closure closure/status contract");
expect(entrypoints).toContain(docs.handoffSummary);
});
});
@@ -5,11 +5,39 @@ import { CookieCategory } from "./CookieCategory";
const allApplicationCookies: ApplicationCookie[] = [
{
category: CookieCategory.REQUIRED,
name: "hivegrid_session",
name: "__Host-hivegrid_app_session",
expiry: "1 month",
expiryKey: "cookies.expiry.oneMonth",
descriptionKey: "cookies.items.session.description",
},
{
category: CookieCategory.REQUIRED,
name: "__Host-hivegrid_admin_session",
expiry: "1 month",
expiryKey: "cookies.expiry.oneMonth",
descriptionKey: "cookies.items.session.description",
},
{
category: CookieCategory.REQUIRED,
name: "__Host-hivegrid_trusted_device",
expiry: "1 month",
expiryKey: "cookies.expiry.oneMonth",
descriptionKey: "cookies.items.trustedDevice.description",
},
{
category: CookieCategory.REQUIRED,
name: "__Host-hivegrid_admin_sso_challenge",
expiry: "10 minutes",
expiryKey: "cookies.expiry.tenMinutes",
descriptionKey: "cookies.items.adminSsoChallenge.description",
},
{
category: CookieCategory.REQUIRED,
name: "__Host-hivegrid_admin_sso_id_token",
expiry: "15 minutes",
expiryKey: "cookies.expiry.fifteenMinutes",
descriptionKey: "cookies.items.adminSsoIdToken.description",
},
{
category: CookieCategory.FUNCTIONAL,
name: "crisp-client/*",
@@ -1,6 +1,4 @@
import { UserWithoutPassword } from "~/utils/db/users.db.server";
export type ImpersonatingSessionDto = {
fromUser: UserWithoutPassword;
toUser: UserWithoutPassword;
fromUser: { id: string; email: string };
toUser: { id: string; email: string };
};
@@ -7,10 +7,6 @@ export const DefaultPermissions = [
"admin.account.users",
"admin.account.subscription",
"admin.account.delete",
"admin.accountTypes.view",
"admin.accountTypes.create",
"admin.accountTypes.update",
"admin.accountTypes.delete",
"admin.users.view",
"admin.users.impersonate",
"admin.users.changePassword",
@@ -51,6 +47,10 @@ export const DefaultPermissions = [
"admin.featureFlags.manage",
"admin.marketing.leads.view",
"admin.marketing.leads.manage",
"admin.leads.read_own",
"admin.leads.read_all",
"admin.leads.write",
"admin.leads.admin",
"admin.marketing.integrations.view",
"admin.marketing.integrations.manage",
"admin.marketing.funnels.view",
@@ -65,9 +65,6 @@ export const DefaultPermissions = [
"admin.kb.create",
"admin.kb.update",
"admin.kb.delete",
"admin.settings.cookies.view",
"admin.settings.cookies.create",
"admin.settings.cookies.update",
"admin.settings.general.view",
"admin.settings.general.update",
"admin.settings.authentication.view",
@@ -113,6 +110,15 @@ export const DefaultPermissions = [
"app.settings.auditTrails.view",
"app.plugins.use",
"app.plugins.manage",
// P26 Customer Portal (VA-P26a/b) — tenant-side portal management only.
// PortalUser identities never receive workspace permissions.
"portal.read",
"portal.manage_users",
"portal.manage_access",
"portal.delete_user",
"portal.activity.read",
"portal.activity.manage",
"portal.admin",
// P4 Files (AK-P4a) — see packages/db permissions-seed (same list).
"files.read_own",
"files.read_all",
@@ -147,6 +153,10 @@ export const DefaultPermissions = [
"projects.manage_members",
"projects.delete",
"projects.admin",
// WF-P8 S02-N: read notes marked "Nur Innendienst".
"projects.read_internal_notes",
// WF-P8 M04: hand a project over into the successor pipeline.
"projects.handover",
// P9 Plantafel + Abnahme (R-P9b) — see packages/db permissions-seed.
"plantafel.read_own",
"plantafel.read_all",
@@ -164,6 +174,7 @@ export const DefaultPermissions = [
"hr.write",
"hr.admin",
"hr.passwordsafe.use",
"hr.passwordsafe.export",
"hr.passwordsafe.admin",
// P17 HR-Hub workflows (AK-P17b) — see packages/db permissions-seed (same list).
"hr.leave.approve",
@@ -189,6 +200,21 @@ export const DefaultPermissions = [
"integrations.manual_sync",
"integrations.view_logs",
"integrations.admin",
// P15 Telephony (AK-P15a) — see packages/db permissions-seed (same list).
// read_own/call are user capabilities; read_all/manage are tenant-admin
// capabilities for call history, OAuth setup, bindings and match overrides.
"telephony.read_own",
"telephony.read_all",
"telephony.call",
"telephony.manage",
// P15 Team-Chat (AK-P15b) — membership-scoped collaboration plus explicit
// tenant-wide channel administration and audited read access.
"chat.read_own_channels",
"chat.write",
"chat.create_channel",
"chat.create_dm",
"chat.admin",
"chat.read_all_channels",
// P16 Calendar-Sync (AK-P16a) — see packages/db permissions-seed (same list).
// connect_own: connect/manage your OWN calendar; admin: tenant-wide oversight
// + force-disconnect on user offboarding (M25 Block I).
@@ -213,7 +239,7 @@ export const DefaultPermissions = [
"signature.send",
"signature.revoke",
"signature.admin",
// P11 Global Search (R-P11a) — search.use opens Cmd+K and full search;
// P11 Global Search (R-P11a) — search.use opens the desktop/mobile Spotlight search;
// search.admin is reserved for reindex/admin controls.
"search.use",
"search.admin",
@@ -224,6 +250,42 @@ export const DefaultPermissions = [
"privacy.avv.read",
"privacy.avv.accept",
"privacy.subprocessors.read",
// P28 Admin identity and platform-sales workspace.
"admin_identity.users.read",
"admin_identity.users.manage",
"admin_identity.roles.read",
"admin_identity.roles.manage",
"admin_identity.sessions.read",
"admin_identity.sessions.revoke",
"admin_identity.audit.read",
"admin_identity.audit.export",
"admin_identity.impersonation.start",
"admin_identity.tenants.manage",
"admin_sales.crm.read",
"admin_sales.crm.read_all",
"admin_sales.crm.write",
"admin_sales.crm.write_all",
"admin_sales.crm.assign",
"admin_sales.crm.merge",
"admin_sales.crm.export",
"admin_sales.communication.read_all",
"admin_sales.email.connect",
"admin_sales.email.send",
"admin_sales.email.track",
"admin_sales.email.bulk_send",
"admin_sales.phone.call",
"admin_sales.phone.recording",
"admin_sales.sequence.manage",
"admin_sales.sequence.enroll",
"admin_sales.booking.manage",
"admin_sales.quote.manage",
"admin_sales.quote.approve",
"admin_sales.signature.manage",
"admin_sales.reporting.read",
"admin_sales.reporting.read_all",
"admin_sales.reporting.manage",
"admin_sales.automation.manage",
"admin_sales.integrations.manage",
// "entity.{name}.view",
// "entity.{name}.read",
// "entity.{name}.create",
@@ -2,7 +2,7 @@ import { SubscriptionPriceDto } from "./SubscriptionPriceDto";
import { SubscriptionFeatureDto } from "./SubscriptionFeatureDto";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { SubscriptionUsageBasedPriceDto } from "./SubscriptionUsageBasedPriceDto";
import { TenantSubscriptionProduct, TenantType } from "@hivegrid/db/prisma-browser";
import { TenantSubscriptionProduct } from "@hivegrid/db/prisma-browser";
export interface SubscriptionProductDto {
id?: string;
@@ -21,8 +21,11 @@ export interface SubscriptionProductDto {
translatedTitle?: string;
usageBasedPrices?: SubscriptionUsageBasedPriceDto[];
tenantProducts?: TenantSubscriptionProduct[];
assignsTenantTypes?: TenantType[];
tenantProductCount?: number;
billingAddressCollection?: string | null;
hasQuantity?: boolean;
canBuyAgain?: boolean;
kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
code?: string | null;
lagoPlanCode?: string | null;
}
@@ -1,9 +0,0 @@
export type TenantTypeDto = {
id?: string;
title: string;
titlePlural: string;
description: string | null;
isDefault?: boolean;
subscriptionProducts?: { id?: string; title: string }[];
_count?: { tenants: number };
};
@@ -1,142 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { getEnvVariableDefinition } from "@hivegrid/config";
import { loadFeatureManifests } from "@hivegrid/plugins";
import { queueNames } from "@hivegrid/queue";
const manifestLoad = await loadFeatureManifests();
const manifests = manifestLoad.manifests;
const requiredPlaybooks = [
"docs/agent-entrypoints.md",
"docs/agent-playbooks/feature-integration.md",
"docs/agent-playbooks/mvp-intake.md",
"docs/agent-playbooks/admin-managed-features.md",
"docs/agent-playbooks/worker-backed-features.md",
];
function expectStringArray(value: unknown) {
expect(Array.isArray(value)).toBe(true);
expect((value as unknown[]).every((item) => typeof item === "string")).toBe(true);
}
describe("agent feature planning docs", () => {
it("provides the required agent entrypoint and playbooks", () => {
requiredPlaybooks.forEach((file) => {
expect(fs.existsSync(path.join(process.cwd(), file)), file).toBe(true);
});
});
it("documents the key concepts agents need before implementation", () => {
const entrypoint = fs.readFileSync(path.join(process.cwd(), "docs/agent-entrypoints.md"), "utf8");
const featureIntegration = fs.readFileSync(path.join(process.cwd(), "docs/agent-playbooks/feature-integration.md"), "utf8");
const adminManaged = fs.readFileSync(path.join(process.cwd(), "docs/agent-playbooks/admin-managed-features.md"), "utf8");
const workerBacked = fs.readFileSync(path.join(process.cwd(), "docs/agent-playbooks/worker-backed-features.md"), "utf8");
expect(entrypoint).toContain("MVP import");
expect(featureIntegration).toContain("Feature Integration Playbook");
expect(featureIntegration).toContain("Do not expose provider secrets");
expect(adminManaged).toContain("admin-managed");
expect(adminManaged).toContain("Provider keys must not be sent to tenant loaders");
expect(workerBacked).toContain("Browser-backed features require extra constraints");
});
});
describe("feature manifests", () => {
it("keeps every manifest on the integration-aware schema", () => {
manifests.forEach((manifest) => {
expect(manifest.schemaVersion).toBe("1.0");
expect(manifest.id).toMatch(/^[a-z0-9][a-z0-9-]*$/);
expect(manifest.title).toEqual(expect.any(String));
expect(["core", "plugin-candidate", "remove-candidate", "mixed"]).toContain(manifest.classification);
expect(["active", "proposed", "review-needed"]).toContain(manifest.status);
expectStringArray(manifest.rationale);
expectStringArray(manifest.codeAreas);
expectStringArray(manifest.dependencies);
expectStringArray(manifest.consumers);
expectStringArray(manifest.boundaries.mustKeep);
expectStringArray(manifest.boundaries.mayMoveToPlugin);
expectStringArray(manifest.boundaries.mustNotTouch);
expectStringArray(manifest.pruning.notes);
expectStringArray(manifest.validation.source);
expect(manifest.validation.lastReviewed).toMatch(/^\d{4}-\d{2}-\d{2}$/);
});
});
it("requires explicit ownership, surfaces, configuration, workers and UAT", () => {
manifests.forEach((manifest) => {
expect(["tenant-owned", "admin-managed", "hybrid", "system-only"]).toContain(manifest.integration.ownership);
expectStringArray(manifest.integration.surfaces.adminRoutes);
expectStringArray(manifest.integration.surfaces.tenantRoutes);
expectStringArray(manifest.integration.surfaces.publicRoutes);
expectStringArray(manifest.integration.surfaces.apiRoutes);
expectStringArray(manifest.integration.configuration.admin);
expectStringArray(manifest.integration.configuration.tenant);
expectStringArray(manifest.integration.configuration.environment);
expectStringArray(manifest.integration.configuration.secrets);
expect(typeof manifest.integration.workers.required).toBe("boolean");
expectStringArray(manifest.integration.workers.queues);
expectStringArray(manifest.integration.workers.jobs);
expectStringArray(manifest.integration.workers.notes);
expectStringArray(manifest.integration.externalProviders);
expectStringArray(manifest.integration.permissions);
expectStringArray(manifest.integration.auditEvents);
expectStringArray(manifest.integration.billingImpacts);
expectStringArray(manifest.integration.uat);
expect(manifest.integration.uat.length, manifest.id).toBeGreaterThan(0);
});
});
it("loads real docs manifests without loader diagnostics", () => {
expect(manifestLoad.ok).toBe(true);
expect(manifestLoad.diagnostics).toEqual([]);
});
it("guards the Feature Manifest manifest decision contract in docs", () => {
const inventory = fs.readFileSync(path.join(process.cwd(), "docs/feature-inventory.md"), "utf8");
const manifestReadme = fs.readFileSync(path.join(process.cwd(), "docs/feature-manifests/README.md"), "utf8");
["Manifest-Decision", "Pruned Core", "Full-Boilerplate", "plugin-candidate", "remove-candidate"].forEach((anchor) => {
expect(inventory, `inventory missing ${anchor}`).toContain(anchor);
expect(manifestReadme, `manifest README missing ${anchor}`).toContain(anchor);
});
["core", "plugin-candidates", "remove-candidates"].forEach((manifestIdAnchor) => {
expect(manifestReadme, `manifest README missing ${manifestIdAnchor}`).toContain(manifestIdAnchor);
});
});
it("guards admin-managed secret ownership and worker-backed declarations", () => {
manifests
.filter((manifest) => manifest.integration.ownership === "admin-managed")
.forEach((manifest) => {
expect(manifest.integration.configuration.admin.length, manifest.id).toBeGreaterThan(0);
expect(manifest.integration.configuration.secrets.join(" ").toLowerCase(), manifest.id).toMatch(/admin|platform/);
expect(manifest.integration.permissions.some((permission) => permission.startsWith("admin.")), manifest.id).toBe(true);
expect(manifest.integration.auditEvents.length, manifest.id).toBeGreaterThan(0);
});
manifests
.filter((manifest) => manifest.integration.workers.required)
.forEach((manifest) => {
expect(manifest.integration.workers.queues.length, manifest.id).toBeGreaterThan(0);
expect(manifest.integration.workers.jobs.length, manifest.id).toBeGreaterThan(0);
});
});
it("keeps admin-managed browser feature contracts backed by config and queue packages", () => {
[
"BULLMQ_REDIS_URL",
"BROWSER_RUNTIME_URL",
"BROWSER_RUNTIME_API_KEY",
"BROWSER_SESSION_TIMEOUT_MS",
].forEach((name) => {
const definition = getEnvVariableDefinition(name);
expect(definition?.classification, name).toBe("optional-provider");
expect(definition?.targets.some((target) => target === "api" || target === "worker"), name).toBe(true);
});
expect(queueNames.browserAutomation).toBe("hivegrid.browser-automation");
});
});
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import {
deriveAdminCatalogProductKind,
isManagedBillingCatalogProduct,
} from "./adminCatalogPolicy";
describe("admin billing catalog policy", () => {
it("protects every canonical base-plan identity and every base-plan row", () => {
for (const code of [
"starter",
"starter_annual_sepa",
"pro",
"pro_annual_sepa",
"business",
"business_annual_sepa",
]) {
expect(isManagedBillingCatalogProduct({ code })).toBe(true);
}
expect(isManagedBillingCatalogProduct({ kind: "base_plan", code: "legacy" })).toBe(true);
expect(
isManagedBillingCatalogProduct({
kind: "recurring_add_on",
code: "customer_portal_monthly",
}),
).toBe(false);
});
it("creates only separate recurring add-ons or one-time setup products", () => {
expect(
deriveAdminCatalogProductKind([
{ billingPeriod: SubscriptionBillingPeriod.MONTHLY },
]),
).toBe("recurring_add_on");
expect(
deriveAdminCatalogProductKind([
{ billingPeriod: SubscriptionBillingPeriod.ONCE },
]),
).toBe("one_time_setup");
expect(
deriveAdminCatalogProductKind([
{ billingPeriod: SubscriptionBillingPeriod.ONCE },
{ billingPeriod: SubscriptionBillingPeriod.MONTHLY },
]),
).toBeNull();
expect(deriveAdminCatalogProductKind([])).toBeNull();
});
});
@@ -0,0 +1,43 @@
import { hiveGridBasePlans } from "@hivegrid/entitlements";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
export type AdminCatalogProductKind =
| "base_plan"
| "recurring_add_on"
| "one_time_setup"
| "contract_override";
type AdminCatalogProductIdentity = {
readonly kind?: AdminCatalogProductKind | null;
readonly code?: string | null;
readonly lagoPlanCode?: string | null;
};
const managedBasePlanCodes = new Set(
hiveGridBasePlans.flatMap((plan) => [
plan.technicalCode,
...plan.variants.map((variant) => variant.code),
]),
);
export function isManagedBillingCatalogProduct(
product: AdminCatalogProductIdentity,
): boolean {
if (product.kind === "base_plan") return true;
return [product.code, product.lagoPlanCode].some(
(code) => Boolean(code?.trim() && managedBasePlanCodes.has(code.trim())),
);
}
export function deriveAdminCatalogProductKind(
prices: readonly { readonly billingPeriod: SubscriptionBillingPeriod }[],
): Exclude<AdminCatalogProductKind, "base_plan" | "contract_override"> | null {
if (prices.length === 0) return null;
const oneTimeCount = prices.filter(
(price) => price.billingPeriod === SubscriptionBillingPeriod.ONCE,
).length;
if (oneTimeCount === prices.length) return "one_time_setup";
if (oneTimeCount === 0) return "recurring_add_on";
return null;
}
@@ -1,325 +0,0 @@
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { SubscriptionPriceType } from "~/application/enums/subscriptions/SubscriptionPriceType";
import { DefaultFeatures } from "../dtos/shared/DefaultFeatures";
import { SubscriptionPriceDto } from "../dtos/subscriptions/SubscriptionPriceDto";
import { SubscriptionProductDto } from "../dtos/subscriptions/SubscriptionProductDto";
import { SubscriptionUsageBasedPriceDto } from "../dtos/subscriptions/SubscriptionUsageBasedPriceDto";
import { SubscriptionUsageBasedTierDto } from "../dtos/subscriptions/SubscriptionUsageBasedTierDto";
import { PricingModel } from "../enums/subscriptions/PricingModel";
import { SubscriptionFeatureLimitType } from "../enums/subscriptions/SubscriptionFeatureLimitType";
const UNIT_API_CALL = {
name: "api",
title: "API Call",
titlePlural: "API Calls",
};
function generatePrice(currency: string, price: number, billingPeriod: SubscriptionBillingPeriod): SubscriptionPriceDto {
return {
billingProviderId: "",
subscriptionProductId: "",
type: billingPeriod === SubscriptionBillingPeriod.ONCE ? SubscriptionPriceType.ONE_TIME : SubscriptionPriceType.RECURRING,
billingPeriod,
price: Math.round(price * 100) / 100,
currency,
trialDays: 0,
active: true,
usageBasedPrices: [],
};
}
function generateUsageBasedPrice(
currency: string,
unit: {
name: string;
title: string;
titlePlural: string;
},
usageType: "licensed" | "metered",
aggregateUsage: "last_during_period" | "last_ever" | "max" | "sum",
tiersMode: "graduated" | "volume",
billingScheme: "per_unit" | "tiered",
tiers: {
from: number;
to: undefined | number;
perUnitPrice: number | undefined;
flatFeePrice: number | undefined;
}[]
): SubscriptionUsageBasedPriceDto {
const usageBasedPriceTiers: SubscriptionUsageBasedTierDto[] = [];
tiers.forEach((tier) => {
usageBasedPriceTiers.push({
id: "",
subscriptionUsageBasedPriceId: "",
...tier,
});
});
return {
id: "",
billingProviderId: "",
subscriptionProductId: "",
billingPeriod: SubscriptionBillingPeriod.MONTHLY,
currency,
unit: unit.name,
unitTitle: unit.title,
unitTitlePlural: unit.titlePlural,
usageType,
aggregateUsage,
tiersMode,
billingScheme,
tiers: usageBasedPriceTiers,
};
}
function generateCommonPlan(order: number, model: PricingModel) {
if (order === 1) {
return {
billingProviderId: "",
order,
title: "pricing.products.plan1.title",
description: "pricing.products.plan1.description",
model,
public: true,
features: [
{
order: 1,
title: "pricing.features.users.max",
name: DefaultFeatures.Users,
value: 2,
type: SubscriptionFeatureLimitType.MAX,
accumulate: false,
},
{
order: 3,
title: "pricing.features.apiCalls.units",
name: DefaultFeatures.API,
value: 0,
type: SubscriptionFeatureLimitType.NOT_INCLUDED,
accumulate: false,
},
{
order: 4,
title: "pricing.features.prioritySupport.none",
name: DefaultFeatures.PrioritySupport,
value: 0,
type: SubscriptionFeatureLimitType.NOT_INCLUDED,
accumulate: false,
},
],
badge: "",
active: true,
prices: [],
};
} else if (order === 2) {
return {
billingProviderId: "",
order,
title: "pricing.products.plan2.title",
description: "pricing.products.plan2.description",
public: true,
model,
features: [
{
order: 1,
title: "pricing.features.users.max",
name: DefaultFeatures.Users,
value: 5,
type: SubscriptionFeatureLimitType.MAX,
accumulate: false,
},
{
order: 3,
title: "pricing.features.apiCalls.monthly",
name: DefaultFeatures.API,
value: 100,
type: SubscriptionFeatureLimitType.MONTHLY,
accumulate: false,
},
{
order: 4,
title: "pricing.features.prioritySupport.basic",
name: DefaultFeatures.PrioritySupport,
value: 0,
type: SubscriptionFeatureLimitType.INCLUDED,
accumulate: false,
},
],
badge: "pricing.recommended",
active: true,
};
} else if (order === 3) {
return {
billingProviderId: "",
order,
title: "pricing.products.plan3.title",
description: "pricing.products.plan3.description",
public: true,
model,
features: [
{
order: 1,
title: "pricing.features.users.max",
name: DefaultFeatures.Users,
value: 12,
type: SubscriptionFeatureLimitType.MAX,
accumulate: false,
},
{
order: 3,
title: "pricing.features.apiCalls.unlimited",
name: DefaultFeatures.API,
value: 0,
type: SubscriptionFeatureLimitType.UNLIMITED,
accumulate: false,
},
{
order: 4,
title: "pricing.features.prioritySupport.priority",
name: DefaultFeatures.PrioritySupport,
value: 0,
type: SubscriptionFeatureLimitType.INCLUDED,
accumulate: false,
},
],
badge: "",
active: true,
};
}
return {
billingProviderId: "",
order,
title: "pricing.products.plan1.title",
description: "pricing.products.plan1.description",
model,
public: true,
features: [
{
order: 1,
title: "pricing.features.users.one",
name: DefaultFeatures.Users,
value: 1,
type: SubscriptionFeatureLimitType.MAX,
accumulate: false,
},
],
badge: "",
active: true,
};
}
const FLAT_RATE_PRICES: SubscriptionProductDto[] = [
{
...generateCommonPlan(1, PricingModel.FLAT_RATE),
prices: [
generatePrice("usd", 9, SubscriptionBillingPeriod.MONTHLY),
generatePrice("usd", 90, SubscriptionBillingPeriod.YEARLY),
generatePrice("mxn", 199, SubscriptionBillingPeriod.MONTHLY),
generatePrice("mxn", 1990, SubscriptionBillingPeriod.YEARLY),
],
usageBasedPrices: [],
},
{
...generateCommonPlan(2, PricingModel.FLAT_RATE),
prices: [
generatePrice("usd", 199, SubscriptionBillingPeriod.MONTHLY),
generatePrice("usd", 1990, SubscriptionBillingPeriod.YEARLY),
generatePrice("mxn", 3999, SubscriptionBillingPeriod.MONTHLY),
generatePrice("mxn", 39990, SubscriptionBillingPeriod.YEARLY),
],
usageBasedPrices: [],
},
{
...generateCommonPlan(3, PricingModel.FLAT_RATE),
prices: [
generatePrice("usd", 399, SubscriptionBillingPeriod.MONTHLY),
generatePrice("usd", 3990, SubscriptionBillingPeriod.YEARLY),
generatePrice("mxn", 7999, SubscriptionBillingPeriod.MONTHLY),
generatePrice("mxn", 79990, SubscriptionBillingPeriod.YEARLY),
],
usageBasedPrices: [],
},
];
const USAGE_BASED_PRICES: SubscriptionProductDto[] = [
{
...generateCommonPlan(1, PricingModel.USAGE_BASED),
prices: [],
usageBasedPrices: [
generateUsageBasedPrice("usd", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 0.02, flatFeePrice: 5 },
{ from: 21, to: undefined, perUnitPrice: 0.01, flatFeePrice: 10 },
]),
generateUsageBasedPrice("mxn", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 0.4, flatFeePrice: 100 },
{ from: 21, to: undefined, perUnitPrice: 0.2, flatFeePrice: 200 },
]),
],
},
{
...generateCommonPlan(2, PricingModel.USAGE_BASED),
prices: [],
usageBasedPrices: [
generateUsageBasedPrice("usd", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 0.04, flatFeePrice: 10 },
{ from: 21, to: undefined, perUnitPrice: 0.02, flatFeePrice: 20 },
]),
generateUsageBasedPrice("mxn", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 0.8, flatFeePrice: 200 },
{ from: 21, to: undefined, perUnitPrice: 0.4, flatFeePrice: 400 },
]),
],
},
{
...generateCommonPlan(3, PricingModel.USAGE_BASED),
prices: [],
usageBasedPrices: [
generateUsageBasedPrice("usd", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 0.06, flatFeePrice: 15 },
{ from: 21, to: undefined, perUnitPrice: 0.03, flatFeePrice: 30 },
]),
generateUsageBasedPrice("mxn", UNIT_API_CALL, "metered", "sum", "volume", "tiered", [
{ from: 0, to: 10, perUnitPrice: 0.0, flatFeePrice: undefined },
{ from: 11, to: 20, perUnitPrice: 1.2, flatFeePrice: 300 },
{ from: 21, to: undefined, perUnitPrice: 0.6, flatFeePrice: 600 },
]),
],
},
];
const FLAT_RATE_PLUS_USAGE_BASED_PRICES: SubscriptionProductDto[] = [
...FLAT_RATE_PRICES.map((flatRate) => {
const usageBasedPrices = USAGE_BASED_PRICES.find((f) => f.order === flatRate.order)?.usageBasedPrices ?? [];
return {
...flatRate,
usageBasedPrices,
model: PricingModel.FLAT_RATE_USAGE_BASED,
};
}),
];
const ONE_TIME_PRICES: SubscriptionProductDto[] = [
{
...generateCommonPlan(1, PricingModel.ONCE),
prices: [generatePrice("usd", 99 * 2, SubscriptionBillingPeriod.ONCE), generatePrice("mxn", 1999 * 2, SubscriptionBillingPeriod.ONCE)],
usageBasedPrices: [],
},
{
...generateCommonPlan(2, PricingModel.ONCE),
prices: [generatePrice("usd", 499 * 2, SubscriptionBillingPeriod.ONCE), generatePrice("mxn", 9999 * 2, SubscriptionBillingPeriod.ONCE)],
usageBasedPrices: [],
},
{
...generateCommonPlan(3, PricingModel.ONCE),
prices: [generatePrice("usd", 1999 * 2, SubscriptionBillingPeriod.ONCE), generatePrice("mxn", 4999 * 2, SubscriptionBillingPeriod.ONCE)],
usageBasedPrices: [],
},
];
const plans = [...FLAT_RATE_PRICES, ...USAGE_BASED_PRICES, ...FLAT_RATE_PLUS_USAGE_BASED_PRICES, ...ONE_TIME_PRICES];
export default plans;
@@ -1,17 +1,27 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import plans from "~/application/pricing/plans.server";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import { HIVEGRID_SUBSCRIPTION_PRICING_MODELS, isHiveGridSubscriptionPricingModel } from "./pricingModelPolicy";
describe("HiveGrid subscription pricing model policy", () => {
it("does not allow seat-type pricing models", () => {
it("allows only fixed recurring and one-time products", () => {
expect(HIVEGRID_SUBSCRIPTION_PRICING_MODELS).toEqual([PricingModel.FLAT_RATE, PricingModel.ONCE]);
expect(HIVEGRID_SUBSCRIPTION_PRICING_MODELS).not.toContain(PricingModel.PER_SEAT);
expect(HIVEGRID_SUBSCRIPTION_PRICING_MODELS).not.toContain(PricingModel.USAGE_BASED);
expect(HIVEGRID_SUBSCRIPTION_PRICING_MODELS).not.toContain(PricingModel.FLAT_RATE_USAGE_BASED);
expect(isHiveGridSubscriptionPricingModel(PricingModel.PER_SEAT)).toBe(false);
expect(isHiveGridSubscriptionPricingModel(PricingModel.USAGE_BASED)).toBe(false);
expect(isHiveGridSubscriptionPricingModel(PricingModel.FLAT_RATE_USAGE_BASED)).toBe(false);
});
it("keeps generated admin pricing seeds free of seat-type plans", () => {
expect(plans).not.toHaveLength(0);
expect(plans.map((plan) => plan.model)).not.toContain(PricingModel.PER_SEAT);
it("does not expose the removed demo-plan generator from the admin route", () => {
const route = fs.readFileSync(path.join(process.cwd(), "apps/web/app/routes/admin/settings/pricing.tsx"), "utf8");
expect(route).not.toContain("plans.server");
expect(route).not.toContain("create-all-plans");
expect(route).not.toContain("generateFromFiles");
expect(route).toContain("admin.pricing.catalogManaged");
});
});
@@ -1,13 +1,7 @@
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
export const HIVEGRID_SUBSCRIPTION_PRICING_MODELS = [
PricingModel.FLAT_RATE,
PricingModel.USAGE_BASED,
PricingModel.FLAT_RATE_USAGE_BASED,
PricingModel.ONCE,
] as const;
export const HIVEGRID_SUBSCRIPTION_PRICING_MODELS = [PricingModel.FLAT_RATE, PricingModel.ONCE] as const;
export function isHiveGridSubscriptionPricingModel(model: PricingModel) {
return HIVEGRID_SUBSCRIPTION_PRICING_MODELS.includes(model as (typeof HIVEGRID_SUBSCRIPTION_PRICING_MODELS)[number]);
}
@@ -3,7 +3,8 @@ import * as path from "node:path";
import { describe, it, expect, vi } from "vitest";
import { AdminSidebar } from "./AdminSidebar";
import type { SideBarItem } from "./SidebarItem";
import { canonicalAdminRouteSlugs, disabledPluginRouteSlugs } from "~/utils/app/PublicRouteSegments";
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
import { canonicalAdminRouteExactPaths, canonicalAdminRouteSlugs, disabledPluginRouteSlugs } from "~/utils/app/PublicRouteSegments";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
function flattenSidebarItems(items: SideBarItem[]): SideBarItem[] {
@@ -84,15 +85,14 @@ describe("AdminSidebar", () => {
expect(serialized).toContain("/accounts");
expect(serialized).toContain("/audit-trails");
expect(serialized).toContain("/notifications/messages");
expect(serialized).toContain("/feature-flags/flags");
expect(serialized).toContain("/settings/profile");
expect(serialized).not.toContain("/feature-flags");
expect(serialized).toContain("/settings/security");
expect(serialized).not.toContain("/settings/profile");
expect(serialized).not.toContain("/metrics");
expect(sidebar).toEqual(
expect.arrayContaining([
expect.objectContaining({
items: expect.arrayContaining([
expect.objectContaining({ id: "ui.nav.admin.dashboard", path: "/dashboard" }),
]),
items: expect.arrayContaining([expect.objectContaining({ id: "ui.nav.admin.dashboard", path: "/dashboard" })]),
}),
])
);
@@ -113,12 +113,15 @@ describe("AdminSidebar", () => {
expect(serialized).not.toContain("/portals");
expect(serialized).not.toContain("/prompts");
expect(serialized).not.toContain("/workflow-engine");
expect(serialized).not.toContain("\"path\":\"/crm\"");
expect(serialized).not.toContain('"path":"/crm"');
expect(serialized).not.toContain("ui.nav.admin.crm");
expect(allPaths.map((path) => path.split("/").filter(Boolean)[0])).not.toEqual(expect.arrayContaining([...disabledPluginRouteSlugs]));
expect(allPaths.map((path) => path.split("/").filter(Boolean)[0])).toEqual(expect.arrayContaining(["dashboard", "accounts", "settings"]));
allPaths.forEach((path) => {
expect(canonicalAdminRouteSlugs).toContain(path.split("/").filter(Boolean)[0] as any);
const firstSlug = path.split("/").filter(Boolean)[0] ?? "";
const isCanonicalSlug = (canonicalAdminRouteSlugs as readonly string[]).includes(firstSlug);
const isCanonicalExactPath = (canonicalAdminRouteExactPaths as readonly string[]).includes(path);
expect(isCanonicalSlug || isCanonicalExactPath, path).toBe(true);
});
sidebar.forEach((item) => {
@@ -136,6 +139,155 @@ describe("AdminSidebar", () => {
});
});
it("consolidates platform operations and support without exposing feature flags", () => {
const sidebar = AdminSidebar({ t, appConfiguration: null });
const platform = sidebar.find((item) => item.id === "ui.nav.admin.platform");
const platformItems = platform?.items ?? [];
const operations = platformItems.find((item) => item.id === "ui.nav.admin.platform.operations");
const support = platformItems.find((item) => item.id === "ui.nav.admin.platform.support");
expect(platformItems.map((item) => item.id)).toEqual(["ui.nav.admin.platform.operations", "ui.nav.admin.platform.support", UI_NAV_IDS.adminApi]);
expect(operations).toMatchObject({
title: "admin.platformNavigation.operations",
path: "/system",
isCollapsible: false,
activePaths: ["/system", "/system/health", "/system/deploys", "/system/jobs", "/system/webhooks", "/system/billing"],
anyPermissions: ["admin.metrics.view", "admin.events.view", "admin.account.subscription"],
});
expect(operations?.items?.map((item) => item.path)).toEqual([
"/system",
"/system/health",
"/system/deploys",
"/system/jobs",
"/system/webhooks",
"/system/billing",
]);
const accounts = flattenSidebarItems(sidebar).find((item) => item.id === UI_NAV_IDS.adminAccounts);
const audit = flattenSidebarItems(sidebar).find((item) => item.id === UI_NAV_IDS.adminAudit);
expect(accounts?.items?.map((item) => item.path)).not.toContain("/accounts/billing");
expect(accounts?.excludePaths).toContain("/accounts/billing");
expect(audit?.items?.map((item) => item.path)).not.toContain("/webhooks");
expect(support).toMatchObject({
title: "admin.platformNavigation.support",
path: "/support",
anyPermissions: ["admin_identity.impersonation.start", "admin.metrics.view"],
isCollapsible: false,
activePaths: ["/support", "/support/kwp-contracts"],
});
expect(support?.items?.map((item) => item.path)).toEqual(["/support", "/support/kwp-contracts"]);
expect(platformItems.at(-1)).toMatchObject({
id: UI_NAV_IDS.adminApi,
title: "admin.platformNavigation.apiAccess",
path: "/api",
});
expect(flattenSidebarItems(sidebar).map((item) => item.id)).not.toContain(UI_NAV_IDS.adminFeatureFlags);
});
it("gates platform leads only by the sales CRM read permission", () => {
const leadInbox = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null })).find((item) => item.id === "ui.nav.admin.platformLeads");
expect(leadInbox).toMatchObject({
permission: "admin_sales.crm.read",
});
});
it("keeps sales work and communication separate while nesting configuration under settings", () => {
const sidebar = AdminSidebar({ t, appConfiguration: null });
const salesGroups = sidebar.filter((item) => ["ui.nav.admin.sales", "ui.nav.admin.salesCommunication"].includes(item.id ?? ""));
const settings = flattenSidebarItems(sidebar).find((item) => item.id === UI_NAV_IDS.adminSettings);
expect(salesGroups.map((group) => group.id)).toEqual(["ui.nav.admin.sales", "ui.nav.admin.salesCommunication"]);
expect(salesGroups.map((group) => group.title)).toEqual(["admin.sales.navigation.title", "admin.sales.navigation.communicationSection"]);
expect(salesGroups[0]?.items?.map((item) => item.id)).toEqual([
"ui.nav.admin.sales.today",
"ui.nav.admin.platformLeads",
"ui.nav.admin.sales.deals",
"ui.nav.admin.sales.contacts",
"ui.nav.admin.sales.companies",
UI_NAV_IDS.adminSalesImportExport,
]);
expect(salesGroups[1]?.items?.map((item) => item.id)).toEqual(["ui.nav.admin.sales.email", "ui.nav.admin.sales.calls", "ui.nav.admin.sales.bookings"]);
expect(salesGroups.flatMap((group) => group.items ?? []).every((item) => item.icon)).toBe(true);
expect(settings?.items?.slice(-4).map((item) => item.id)).toEqual([
UI_NAV_IDS.adminSalesPipelineSettings,
UI_NAV_IDS.adminSalesLeadSettings,
UI_NAV_IDS.adminSalesFieldsTags,
UI_NAV_IDS.adminSalesTelephonySettings,
]);
expect(settings).toMatchObject({
isCollapsible: false,
activePaths: ["/settings"],
anyPermissions: expect.arrayContaining(["admin_identity.sessions.read", "admin.settings.general.view", "admin.settings.danger.reset"]),
});
expect(settings?.items?.slice(0, 3).map((item) => item.id)).toEqual([
"ui.nav.admin.settings.profile",
"ui.nav.admin.settings.adminUsers",
"ui.nav.admin.settings.adminRoles",
]);
expect(flattenSidebarItems(sidebar).map((item) => item.id)).not.toContain("ui.nav.admin.adminUsers");
expect(flattenSidebarItems(sidebar).map((item) => item.id)).not.toContain("ui.nav.admin.salesConfiguration");
});
it("gates lead automation settings with the smallest assignment permission", () => {
const settings = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null })).find((item) => item.id === "ui.nav.admin.sales.leadSettings");
expect(settings).toMatchObject({
path: "/settings/leads",
permission: "admin_sales.crm.assign",
});
});
it("exposes the personal today list with CRM read permission", () => {
const today = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null })).find((item) => item.id === "ui.nav.admin.sales.today");
expect(today).toMatchObject({
path: "/sales/tasks/today",
permission: "admin_sales.crm.read",
});
});
it("exposes telephony workspace and settings with their smallest permissions", () => {
const items = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null }));
expect(items.find((item) => item.id === "ui.nav.admin.sales.calls")).toMatchObject({
path: "/sales/calls",
permission: "admin_sales.phone.call",
});
expect(items.find((item) => item.id === "ui.nav.admin.sales.telephonySettings")).toMatchObject({
path: "/settings/telephony",
permission: "admin_sales.integrations.manage",
});
});
it("exposes tenantless platform contacts with CRM read permission", () => {
const contacts = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null })).find((item) => item.id === "ui.nav.admin.sales.contacts");
expect(contacts).toMatchObject({
path: "/sales/contacts",
permission: "admin_sales.crm.read",
});
});
it("exposes every VA-P28b data screen through its smallest permission", () => {
const items = flattenSidebarItems(AdminSidebar({ t, appConfiguration: null }));
expect(items.find((item) => item.id === "ui.nav.admin.sales.companies")).toMatchObject({
path: "/sales/companies",
permission: "admin_sales.crm.read",
});
expect(items.find((item) => item.id === "ui.nav.admin.sales.pipelineSettings")).toMatchObject({
path: "/settings/pipelines",
permission: "admin_sales.crm.write",
});
expect(items.find((item) => item.id === "ui.nav.admin.sales.fieldsTags")).toMatchObject({
path: "/settings/fields-tags",
permission: "admin_sales.crm.read",
});
expect(items.find((item) => item.id === "ui.nav.admin.sales.importExport")).toMatchObject({
path: "/sales/import-export",
permission: "admin_sales.crm.read",
});
});
it("only emits canonical admin sidebar paths backed by route files", () => {
const routePaths = collectAdminRoutePaths();
const sidebar = AdminSidebar({
@@ -1,4 +1,15 @@
import { SideBarItem } from "./SidebarItem";
import {
FeatherBuilding2,
FeatherCalendarDays,
FeatherDatabase,
FeatherKanbanSquare,
FeatherListTodo,
FeatherMail,
FeatherPhone,
FeatherTarget,
FeatherUsers,
} from "@subframe/core";
import { TFunction } from "i18next";
import IconDashboard from "~/components/layouts/icons/IconDashboard";
import MembershipCardIcon from "~/components/ui/icons/MembershipCardIcon";
@@ -7,17 +18,15 @@ import IconSettings from "~/components/layouts/icons/IconSettings";
import IconApp from "~/components/layouts/icons/IconApp";
import IconKeys from "~/components/layouts/icons/IconKeys";
import IconAnalytics from "~/components/layouts/icons/IconAnalytics";
import IconDocs from "~/components/layouts/icons/IconDocs";
import IconEmails from "~/components/layouts/icons/IconEmails";
import IconEvents from "~/components/layouts/icons/IconEvents";
import IconFeatureFlags from "~/components/layouts/icons/IconFeatureFlags";
import IconHelpDesk from "~/components/layouts/icons/IconHelpDesk";
import IconMetrics from "~/components/layouts/icons/IconMetrics";
import IconNotifications from "~/components/layouts/icons/IconNotifications";
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import type { PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
import { disabledPluginRouteSlugs } from "~/utils/app/PublicRouteSegments";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
const adminSidebarPath = (path?: string) => adminPath(path, { mode: "host-aware" });
const disabledAdminRouteSlugs = new Set<string>(disabledPluginRouteSlugs);
@@ -36,6 +45,23 @@ type Props = {
routing?: PublicDomainRoutingConfig;
};
function consolidatedPlatformItem(input: {
id: string;
title: string;
path: string;
icon: SideBarItem["icon"];
permission?: SideBarItem["permission"];
anyPermissions?: SideBarItem["anyPermissions"];
contextItems: SideBarItem[];
}): SideBarItem {
return {
...input,
activePaths: input.contextItems.map((item) => item.path),
isCollapsible: false,
items: input.contextItems,
};
}
export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
{
id: "ui.nav.admin.primary",
@@ -47,6 +73,7 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
title: t("app.sidebar.dashboard"),
path: adminSidebarPath("dashboard"),
icon: <IconDashboard />,
permission: ADMIN_AREA_ACCESS.dashboard,
},
],
},
@@ -86,13 +113,6 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
items: [],
permission: "admin.accounts.view",
},
{
id: "ui.nav.admin.accounts.billing",
title: t("admin.billing.title"),
path: adminSidebarPath("accounts/billing"),
items: [],
permission: "admin.account.subscription",
},
{
id: "ui.nav.admin.accounts.rolesAndPermissions",
title: t("app.sidebar.rolesAndPermissions"),
@@ -116,6 +136,7 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
},
],
permission: "admin.accounts.view",
excludePaths: [adminSidebarPath("accounts/billing")],
},
{
id: UI_NAV_IDS.adminAudit,
@@ -124,11 +145,16 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
icon: <IconEvents />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.audit.viewer", title: t("app.sidebar.audit"), path: adminSidebarPath("audit"), permission: "admin.auditTrails.view" },
{ id: "ui.nav.admin.audit.trails", title: t("app.sidebar.auditTrails"), path: adminSidebarPath("audit-trails"), permission: "admin.auditTrails.view" },
{ id: "ui.nav.admin.audit.viewer", title: t("app.sidebar.audit"), path: adminSidebarPath("audit"), permission: "admin_identity.audit.read" },
{
id: "ui.nav.admin.audit.trails",
title: t("app.sidebar.auditTrails"),
path: adminSidebarPath("audit-trails"),
permission: "admin.auditTrails.view",
},
{ id: "ui.nav.admin.audit.events", title: t("models.event.plural"), path: adminSidebarPath("events"), permission: "admin.events.view" },
],
permission: "admin.auditTrails.view",
anyPermissions: ["admin.auditTrails.view", "admin_identity.audit.read"],
},
{
id: UI_NAV_IDS.adminNotifications,
@@ -137,9 +163,24 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
icon: <IconNotifications />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.notifications.messages", title: t("app.sidebar.messages"), path: adminSidebarPath("notifications/messages"), permission: "admin.notifications.view" },
{ id: "ui.nav.admin.notifications.channels", title: t("app.sidebar.channels"), path: adminSidebarPath("notifications/channels"), permission: "admin.notifications.view" },
{ id: "ui.nav.admin.notifications.subscribers", title: t("app.sidebar.subscribers"), path: adminSidebarPath("notifications/subscribers"), permission: "admin.notifications.view" },
{
id: "ui.nav.admin.notifications.messages",
title: t("app.sidebar.messages"),
path: adminSidebarPath("notifications/messages"),
permission: "admin.notifications.view",
},
{
id: "ui.nav.admin.notifications.channels",
title: t("app.sidebar.channels"),
path: adminSidebarPath("notifications/channels"),
permission: "admin.notifications.view",
},
{
id: "ui.nav.admin.notifications.subscribers",
title: t("app.sidebar.subscribers"),
path: adminSidebarPath("notifications/subscribers"),
permission: "admin.notifications.view",
},
],
permission: "admin.notifications.view",
},
@@ -150,33 +191,175 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
title: t("segments.platform"),
path: "",
items: [
consolidatedPlatformItem({
id: "ui.nav.admin.platform.operations",
title: t("admin.platformNavigation.operations"),
path: adminSidebarPath("system"),
icon: <IconMetrics />,
anyPermissions: [ADMIN_AREA_ACCESS.health, "admin.events.view", "admin.account.subscription"],
contextItems: [
{
id: "ui.nav.admin.health",
title: t("admin.health.title"),
path: adminSidebarPath("system"),
permission: ADMIN_AREA_ACCESS.health,
},
{
id: "ui.nav.admin.system",
title: t("admin.system.title"),
path: adminSidebarPath("system/health"),
permission: ADMIN_AREA_ACCESS.system,
},
{
id: "ui.nav.admin.deploys",
title: t("admin.deploys.title"),
path: adminSidebarPath("system/deploys"),
permission: ADMIN_AREA_ACCESS.deploys,
},
{
id: "ui.nav.admin.jobs",
title: t("admin.jobs.title"),
path: adminSidebarPath("system/jobs"),
permission: ADMIN_AREA_ACCESS.jobs,
},
{
id: "ui.nav.admin.webhooks",
title: t("admin.webhooks.title"),
path: adminSidebarPath("system/webhooks"),
permission: "admin.events.view",
},
{
id: "ui.nav.admin.billingSync",
title: t("admin.health.subsystems.billing.label"),
path: adminSidebarPath("system/billing"),
permission: "admin.account.subscription",
},
],
}),
consolidatedPlatformItem({
id: "ui.nav.admin.platform.support",
title: t("admin.platformNavigation.support"),
path: adminSidebarPath("support"),
icon: <IconEmails />,
anyPermissions: [ADMIN_AREA_ACCESS.support, "admin.metrics.view"],
contextItems: [
{
id: UI_NAV_IDS.adminHelpDesk,
title: t("admin.supportInbox.title"),
path: adminSidebarPath("support"),
permission: ADMIN_AREA_ACCESS.support,
},
{
id: "ui.nav.admin.kwpContracts",
title: t("admin.kwpContracts.title"),
path: adminSidebarPath("support/kwp-contracts"),
permission: "admin.metrics.view",
},
],
}),
{
id: UI_NAV_IDS.adminApi,
title: t("settings.api.title"),
title: t("admin.platformNavigation.apiAccess"),
path: adminSidebarPath("api"),
icon: <IconKeys />,
permission: "admin.apiKeys.view",
hidden: !appConfiguration?.app.features.tenantApiKeys,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.api.overview", title: t("shared.overview"), path: adminSidebarPath("api"), permission: "admin.apiKeys.view" },
{ id: "ui.nav.admin.api.keys", title: t("app.sidebar.apiKeys"), path: adminSidebarPath("api/keys"), permission: "admin.apiKeys.view" },
{ id: "ui.nav.admin.api.logs", title: t("app.sidebar.logs"), path: adminSidebarPath("api/logs"), permission: "admin.apiKeys.view" },
{ id: "ui.nav.admin.api.clients", title: t("admin.apiAdmin.tabs.clients"), path: adminSidebarPath("api/clients"), permission: "admin.apiKeys.view" },
{
id: "ui.nav.admin.api.inbound",
title: t("admin.apiAdmin.tabs.inbound"),
path: adminSidebarPath("api/inbound-registrations"),
permission: "admin.apiKeys.view",
},
],
},
{
id: UI_NAV_IDS.adminFeatureFlags,
title: t("app.sidebar.featureFlags"),
path: adminSidebarPath("feature-flags"),
icon: <IconFeatureFlags />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.featureFlags.flags", title: t("app.sidebar.flags"), path: adminSidebarPath("feature-flags/flags"), permission: "admin.featureFlags.view" },
{ id: "ui.nav.admin.featureFlags.settings", title: t("app.sidebar.settings"), path: adminSidebarPath("feature-flags/settings"), permission: "admin.featureFlags.view" },
],
permission: "admin.featureFlags.view",
},
],
},
{
id: UI_NAV_IDS.adminSales,
title: t("admin.sales.navigation.title"),
path: adminSidebarPath("sales/tasks/today"),
icon: <IconAnalytics />,
items: [
{
id: UI_NAV_IDS.adminSalesToday,
title: t("admin.sales.navigation.today"),
path: adminSidebarPath("sales/tasks/today"),
icon: <FeatherListTodo />,
permission: ADMIN_AREA_ACCESS.sales,
},
{
id: UI_NAV_IDS.adminPlatformLeads,
title: t("admin.sales.navigation.leads"),
path: adminSidebarPath("leads"),
icon: <FeatherTarget />,
permission: "admin_sales.crm.read",
},
{
id: UI_NAV_IDS.adminSalesDeals,
title: t("admin.sales.navigation.deals"),
path: adminSidebarPath("sales/deals"),
icon: <FeatherKanbanSquare />,
permission: "admin_sales.crm.read",
},
{
id: UI_NAV_IDS.adminSalesContacts,
title: t("admin.sales.navigation.contacts"),
path: adminSidebarPath("sales/contacts"),
icon: <FeatherUsers />,
permission: "admin_sales.crm.read",
},
{
id: UI_NAV_IDS.adminSalesCompanies,
title: t("admin.sales.navigation.companies"),
path: adminSidebarPath("sales/companies"),
icon: <FeatherBuilding2 />,
permission: "admin_sales.crm.read",
},
{
id: UI_NAV_IDS.adminSalesImportExport,
title: t("admin.sales.navigation.importExport"),
path: adminSidebarPath("sales/import-export"),
icon: <FeatherDatabase />,
permission: "admin_sales.crm.read",
},
],
anyPermissions: [ADMIN_AREA_ACCESS.sales],
},
{
id: UI_NAV_IDS.adminSalesCommunication,
title: t("admin.sales.navigation.communicationSection"),
path: adminSidebarPath("sales/email/inbox"),
items: [
{
id: UI_NAV_IDS.adminSalesEmail,
title: t("admin.sales.navigation.email"),
path: adminSidebarPath("sales/email/inbox"),
icon: <FeatherMail />,
permission: "admin_sales.email.send",
},
{
id: UI_NAV_IDS.adminSalesCalls,
title: t("admin.sales.navigation.calls"),
path: adminSidebarPath("sales/calls"),
icon: <FeatherPhone />,
permission: "admin_sales.phone.call",
},
{
id: UI_NAV_IDS.adminSalesBookings,
title: t("admin.sales.navigation.bookings"),
path: adminSidebarPath("sales/bookings"),
icon: <FeatherCalendarDays />,
permission: "admin_sales.booking.manage",
},
],
anyPermissions: ["admin_sales.email.send", "admin_sales.phone.call", "admin_sales.booking.manage"],
},
{
id: "ui.nav.admin.market",
title: t("segments.market"),
@@ -189,48 +372,49 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
icon: <IconEmails />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.emailMarketing.campaigns", title: t("app.sidebar.campaigns"), path: adminSidebarPath("email-marketing/campaigns"), permission: "admin.emails.view" },
{ id: "ui.nav.admin.emailMarketing.senders", title: t("app.sidebar.senders"), path: adminSidebarPath("email-marketing/senders"), permission: "admin.emails.view" },
{ id: "ui.nav.admin.emailMarketing.activity", title: t("app.sidebar.activity"), path: adminSidebarPath("email-marketing/activity"), permission: "admin.emails.view" },
{
id: "ui.nav.admin.emailMarketing.campaigns",
title: t("app.sidebar.campaigns"),
path: adminSidebarPath("email-marketing/campaigns"),
permission: "admin.emails.view",
},
{
id: "ui.nav.admin.emailMarketing.senders",
title: t("app.sidebar.senders"),
path: adminSidebarPath("email-marketing/senders"),
permission: "admin.emails.view",
},
{
id: "ui.nav.admin.emailMarketing.activity",
title: t("app.sidebar.activity"),
path: adminSidebarPath("email-marketing/activity"),
permission: "admin.emails.view",
},
],
permission: "admin.emails.view",
}),
{
id: UI_NAV_IDS.adminMarketing,
title: t("app.sidebar.marketing"),
path: adminSidebarPath("marketing-leads"),
path: adminSidebarPath("marketing-integrations"),
icon: <IconAnalytics />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.marketing.leads", title: t("app.sidebar.leads"), path: adminSidebarPath("marketing-leads"), permission: "admin.marketing.leads.view" },
{ id: "ui.nav.admin.marketing.funnels", title: t("app.sidebar.funnels"), path: adminSidebarPath("marketing-funnels"), permission: "admin.marketing.funnels.view" },
{ id: "ui.nav.admin.marketing.integrations", title: t("app.sidebar.integrations"), path: adminSidebarPath("marketing-integrations"), permission: "admin.marketing.integrations.view" },
{ id: "ui.nav.admin.marketing.emailSequences", title: t("app.sidebar.emailSequences"), path: adminSidebarPath("email-sequences"), permission: "admin.marketing.leads.view" },
{
id: "ui.nav.admin.marketing.integrations",
title: t("app.sidebar.integrations"),
path: adminSidebarPath("marketing-integrations"),
permission: "admin.marketing.integrations.view",
},
{
id: "ui.nav.admin.marketing.emailSequences",
title: t("app.sidebar.emailSequences"),
path: adminSidebarPath("email-sequences"),
permission: "admin.marketing.leads.view",
},
],
permission: "admin.marketing.leads.view",
},
...enabledAdminRouteItem("knowledge-base", {
id: UI_NAV_IDS.adminKnowledgeBase,
title: t("app.sidebar.knowledgeBase"),
path: adminSidebarPath("knowledge-base"),
icon: <IconDocs className="size-4" />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.knowledgeBase.bases", title: t("app.sidebar.bases"), path: adminSidebarPath("knowledge-base/bases"), permission: "admin.kb.view" },
{ id: "ui.nav.admin.knowledgeBase.articles", title: t("app.sidebar.articles"), path: adminSidebarPath("knowledge-base/articles"), permission: "admin.kb.view" },
],
permission: "admin.kb.view",
}),
...enabledAdminRouteItem("help-desk", {
id: UI_NAV_IDS.adminHelpDesk,
title: t("app.sidebar.helpDesk"),
path: adminSidebarPath("help-desk"),
icon: <IconHelpDesk className="size-4" />,
isCollapsible: true,
items: [
{ id: "ui.nav.admin.helpDesk.feedback", title: t("app.sidebar.feedback"), path: adminSidebarPath("help-desk/feedback") },
],
}),
],
},
{
@@ -244,11 +428,53 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
title: t("app.sidebar.settings"),
icon: <IconSettings />,
path: adminSidebarPath("settings"),
isCollapsible: true,
anyPermissions: [
"admin_identity.sessions.read",
"admin_identity.users.read",
"admin_identity.roles.read",
"admin.settings.general.view",
"admin.pricing.view",
"admin.settings.authentication.view",
"admin.emails.view",
"admin_sales.crm.write",
"admin_sales.crm.assign",
"admin_sales.crm.read",
"admin_sales.integrations.manage",
"admin.settings.danger.reset",
],
isCollapsible: false,
activePaths: [adminSidebarPath("settings")],
items: [
{ id: "ui.nav.admin.settings.profile", title: t("settings.admin.profile.title"), path: adminSidebarPath("settings/profile") },
{ id: "ui.nav.admin.settings.general", title: t("settings.admin.general.title"), path: adminSidebarPath("settings/general"), permission: "admin.settings.general.view" },
{ id: "ui.nav.admin.settings.pricing", title: t("settings.admin.pricing.title"), path: adminSidebarPath("settings/pricing"), permission: "admin.pricing.view" },
{
id: "ui.nav.admin.settings.profile",
title: t("admin.sales.security.title"),
path: adminSidebarPath("settings/security"),
permission: "admin_identity.sessions.read",
},
{
id: "ui.nav.admin.settings.adminUsers",
title: t("admin.sales.adminUsers.title"),
path: adminSidebarPath("settings/admin-users"),
permission: ADMIN_AREA_ACCESS.employees,
},
{
id: "ui.nav.admin.settings.adminRoles",
title: t("admin.sales.adminRoles.title"),
path: adminSidebarPath("settings/admin-roles"),
permission: ADMIN_AREA_ACCESS.roles,
},
{
id: "ui.nav.admin.settings.general",
title: t("settings.admin.general.title"),
path: adminSidebarPath("settings/general"),
permission: "admin.settings.general.view",
},
{
id: "ui.nav.admin.settings.pricing",
title: t("settings.admin.pricing.title"),
path: adminSidebarPath("settings/pricing"),
permission: "admin.pricing.view",
},
{
id: "ui.nav.admin.settings.authentication",
title: t("settings.admin.authentication.title"),
@@ -261,9 +487,30 @@ export const AdminSidebar = ({ t, appConfiguration }: Props): SideBarItem[] => [
path: adminSidebarPath("settings/transactional-emails"),
permission: "admin.emails.view",
},
{ id: "ui.nav.admin.settings.accountTypes", title: t("settings.admin.tenants.types.title"), path: adminSidebarPath("settings/accounts/types"), permission: "admin.accountTypes.view" },
{ id: "ui.nav.admin.settings.cookies", title: t("settings.admin.cookies.title"), path: adminSidebarPath("settings/cookies"), permission: "admin.settings.cookies.view" },
{ id: "ui.nav.admin.settings.cache", title: t("settings.admin.cache.title"), path: adminSidebarPath("settings/cache"), permission: "admin.settings.general.update" },
{
id: UI_NAV_IDS.adminSalesPipelineSettings,
title: t("admin.sales.navigation.pipelineSettings"),
path: adminSidebarPath("settings/pipelines"),
permission: "admin_sales.crm.write",
},
{
id: UI_NAV_IDS.adminSalesLeadSettings,
title: t("admin.sales.navigation.leadSettings"),
path: adminSidebarPath("settings/leads"),
permission: "admin_sales.crm.assign",
},
{
id: UI_NAV_IDS.adminSalesFieldsTags,
title: t("admin.sales.navigation.fieldsTags"),
path: adminSidebarPath("settings/fields-tags"),
permission: "admin_sales.crm.read",
},
{
id: UI_NAV_IDS.adminSalesTelephonySettings,
title: t("admin.sales.navigation.telephonySettings"),
path: adminSidebarPath("settings/telephony"),
permission: "admin_sales.integrations.manage",
},
],
},
{
@@ -41,6 +41,17 @@ describe("AppSidebar", () => {
"workflow-engine": { allowed: true },
"ai-credits": { allowed: true },
};
const fullProductAccess = {
...businessProductAccess,
leads: { allowed: true },
tasks: { allowed: true },
files: { allowed: true },
hr: { allowed: true },
forms: { allowed: true },
booking: { allowed: true },
integrations: { allowed: true },
chat: { allowed: true },
};
it("returns the expected static sidebar items", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
@@ -48,7 +59,9 @@ describe("AppSidebar", () => {
const result = AppSidebar({ t, i18n, tenantId: "test-user", appConfiguration: null });
const serialized = JSON.stringify(result);
const secondary = result.find((group) => group.isSecondary);
expect(result).toEqual(expect.arrayContaining([expect.objectContaining({ id: "ui.nav.app.overview", title: "" })]));
expect(result[0].items).toEqual(
expect.arrayContaining([
expect.objectContaining({
@@ -56,14 +69,9 @@ describe("AppSidebar", () => {
title: "app.sidebar.dashboard",
path: "/test-user/dashboard",
}),
expect.objectContaining({
id: UI_NAV_IDS.appNotifications,
title: "app.sidebar.notifications",
path: "/test-user/notifications",
}),
])
);
expect(result[1]).toMatchObject({
expect(secondary).toMatchObject({
title: "",
path: "",
isSecondary: true,
@@ -88,6 +96,8 @@ describe("AppSidebar", () => {
expect(serialized).not.toContain("/admin/");
expect(serialized).not.toContain("/blog");
expect(serialized).not.toContain("/pricing");
expect(serialized).not.toContain("/search");
expect(serialized).not.toContain("/notifications");
expect(serialized).not.toContain("/email-marketing");
expect(serialized).not.toContain("/workflow-engine");
expect(serialized).not.toContain("/widgets");
@@ -95,13 +105,48 @@ describe("AppSidebar", () => {
expect(serialized).not.toContain("/sites/");
});
it("groups plan-backed product links into clear app navigation sections", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const result = AppSidebar({ t, i18n, tenantId: "business", appConfiguration: null, productAccess: businessProductAccess });
expect(result).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "ui.nav.app.overview", title: "" }),
expect.objectContaining({ id: "ui.nav.app.customers", title: "app.sidebar.sections.customers" }),
expect.objectContaining({ id: "ui.nav.app.projects", title: "app.sidebar.sections.projects" }),
expect.objectContaining({ id: "ui.nav.app.communication", title: "app.sidebar.sections.communication" }),
expect.objectContaining({ id: "ui.nav.app.automationPlatform", title: "app.sidebar.sections.automationPlatform" }),
])
);
expect(result.find((group) => group.id === "ui.nav.app.overview")?.items?.map((item) => item.id)).toEqual([UI_NAV_IDS.appDashboard]);
expect(result.find((group) => group.id === "ui.nav.app.customers")?.items?.map((item) => item.id)).toEqual([UI_NAV_IDS.appCrm]);
expect(result.find((group) => group.id === "ui.nav.app.projects")?.items?.map((item) => item.id)).toEqual([
UI_NAV_IDS.appProjects,
UI_NAV_IDS.appPlantafel,
]);
expect(result.find((group) => group.id === "ui.nav.app.communication")?.items?.map((item) => item.id)).toEqual([
UI_NAV_IDS.appEmails,
UI_NAV_IDS.appEmailMarketing,
]);
expect(result.find((group) => group.id === "ui.nav.app.automationPlatform")?.items?.map((item) => item.id)).toEqual([UI_NAV_IDS.appAutomation]);
expect(result.find((group) => group.id === "ui.nav.app.apiDeveloper")).toBeUndefined();
});
it("renders plan-backed core feature links from product access decisions", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const starter = JSON.stringify(AppSidebar({ t, i18n, tenantId: "starter", appConfiguration: null, productAccess: starterProductAccess }));
const pro = JSON.stringify(AppSidebar({ t, i18n, tenantId: "pro", appConfiguration: null, productAccess: proProductAccess }));
const business = JSON.stringify(AppSidebar({ t, i18n, tenantId: "business", appConfiguration: null, productAccess: businessProductAccess }));
const starterResult = AppSidebar({ t, i18n, tenantId: "starter", appConfiguration: null, productAccess: starterProductAccess });
const proResult = AppSidebar({ t, i18n, tenantId: "pro", appConfiguration: null, productAccess: proProductAccess });
const businessResult = AppSidebar({ t, i18n, tenantId: "business", appConfiguration: null, productAccess: businessProductAccess });
const starter = JSON.stringify(starterResult);
const pro = JSON.stringify(proResult);
const business = JSON.stringify(businessResult);
const primaryPaths = (groups: ReturnType<typeof AppSidebar>) =>
groups.filter((group) => !group.isSecondary).flatMap((group) => group.items?.map((item) => item.path) ?? []);
expect(starter).toContain("/starter/contacts");
expect(starter).toContain("/starter/projects");
@@ -109,7 +154,7 @@ describe("AppSidebar", () => {
expect(starter).not.toContain("/starter/email-marketing");
expect(starter).not.toContain("/starter/emails");
expect(starter).not.toContain("/starter/automations");
expect(starter).not.toContain("/starter/settings/api");
expect(primaryPaths(starterResult)).not.toContain("/starter/api");
expect(starter).not.toContain("/starter/workflow-engine");
expect(pro).toContain("/pro/contacts");
@@ -117,15 +162,122 @@ describe("AppSidebar", () => {
expect(pro).toContain("/pro/email-marketing");
expect(pro).toContain("/pro/emails");
expect(pro).not.toContain("/pro/automations");
expect(pro).toContain("/pro/settings/api");
expect(primaryPaths(proResult)).not.toContain("/pro/api");
expect(pro).not.toContain("/pro/workflow-engine");
expect(business).toContain("/business/contacts");
expect(business).toContain("/business/projects");
expect(business).toContain("/business/email-marketing");
expect(business).toContain("/business/automations");
expect(business).toContain("/business/settings/api");
expect(business).toContain("/business/workflow-engine");
expect(primaryPaths(businessResult)).not.toContain("/business/api");
expect(business).not.toContain("/business/workflow-engine");
});
it("shows telephony only with product access and carries the read permission gate", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const withoutTelephony = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null, productAccess: businessProductAccess });
const withTelephony = AppSidebar({
t,
i18n,
tenantId: "acme",
appConfiguration: null,
productAccess: { ...businessProductAccess, telephony: { allowed: true } },
});
expect(JSON.stringify(withoutTelephony)).not.toContain("/acme/calls");
expect(withTelephony.flatMap((group) => group.items ?? [])).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: UI_NAV_IDS.appTelephony,
title: "telephony.nav.title",
path: "/acme/calls",
permission: "telephony.read_own",
}),
])
);
});
it("shows team chat only with product access and carries the member read gate", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const withoutChat = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null, productAccess: businessProductAccess });
const withChat = AppSidebar({
t,
i18n,
tenantId: "acme",
appConfiguration: null,
productAccess: { ...businessProductAccess, chat: { allowed: true } },
});
expect(JSON.stringify(withoutChat)).not.toContain("/acme/chat");
expect(withChat.flatMap((group) => group.items ?? [])).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: UI_NAV_IDS.appChat,
title: "chat.nav.title",
path: "/acme/chat",
permission: "chat.read_own_channels",
}),
])
);
});
it("keeps balanced global destinations while consolidating the appointment area", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const result = AppSidebar({ t, i18n, tenantId: "full", appConfiguration: null, productAccess: fullProductAccess });
const globalItems = result.filter((group) => !group.isSecondary).flatMap((group) => group.items ?? []);
expect(globalItems.map((item) => item.id)).toEqual([
UI_NAV_IDS.appDashboard,
"ui.nav.app.tasks",
UI_NAV_IDS.appCrm,
UI_NAV_IDS.appLeads,
UI_NAV_IDS.appProjects,
UI_NAV_IDS.appPlantafel,
"ui.nav.app.files",
UI_NAV_IDS.appEmails,
UI_NAV_IDS.appEmailMarketing,
UI_NAV_IDS.appForms,
"ui.nav.app.appointments",
UI_NAV_IDS.appChat,
"ui.nav.app.hr",
UI_NAV_IDS.appPasswordSafe,
UI_NAV_IDS.appAutomation,
]);
// WF-P8 S00: boards start page is the consolidated module entry, so the
// projects group is back to at most three entries.
expect(result.find((group) => group.id === "ui.nav.app.projects")?.items).toHaveLength(3);
expect(globalItems.find((item) => item.id === "ui.nav.app.appointments")?.contextItems).toHaveLength(3);
expect(globalItems.find((item) => item.id === UI_NAV_IDS.appPasswordSafe)).toMatchObject({
path: "/full/passwords",
anyPermissions: ["hr.passwordsafe.use", "hr.passwordsafe.admin"],
});
});
it("reaches the lead statistics through the leads sub-sidenav, not through the inbox screen", () => {
const t = vi.fn().mockImplementation((v: string) => v) as any;
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const result = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null, productAccess: fullProductAccess });
const leads = result.flatMap((group) => group.items ?? []).find((item) => item.id === UI_NAV_IDS.appLeads);
expect(leads?.contextItems?.map((item) => item.path)).toEqual([
"/acme/leads",
"/acme/leads-statistics",
"/acme/admin/lead-sources",
"/acme/admin/lead-anti-spam",
]);
// Same permission as the inbox: everyone who sees leads sees their statistics.
expect(leads?.contextItems?.find((item) => item.id === "ui.nav.app.leads.statistics")).toMatchObject({
title: "leads.statistics.title",
permission: "leads.read_own",
});
// The statistics path must stay highlighted as part of the leads workspace —
// that is also what puts "Leads" in front of the breadcrumb.
expect(leads?.activePaths).toContain("/acme/leads-statistics");
expect(existsSync(resolveRepoPath("apps/web/app/routes/app.$tenant/leads-statistics.tsx"))).toBe(true);
});
it("keeps static tenant sidebar targets backed by registered route files", () => {
@@ -133,15 +285,16 @@ describe("AppSidebar", () => {
const i18n = { exists: vi.fn().mockReturnValue(false) } as any;
const result = AppSidebar({ t, i18n, tenantId: "acme", appConfiguration: null, productAccess: businessProductAccess });
const serialized = JSON.stringify(result);
const primaryPaths = result.filter((group) => !group.isSecondary).flatMap((group) => group.items?.map((item) => item.path) ?? []);
expect(serialized).toContain("/acme/dashboard");
expect(serialized).toContain("/acme/notifications");
expect(serialized).not.toContain("/acme/notifications");
expect(serialized).toContain("/acme/contacts");
expect(serialized).toContain("/acme/projects");
expect(serialized).toContain("/acme/automations");
expect(serialized).toContain("/acme/email-marketing");
expect(serialized).toContain("/acme/workflow-engine");
expect(serialized).toContain("/acme/settings/api");
expect(serialized).not.toContain("/acme/workflow-engine");
expect(primaryPaths).not.toContain("/acme/api");
expect(serialized).not.toContain("/acme/settings/credits");
expect(serialized).toContain("/acme/settings");
expect(serialized).toContain("/acme/settings/profile");
@@ -150,15 +303,12 @@ describe("AppSidebar", () => {
[
"apps/web/app/routes/app.$tenant/dashboard.tsx",
"apps/web/app/routes/app.$tenant/notifications.tsx",
"apps/web/app/routes/app.$tenant/contacts._index.tsx",
"apps/web/app/routes/app.$tenant/projects._index.tsx",
"apps/web/app/routes/app.$tenant/automations._index.tsx",
"apps/web/app/routes/app.$tenant/automations.$id.edit.tsx",
"apps/web/app/routes/app.$tenant/automations.templates._index.tsx",
"apps/web/app/routes/app.$tenant/email-marketing.tsx",
"apps/web/app/routes/app.$tenant/__workflows/workflow-engine.tsx",
"apps/web/app/routes/app.$tenant/settings/api/index.tsx",
"apps/web/app/routes/app.$tenant/settings.tsx",
"apps/web/app/routes/app.$tenant/settings/profile.tsx",
].forEach((routeFile) => {
@@ -4,20 +4,26 @@ import { AppConfiguration } from "~/utils/db/appConfiguration.db.server";
import IconSettings from "~/components/layouts/icons/IconSettings";
import IconDashboard from "~/components/layouts/icons/IconDashboard";
import IconAdmin from "~/components/layouts/icons/IconAdmin";
import IconNotifications from "~/components/layouts/icons/IconNotifications";
import IconEmails from "~/components/layouts/icons/IconEmails";
import IconKeys from "~/components/layouts/icons/IconKeys";
import IconWorkflows from "~/components/layouts/icons/IconWorkflows";
import AddressBookIcon from "~/components/ui/icons/crm/AddressBookIcon";
import IconDocs from "~/components/layouts/icons/IconDocs";
import ViewListIcon from "~/components/ui/icons/ViewListIcon";
import CalendarIcon from "~/components/ui/icons/CalendarIcon";
import CalendarCheckIcon from "~/components/ui/icons/CalendarCheckIcon";
import CalendarClockIcon from "~/components/ui/icons/CalendarClockIcon";
import CalendarDaysIcon from "~/components/ui/icons/CalendarDaysIcon";
import CalendarRangeIcon from "~/components/ui/icons/CalendarRangeIcon";
import InboxIcon from "~/components/ui/icons/emails/InboxIcon";
import MegaphoneIcon from "~/components/ui/icons/emails/MegaphoneIcon";
import { UI_NAV_IDS } from "~/application/ui/uiRegistry";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAdminPath, type PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
import { resolveConnectorNavState } from "~/utils/connector/connectorNavState";
import { WALKING_SKELETON_MODULE_KEY } from "~/modules/walkingSkeleton/constants";
import { SearchIcon } from "~/components/ui/icons/vendor";
import { ClipboardIcon, FileTextIcon, LockIcon, PhoneIcon, ShieldCheckIcon, TrendingUpIcon, UserIcon } from "~/components/ui/icons/vendor";
import BoardIcon from "~/components/ui/icons/BoardIcon";
import ComboChartIcon from "~/components/ui/icons/ComboChartIcon";
import DataSourceIcon from "~/components/ui/icons/DataSourceIcon";
import TableIcon from "~/components/ui/icons/TableIcon";
import ChatAltIcon from "~/components/ui/icons/ChatAltIcon";
type Props = {
t: TFunction;
@@ -36,35 +42,27 @@ export const AppSidebar = ({ t, tenantId, routing, productAccess }: Props): Side
const walkingSkeletonDecision = productAccess?.[WALKING_SKELETON_MODULE_KEY];
const walkingSkeletonState = walkingSkeletonDecision ? resolveConnectorNavState(walkingSkeletonDecision) : "hidden";
const productCoreItems: SideBarItem[] = [
...(hasFeatureAccess("search")
const overviewItems: SideBarItem[] = [
...(hasDashboardAccess
? [
{
id: UI_NAV_IDS.appSearch,
title: t("search.nav.title"),
path: tenantPath("search"),
icon: <SearchIcon />,
permission: "search.use" as const,
},
]
: []),
...(hasFeatureAccess("automation")
? [
{
id: UI_NAV_IDS.appAutomation,
title: t("automation.nav.title"),
path: tenantPath("automations"),
icon: <IconWorkflows />,
permission: "automation.read" as const,
id: UI_NAV_IDS.appDashboard,
title: t("app.sidebar.dashboard"),
path: tenantPath("dashboard"),
icon: <IconDashboard />,
permission: "dashboard.read" as const,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN, TenantUserType.MEMBER],
},
]
: []),
];
const crmContextItems: SideBarItem[] = [
...(hasFeatureAccess("crm-basic")
? [
{
id: UI_NAV_IDS.appCrm,
title: t("crm:title"),
// R-P6: typed CRM contacts replace the entity-builder CRM (/crm → /contacts).
id: "ui.nav.app.crm.contacts",
title: t("crm.contacts.title"),
path: tenantPath("contacts"),
icon: <AddressBookIcon />,
permission: "crm.read_own" as const,
@@ -77,143 +75,280 @@ export const AppSidebar = ({ t, tenantId, routing, productAccess }: Props): Side
id: UI_NAV_IDS.appLeads,
title: t("leads.nav.title"),
path: tenantPath("leads"),
icon: <ViewListIcon />,
icon: <TrendingUpIcon />,
permission: "leads.read_own" as const,
// Leads is a workspace area: inbox/board plus the two admin screens
// share an inner sub-sidenav (rendered by app.$tenant when >1 item
// is visible — non-admins only see the inbox, so no rail for them).
activePaths: [tenantPath("leads"), tenantPath("leads-statistics"), tenantPath("admin/lead-sources"), tenantPath("admin/lead-anti-spam")],
contextItems: [
{
id: "ui.nav.app.leads.inbox",
title: t("leads.list.title"),
path: tenantPath("leads"),
icon: <InboxIcon />,
permission: "leads.read_own" as const,
},
{
id: "ui.nav.app.leads.statistics",
title: t("leads.statistics.title"),
path: tenantPath("leads-statistics"),
icon: <ComboChartIcon />,
permission: "leads.read_own" as const,
},
{
id: "ui.nav.app.leads.sources",
title: t("leads.sources.title"),
path: tenantPath("admin/lead-sources"),
icon: <DataSourceIcon />,
permission: "leads.admin" as const,
},
{
id: "ui.nav.app.leads.antiSpam",
title: t("leads.antiSpam.title"),
path: tenantPath("admin/lead-anti-spam"),
icon: <ShieldCheckIcon />,
permission: "leads.admin" as const,
},
],
},
]
: []),
];
const projectContextItems: SideBarItem[] = [
...(hasFeatureAccess("projects")
? [
{
id: UI_NAV_IDS.appProjects,
title: t("projects.nav.title"),
path: tenantPath("projects"),
icon: <ViewListIcon />,
// WF-P8 S00 (Subframe 2026-07-15): the boards start page is the
// module entry; the kanban/list/detail routes under /projects keep
// this consolidated entry highlighted via activePaths.
id: "ui.nav.app.projects.boards",
title: t("projects.boards.nav"),
path: tenantPath("projects/boards"),
icon: <BoardIcon />,
permission: "projects.read_own" as const,
activePaths: [tenantPath("projects")],
// Plantafel is its own sidebar entry but lives under /projects.
excludePaths: [tenantPath("projects/plantafel")],
},
]
: []),
...(hasFeatureAccess("files")
? [
{
id: "ui.nav.app.files",
title: t("files.nav.title"),
path: tenantPath("files"),
icon: <IconDocs />,
permission: "files.read_own" as const,
},
]
: []),
...(hasFeatureAccess("tasks")
? [
{
id: "ui.nav.app.tasks",
title: t("tasks.nav.title"),
path: tenantPath("tasks"),
icon: <ViewListIcon />,
permission: "tasks.read_own" as const,
},
]
: []),
...(hasFeatureAccess("hr")
? [
{
id: "ui.nav.app.hr",
title: t("hr.nav.title"),
path: tenantPath("hr"),
icon: <AddressBookIcon />,
permission: "hr.read_own" as const,
},
]
: []),
...(hasFeatureAccess("integrations")
? [
{
id: "ui.nav.app.integrations",
title: t("integrations.nav.title"),
path: tenantPath("integrations"),
icon: <IconWorkflows />,
permission: "integrations.read" as const,
},
]
: []),
...(hasFeatureAccess("integrations")
? [
{
// AK-P16a · calendar reuses the integrations feature gate (it is an
// Apps-Engine integration); the entry is gated by calendar.connect_own.
id: UI_NAV_IDS.appCalendar,
title: t("calendar.nav.title"),
path: tenantPath("calendar"),
icon: <CalendarIcon />,
permission: "calendar.connect_own" as const,
id: UI_NAV_IDS.appPlantafel,
title: t("projects.nav.plantafel"),
path: tenantPath("projects/plantafel"),
icon: <CalendarRangeIcon />,
permission: "plantafel.read_own" as const,
},
]
: []),
];
const communicationContextItems: SideBarItem[] = [
...(hasFeatureAccess("email-inbox")
? [
{
// VA-P23 · mailbox sync inbox — own `email-inbox` feature gate; the
// entry is gated by email.read_own (own-mailbox visibility, M09 I).
id: UI_NAV_IDS.appEmails,
title: t("emailInbox.nav.title"),
path: tenantPath("emails"),
icon: <IconEmails className="h-5 w-5" />,
icon: <IconEmails />,
permission: "email.read_own" as const,
},
]
: []),
...(hasFeatureAccess("booking")
? [
{
// AK-P16b · Booking module — own `booking` feature gate; the entry is
// gated by bookings.read_own (every provider can see their own bookings).
id: UI_NAV_IDS.appBookings,
title: t("bookings.nav.title"),
path: tenantPath("bookings"),
icon: <CalendarIcon />,
permission: "bookings.read_own" as const,
},
]
: []),
...(hasFeatureAccess("forms")
? [
{
id: UI_NAV_IDS.appForms,
title: t("settings.forms.admin.title"),
path: tenantPath("forms"),
icon: <ViewListIcon />,
permission: "forms.basic" as const,
},
]
: []),
...(hasFeatureAccess("email-marketing")
? [
{
id: UI_NAV_IDS.appEmailMarketing,
title: t("emailMarketing:title"),
path: tenantPath("email-marketing"),
icon: <IconEmails />,
icon: <MegaphoneIcon />,
permission: "emailMarketing.view" as const,
},
]
: []),
...(hasFeatureAccess("workflow-engine")
...(hasFeatureAccess("forms")
? [
{
id: UI_NAV_IDS.appWorkflowEngine,
title: t("workflows.title"),
path: tenantPath("workflow-engine"),
id: UI_NAV_IDS.appForms,
title: t("settings.forms.admin.title"),
path: tenantPath("forms"),
icon: <TableIcon />,
permission: "forms.basic" as const,
},
]
: []),
...(hasFeatureAccess("telephony")
? [
{
id: UI_NAV_IDS.appTelephony,
title: t("telephony.nav.title"),
path: tenantPath("calls"),
icon: <PhoneIcon />,
permission: "telephony.read_own" as const,
},
]
: []),
];
const appointmentContextItems: SideBarItem[] = [
...(hasFeatureAccess("integrations")
? [
{
id: UI_NAV_IDS.appCalendar,
title: t("calendar.nav.title"),
path: tenantPath("calendar"),
icon: <CalendarDaysIcon />,
permission: "calendar.connect_own" as const,
},
]
: []),
...(hasFeatureAccess("booking")
? [
{
id: UI_NAV_IDS.appBookings,
title: t("bookings.nav.title"),
path: tenantPath("bookings"),
icon: <CalendarCheckIcon />,
permission: "bookings.read_own" as const,
},
{
id: UI_NAV_IDS.appAvailability,
title: t("bookings.availability.title"),
path: tenantPath("availability"),
icon: <CalendarClockIcon />,
permission: "bookings.read_own" as const,
},
]
: []),
];
const workspaceArea = ({
id,
title,
icon,
contextItems,
}: {
id: string;
title: string;
icon: SideBarItem["icon"];
contextItems: SideBarItem[];
}): SideBarItem | null => {
const firstItem = contextItems[0];
if (!firstItem) return null;
return {
id,
title,
path: firstItem.path,
icon,
activePaths: contextItems.map((item) => item.path),
contextItems,
};
};
const appointmentsArea = workspaceArea({
id: "ui.nav.app.appointments",
title: t("app.sidebar.areas.appointments"),
icon: <CalendarDaysIcon />,
contextItems: appointmentContextItems,
});
const taskItems: SideBarItem[] = [
...(hasFeatureAccess("tasks")
? [
{
id: "ui.nav.app.tasks",
title: t("tasks.nav.title"),
path: tenantPath("tasks"),
icon: <ClipboardIcon />,
permission: "tasks.read_own" as const,
},
]
: []),
];
const fileItems: SideBarItem[] = [
...(hasFeatureAccess("files")
? [
{
id: "ui.nav.app.files",
title: t("files.nav.title"),
path: tenantPath("files"),
icon: <FileTextIcon />,
permission: "files.read_own" as const,
},
]
: []),
];
const hrItems: SideBarItem[] = [
...(hasFeatureAccess("hr")
? [
{
id: UI_NAV_IDS.appHr,
title: t("hr.nav.title"),
path: tenantPath("hr"),
icon: <UserIcon />,
permission: "hr.read_own" as const,
},
]
: []),
];
const passwordSafeItems: SideBarItem[] = [
...(hasFeatureAccess("hr")
? [
{
id: UI_NAV_IDS.appPasswordSafe,
title: t("hr.passwordSafe.title"),
path: tenantPath("passwords"),
icon: <LockIcon />,
anyPermissions: ["hr.passwordsafe.use" as const, "hr.passwordsafe.admin" as const],
activePaths: [tenantPath("passwords")],
contextItems: [
{
id: "ui.nav.app.passwordSafe.vaults",
title: t("hr.passwordSafe.nav.vaults"),
path: tenantPath("passwords"),
icon: <LockIcon />,
permission: "hr.passwordsafe.use" as const,
exact: true,
},
{
id: "ui.nav.app.passwordSafe.admin",
title: t("hr.passwordSafe.nav.admin"),
path: tenantPath("passwords/admin"),
icon: <ShieldCheckIcon />,
permission: "hr.passwordsafe.admin" as const,
},
],
},
]
: []),
];
const chatItems: SideBarItem[] = [
...(hasFeatureAccess("chat")
? [
{
id: UI_NAV_IDS.appChat,
title: t("chat.nav.title"),
path: tenantPath("chat"),
icon: <ChatAltIcon />,
permission: "chat.read_own_channels" as const,
},
]
: []),
];
const automationItems: SideBarItem[] = [
...(hasFeatureAccess("automation")
? [
{
id: UI_NAV_IDS.appAutomation,
title: t("automation.nav.title"),
path: tenantPath("automations"),
icon: <IconWorkflows />,
},
]
: []),
...(hasFeatureAccess("api")
? [
{
id: UI_NAV_IDS.appApi,
title: t("models.apiKey.plural"),
path: tenantPath("settings/api"),
icon: <IconKeys />,
permission: "automation.read" as const,
},
]
: []),
@@ -230,70 +365,81 @@ export const AppSidebar = ({ t, tenantId, routing, productAccess }: Props): Side
: []),
];
const appItem: SideBarItem = {
id: "ui.nav.app.primary",
const startItems = [...overviewItems, ...taskItems];
const customerItems = crmContextItems.map((item, index) => (index === 0 ? { ...item, id: UI_NAV_IDS.appCrm, title: t("crm:title") } : item));
const projectItems = [...projectContextItems.map((item, index) => (index === 0 ? { ...item, id: UI_NAV_IDS.appProjects } : item)), ...fileItems];
const organizationItems = [...(appointmentsArea ? [appointmentsArea] : []), ...chatItems, ...hrItems, ...passwordSafeItems];
const navigationGroups: SideBarItem[] = [
{
id: "ui.nav.app.overview",
title: "",
path: "",
items: startItems,
},
{
id: "ui.nav.app.customers",
title: t("app.sidebar.sections.customers"),
path: "",
items: customerItems,
},
{
id: "ui.nav.app.projects",
title: t("app.sidebar.sections.projects"),
path: "",
items: projectItems,
},
{
id: "ui.nav.app.communication",
title: t("app.sidebar.sections.communication"),
path: "",
items: communicationContextItems,
},
{
id: "ui.nav.app.organization",
title: t("app.sidebar.sections.organization"),
path: "",
items: organizationItems,
},
{
id: "ui.nav.app.automationPlatform",
title: t("app.sidebar.sections.automationPlatform"),
path: "",
items: automationItems,
},
].filter((group) => (group.items?.length ?? 0) > 0);
const secondaryItem: SideBarItem = {
id: "ui.nav.app.secondary",
title: "",
path: "",
isSecondary: true,
items: [
...(hasDashboardAccess
? [
{
id: UI_NAV_IDS.appDashboard,
title: t("app.sidebar.dashboard"),
path: tenantPath("dashboard"),
icon: <IconDashboard />,
permission: "dashboard.read" as const,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN, TenantUserType.MEMBER],
},
]
: []),
{
id: UI_NAV_IDS.appNotifications,
title: t("app.sidebar.notifications"),
path: tenantPath("notifications"),
icon: <IconNotifications />,
id: UI_NAV_IDS.appSettings,
title: t("app.sidebar.settings"),
icon: <IconSettings />,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN],
path: tenantPath("settings"),
redirectTo: tenantPath("settings/profile"),
},
...productCoreItems,
// {
// title: t("models.email.plural"),
// path: `${currentTenantUrl}/emails`,
// icon: SvgIcon.EMAILS,
// title: t("app.sidebar.logs"),
// icon: SvgIcon.LOGS,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN],
// path: `${currentTenantUrl}/logs`,
// },
{
id: UI_NAV_IDS.appSwitchToAdmin,
title: t("admin.switchToAdmin"),
path: absoluteAdminPath(routing, "dashboard"),
icon: <IconAdmin />,
adminOnly: true,
},
],
};
return [
appItem,
{
id: "ui.nav.app.secondary",
title: "",
path: "",
isSecondary: true,
items: [
{
id: UI_NAV_IDS.appSettings,
title: t("app.sidebar.settings"),
icon: <IconSettings />,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN],
path: tenantPath("settings"),
redirectTo: tenantPath("settings/profile"),
},
// {
// title: t("app.sidebar.logs"),
// icon: SvgIcon.LOGS,
// tenantUserTypes: [TenantUserType.OWNER, TenantUserType.ADMIN],
// path: `${currentTenantUrl}/logs`,
// },
{
id: UI_NAV_IDS.appSwitchToAdmin,
title: t("admin.switchToAdmin"),
path: absoluteAdminPath(routing, "dashboard"),
icon: <IconAdmin />,
adminOnly: true,
},
],
},
];
return [...navigationGroups, secondaryItem];
};
// function SideText({ text }: { text: string }) {
@@ -1,5 +1,5 @@
import { SideBarItem } from "./SidebarItem";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { UI_ID_PATTERNS, UI_NAV_IDS, uiIdSegment } from "~/application/ui/uiRegistry";
function withDocsSidebarIds(items: SideBarItem[], seenIds = new Map<string, number>()): SideBarItem[] {
@@ -274,26 +274,6 @@ export const DocsSidebar = (): SideBarItem[] => {
title: i18nT("docs.sidebar.supportLanguageI18n"),
path: "/docs/learning-center/guides/localization/support-a-language",
},
{
title: i18nT("docs.sidebar.createCustomEntity"),
path: "/docs/learning-center/guides/entities/create-a-custom-entity",
},
{
title: i18nT("docs.sidebar.useCustomEntityApi"),
path: "/docs/learning-center/guides/entities/use-the-custom-entity-api",
},
{
title: i18nT("docs.sidebar.sharedEntityRows"),
path: "/docs/learning-center/guides/entities/shared-entity-rows",
},
{
title: i18nT("docs.sidebar.planEntityLimits"),
path: "/docs/learning-center/guides/entities/plan-entity-limits",
},
{
title: i18nT("docs.sidebar.extendExistingModels"),
path: "/docs/learning-center/guides/entities/extend-existing-models",
},
{
title: i18nT("docs.sidebar.singleSignOn"),
path: "/docs/learning-center/guides/sso/",
@@ -47,6 +47,14 @@ describe("sidebar UI IDs", () => {
expectStaticItemsHaveIds(sidebar);
expect(ids).toContain(UI_NAV_IDS.adminDashboard);
expect(ids).toContain(UI_NAV_IDS.adminSettings);
expect(ids).toContain(UI_NAV_IDS.adminSalesCommunication);
expect(ids).toContain(UI_NAV_IDS.adminSalesLeadSettings);
expect(ids).toContain(UI_NAV_IDS.adminSalesToday);
expect(ids).toContain(UI_NAV_IDS.adminSalesEmail);
expect(ids).toContain(UI_NAV_IDS.adminSalesContacts);
expect(ids).toContain(UI_NAV_IDS.adminSalesCompanies);
expect(ids).toContain(UI_NAV_IDS.adminSalesFieldsTags);
expect(ids).toContain(UI_NAV_IDS.adminSalesImportExport);
});
it("assigns unique IDs to app sidebar static items", () => {
@@ -14,7 +14,15 @@ export interface SideBarItem {
adminOnly?: boolean;
tenantUserTypes?: TenantUserType[];
permission?: DefaultPermission;
/** Item is visible when at least one permission is granted. */
anyPermissions?: DefaultPermission[];
items?: SideBarItem[];
/** Alternate route roots that keep a consolidated navigation entry active. */
activePaths?: string[];
/** Route roots that must NOT activate this entry (sibling entries' subroutes under a broad activePaths prefix). */
excludePaths?: string[];
/** Links shown inside the workspace area instead of permanently in the global sidebar. */
contextItems?: SideBarItem[];
side?: ReactNode;
exact?: boolean;
redirectTo?: string;
@@ -1,8 +1,21 @@
import { describe, expect, it } from "vitest";
import { UI_NAV_IDS } from "./uiRegistry";
import { UI_ACTION_IDS, UI_ID_PATTERNS, UI_NAV_IDS, getCommandPaletteActionId, getCommandPaletteRecentId, getCommandPaletteResultId } from "./uiRegistry";
describe("UI_NAV_IDS", () => {
it("exposes the app notification nav id", () => {
expect(UI_NAV_IDS.appNotifications).toBe("ui.nav.app.notifications");
});
it("keeps desktop and mobile search triggers independently addressable", () => {
expect(UI_ACTION_IDS.search).toBe("ui.action.shell.search");
expect(UI_ACTION_IDS.searchMobile).toBe("ui.action.shell.searchMobile");
expect(UI_ACTION_IDS.searchMobile).not.toBe(UI_ACTION_IDS.search);
});
it("builds stable, unique Spotlight row ids from the registered patterns", () => {
expect(UI_ID_PATTERNS.commandPaletteResult).toBe("ui.surface.commandPalette.result.{entityType}.{entityId}");
expect(getCommandPaletteResultId("project", "project-42")).toBe("ui.surface.commandPalette.result.project.project42");
expect(getCommandPaletteRecentId("recent-42")).toBe("ui.surface.commandPalette.recent.recent42");
expect(getCommandPaletteActionId("open-settings")).toBe("ui.surface.commandPalette.action.openSettings");
});
});
@@ -17,13 +17,20 @@ export const UI_SURFACE_IDS = {
feedbackDialog: "ui.surface.shell.feedback.dialog",
commandPalettePortal: "ui.surface.commandPalette.portal",
commandPaletteSearch: "ui.surface.commandPalette.search",
commandPaletteFilters: "ui.surface.commandPalette.filters",
commandPaletteResults: "ui.surface.commandPalette.results",
commandPaletteRow: "ui.surface.commandPalette.row",
commandPaletteQueryHint: "ui.surface.commandPalette.queryHint",
commandPaletteSearchStatus: "ui.surface.commandPalette.searchStatus",
commandPaletteRecentStatus: "ui.surface.commandPalette.recentStatus",
commandPalettePermissionHint: "ui.surface.commandPalette.permissionHint",
commandPaletteFooter: "ui.surface.commandPalette.footer",
} as const;
export const UI_ACTION_IDS = {
sidebarTrigger: "ui.action.shell.sidebarTrigger",
search: "ui.action.shell.search",
searchMobile: "ui.action.shell.searchMobile",
commandPaletteLoadMore: "ui.action.commandPalette.loadMore",
aiAssistant: "ui.action.shell.aiAssistant",
aiAssistantExpand: "ui.action.shell.aiAssistant.expand",
aiAssistantClose: "ui.action.shell.aiAssistant.close",
@@ -40,20 +47,33 @@ export const UI_ACTION_IDS = {
export const UI_NAV_IDS = {
appDashboard: "ui.nav.app.dashboard",
appNotifications: "ui.nav.app.notifications",
appSearch: "ui.nav.app.search",
appAutomation: "ui.nav.app.automation",
appCrm: "ui.nav.app.crm",
appLeads: "ui.nav.app.leads",
appProjects: "ui.nav.app.projects",
appPlantafel: "ui.nav.app.plantafel",
appEmailMarketing: "ui.nav.app.emailMarketing",
appEmails: "ui.nav.app.emails",
appTelephony: "ui.nav.app.telephony",
appChat: "ui.nav.app.chat",
appHr: "ui.nav.app.hr",
appPasswordSafe: "ui.nav.app.passwordSafe",
appCalendar: "ui.nav.app.calendar",
appBookings: "ui.nav.app.bookings",
appAvailability: "ui.nav.app.availability",
appForms: "ui.nav.app.forms",
appBilling: "ui.nav.app.billing",
appApi: "ui.nav.app.api",
appWorkflowEngine: "ui.nav.app.workflowEngine",
appCredits: "ui.nav.app.credits",
appSettings: "ui.nav.app.settings",
appSettingsAccount: "ui.nav.app.settings.account",
appSettingsTeam: "ui.nav.app.settings.team",
appSettingsBilling: "ui.nav.app.settings.billing",
appSettingsWorkspace: "ui.nav.app.settings.workspace",
appSettingsCustomerPortal: "ui.nav.app.settings.customerPortal",
appSettingsIntegrations: "ui.nav.app.settings.integrations",
appSettingsCompliance: "ui.nav.app.settings.compliance",
appSwitchToAdmin: "ui.nav.app.switchToAdmin",
adminDashboard: "ui.nav.admin.dashboard",
adminAccounts: "ui.nav.admin.accounts",
@@ -64,6 +84,21 @@ export const UI_NAV_IDS = {
adminPrompts: "ui.nav.admin.prompts",
adminEmailMarketing: "ui.nav.admin.emailMarketing",
adminMarketing: "ui.nav.admin.marketing",
adminPlatformLeads: "ui.nav.admin.platformLeads",
adminSales: "ui.nav.admin.sales",
adminSalesCommunication: "ui.nav.admin.salesCommunication",
adminSalesContacts: "ui.nav.admin.sales.contacts",
adminSalesCompanies: "ui.nav.admin.sales.companies",
adminSalesDeals: "ui.nav.admin.sales.deals",
adminSalesToday: "ui.nav.admin.sales.today",
adminSalesEmail: "ui.nav.admin.sales.email",
adminSalesCalls: "ui.nav.admin.sales.calls",
adminSalesBookings: "ui.nav.admin.sales.bookings",
adminSalesTelephonySettings: "ui.nav.admin.sales.telephonySettings",
adminSalesLeadSettings: "ui.nav.admin.sales.leadSettings",
adminSalesPipelineSettings: "ui.nav.admin.sales.pipelineSettings",
adminSalesFieldsTags: "ui.nav.admin.sales.fieldsTags",
adminSalesImportExport: "ui.nav.admin.sales.importExport",
adminKnowledgeBase: "ui.nav.admin.knowledgeBase",
adminHelpDesk: "ui.nav.admin.helpDesk",
adminSettings: "ui.nav.admin.settings",
@@ -77,8 +112,23 @@ export const UI_ID_PATTERNS = {
appEntityGroupEntity: "ui.nav.app.entityGroup.{groupSlug}.entity.{entityName}",
appSection: "ui.nav.app.section.{sectionName}",
docsRoute: "ui.nav.docs.route.{routeSlug}",
commandPaletteResult: "ui.surface.commandPalette.result.{entityType}.{entityId}",
commandPaletteRecent: "ui.surface.commandPalette.recent.{recentId}",
commandPaletteAction: "ui.surface.commandPalette.action.{actionId}",
} as const;
export function getCommandPaletteResultId(entityType: string, entityId: string) {
return `ui.surface.commandPalette.result.${uiIdSegment(entityType)}.${uiIdSegment(entityId)}`;
}
export function getCommandPaletteRecentId(recentId: string) {
return `ui.surface.commandPalette.recent.${uiIdSegment(recentId)}`;
}
export function getCommandPaletteActionId(actionId: string) {
return `ui.surface.commandPalette.action.${uiIdSegment(actionId)}`;
}
export function getSidebarSurfaceId(layout: UiLayout) {
if (layout === "admin") {
return UI_SURFACE_IDS.adminSidebar;
@@ -0,0 +1,106 @@
// @vitest-environment node
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { inflateSync } from "node:zlib";
import { describe, expect, it } from "vitest";
import { defaultBrandPublicIcons, defaultFavicon32Href, defaultFaviconCacheKey, defaultFaviconLinks, defaultFaviconPreviewSrc } from "./public-icons";
const PNG_SIGNATURE = "89504e470d0a1a0a";
const publicDirectory = fileURLToPath(new URL("../../../../public/", import.meta.url));
function paethPredictor(left: number, up: number, upperLeft: number) {
const estimate = left + up - upperLeft;
const leftDistance = Math.abs(estimate - left);
const upDistance = Math.abs(estimate - up);
const upperLeftDistance = Math.abs(estimate - upperLeft);
if (leftDistance <= upDistance && leftDistance <= upperLeftDistance) return left;
return upDistance <= upperLeftDistance ? up : upperLeft;
}
function decodeRgbaPng(png: Buffer) {
if (png.subarray(0, 8).toString("hex") !== PNG_SIGNATURE) throw new Error("Expected a PNG favicon");
const width = png.readUInt32BE(16);
const height = png.readUInt32BE(20);
if (png[24] !== 8 || png[25] !== 6 || png[28] !== 0) throw new Error("Expected a non-interlaced 8-bit RGBA favicon");
const idatChunks: Buffer[] = [];
let chunkOffset = 8;
while (chunkOffset < png.length) {
const chunkLength = png.readUInt32BE(chunkOffset);
const chunkType = png.toString("ascii", chunkOffset + 4, chunkOffset + 8);
if (chunkType === "IDAT") idatChunks.push(png.subarray(chunkOffset + 8, chunkOffset + 8 + chunkLength));
chunkOffset += chunkLength + 12;
}
const bytesPerPixel = 4;
const rowLength = width * bytesPerPixel;
const filtered = inflateSync(Buffer.concat(idatChunks));
const pixels = Buffer.alloc(rowLength * height);
let sourceOffset = 0;
for (let y = 0; y < height; y += 1) {
const filter = filtered[sourceOffset++];
for (let x = 0; x < rowLength; x += 1) {
const raw = filtered[sourceOffset++];
const targetOffset = y * rowLength + x;
const left = x >= bytesPerPixel ? pixels[targetOffset - bytesPerPixel] : 0;
const up = y > 0 ? pixels[targetOffset - rowLength] : 0;
const upperLeft = y > 0 && x >= bytesPerPixel ? pixels[targetOffset - rowLength - bytesPerPixel] : 0;
const predictor =
filter === 0
? 0
: filter === 1
? left
: filter === 2
? up
: filter === 3
? Math.floor((left + up) / 2)
: filter === 4
? paethPredictor(left, up, upperLeft)
: undefined;
if (predictor === undefined) throw new Error(`Unsupported PNG filter ${filter}`);
pixels[targetOffset] = (raw + predictor) & 0xff;
}
}
return { width, height, pixels };
}
function expectTransparentCorners(png: Buffer) {
const { width, height, pixels } = decodeRgbaPng(png);
const alphaAt = (x: number, y: number) => pixels[(y * width + x) * 4 + 3];
expect([alphaAt(0, 0), alphaAt(width - 1, 0), alphaAt(0, height - 1), alphaAt(width - 1, height - 1)]).toEqual([0, 0, 0, 0]);
expect(Array.from({ length: width * height }, (_, index) => pixels[index * 4 + 3]).some((alpha) => alpha === 255)).toBe(true);
}
describe("default favicon links", () => {
it("uses only the transparent browser favicon family with a cache key", () => {
expect(defaultFaviconLinks.map(({ sizes }) => sizes)).toEqual(["32x32", "96x96", "16x16"]);
expect(defaultFaviconLinks.every(({ href }) => href.includes(`?v=${defaultFaviconCacheKey}`))).toBe(true);
expect(defaultFaviconLinks.every(({ href }) => href.startsWith("/favicon-"))).toBe(true);
});
it("uses the cache-busted 32px favicon for the portal and branding preview", () => {
expect(defaultFavicon32Href).toBe(`${defaultBrandPublicIcons.favicon32}?v=${defaultFaviconCacheKey}`);
expect(defaultFaviconPreviewSrc).toBe(defaultFavicon32Href);
});
it("stores real transparency in every browser PNG and ICO entry", () => {
for (const filename of ["favicon-16x16.png", "favicon-32x32.png", "favicon-96x96.png"]) {
expectTransparentCorners(readFileSync(`${publicDirectory}${filename}`));
}
const ico = readFileSync(`${publicDirectory}favicon.ico`);
const imageCount = ico.readUInt16LE(4);
expect(imageCount).toBe(3);
for (let index = 0; index < imageCount; index += 1) {
const entryOffset = 6 + index * 16;
const imageLength = ico.readUInt32LE(entryOffset + 8);
const imageOffset = ico.readUInt32LE(entryOffset + 12);
expectTransparentCorners(ico.subarray(imageOffset, imageOffset + imageLength));
}
});
});
@@ -10,11 +10,14 @@ export const defaultBrandPublicIcons = {
webManifest: "/site.webmanifest",
} as const;
export const defaultFaviconPreviewSrc = defaultBrandPublicIcons.favicon32;
export const defaultFaviconCacheKey = "20260722-transparent";
export const defaultFavicon32Href = `${defaultBrandPublicIcons.favicon32}?v=${defaultFaviconCacheKey}`;
export const defaultFaviconPreviewSrc = defaultFavicon32Href;
export const defaultFaviconLinks = [
{ rel: "icon", type: "image/png", sizes: "192x192", href: defaultBrandPublicIcons.androidIcon192 },
{ rel: "icon", type: "image/png", sizes: "32x32", href: defaultBrandPublicIcons.favicon32 },
{ rel: "icon", type: "image/png", sizes: "96x96", href: defaultBrandPublicIcons.favicon96 },
{ rel: "icon", type: "image/png", sizes: "16x16", href: defaultBrandPublicIcons.favicon16 },
{ rel: "icon", type: "image/png", sizes: "32x32", href: defaultFavicon32Href },
{ rel: "icon", type: "image/png", sizes: "96x96", href: `${defaultBrandPublicIcons.favicon96}?v=${defaultFaviconCacheKey}` },
{ rel: "icon", type: "image/png", sizes: "16x16", href: `${defaultBrandPublicIcons.favicon16}?v=${defaultFaviconCacheKey}` },
] as const;
@@ -3,6 +3,11 @@ import { subscribeSubscriptionCache } from "./utils/services/.server/subscriptio
import { subscribeTenantCache } from "./utils/db/tenant-cache.server";
import { subscribeFeatureFlagCache } from "./utils/services/.server/featureFlagCache.server";
import { wireTenantPlanLookup } from "./utils/services/.server/tenantPlanLookup.server";
import { getSharedStore } from "./shared-store.server";
import { subscribePermissionCache } from "./utils/db/permissions/permission-cache.server";
import { subscribeApiKeyAuthCache } from "./utils/api/api-key-auth-cache.server";
import { subscribeUserSnapshotCache } from "./utils/db/user-snapshot-cache.server";
import { subscribeAppConfigurationCache } from "./utils/db/app-configuration-cache.server";
const log = createScopedLogger("cache-bootstrap");
let started = false;
@@ -25,6 +30,10 @@ function pubsubEnabled(): boolean {
*/
export function startCacheSubscribers(): void {
if (started) return;
// Resolve the backing store synchronously at boot. Production must never
// continue with replica-local cache and rate-limit state when Redis is
// missing; asynchronous subscriber errors would otherwise be swallowed.
getSharedStore();
started = true;
// Wire the BullMQ tenant-plan lookup unconditionally — it reads from the
// subscription cache which still serves locally when pub/sub is off.
@@ -32,7 +41,7 @@ export function startCacheSubscribers(): void {
if (!pubsubEnabled()) {
log.warn(
{ component: "cache-bootstrap" },
"CACHE_INVALIDATION_ENABLED=false — pub/sub subscribers will not start (L1 TTL is the only consistency mechanism)",
"CACHE_INVALIDATION_ENABLED=false — pub/sub subscribers will not start (L1 TTL is the only consistency mechanism)"
);
return;
}
@@ -46,6 +55,18 @@ export function startCacheSubscribers(): void {
subscribeFeatureFlagCache().catch((err: unknown) => {
log.error({ err }, "feature-flag cache subscriber failed to start");
}),
subscribePermissionCache().catch((err: unknown) => {
log.error({ err }, "permission cache subscriber failed to start");
}),
subscribeApiKeyAuthCache().catch((err: unknown) => {
log.error({ err }, "API-key authorization cache subscriber failed to start");
}),
subscribeUserSnapshotCache().catch((err: unknown) => {
log.error({ err }, "user snapshot cache subscriber failed to start");
}),
subscribeAppConfigurationCache().catch((err: unknown) => {
log.error({ err }, "app configuration cache subscriber failed to start");
}),
]).then(() => {
log.info({ component: "cache-bootstrap" }, "cache subscribers started");
});
@@ -1,5 +1,5 @@
import { AnimatePresence, motion } from "framer-motion";
import { t as i18nT } from "i18next";
import { AnimatePresence, motion } from "motion/react";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import LinkOrAhref from "../ui/buttons/LinkOrAhref";
import clsx from "clsx";
@@ -1,9 +1,10 @@
import React, { useRef } from "react";
import { t as i18nT } from "i18next";
import { motion, useScroll, useSpring, useTransform } from "framer-motion";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { motion, useScroll, useSpring, useTransform } from "motion/react";
import type { Transition } from "motion/react";
export const MovingLine = () => {
const transition = {
const transition: Transition = {
duration: 14,
ease: "easeInOut",
};
@@ -27,7 +27,7 @@ const filters = [
function renderToolbar(initialEntry: string) {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<TenantActivityLogToolbar filters={filters} />
<TenantActivityLogToolbar filters={filters} exportTo="/acme/settings/logs/export" />
</MemoryRouter>
);
}
@@ -42,12 +42,12 @@ describe("TenantActivityLogToolbar", () => {
expect(screen.getByText("models.log.actor")).toBeInTheDocument();
});
it("preserves active filters while replacing stale pagination with CSV export", () => {
it("preserves active filters while dropping stale pagination on the export href", () => {
renderToolbar("/acme/settings/logs?q=login&action=auth&url=%2Flogin&actor=Grace&page=3&pageSize=25");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/acme/settings/logs");
expect(exportUrl.pathname).toBe("/acme/settings/logs/export");
expect(exportUrl.searchParams.get("q")).toBe("login");
expect(exportUrl.searchParams.get("action")).toBe("auth");
expect(exportUrl.searchParams.get("url")).toBe("/login");
@@ -55,22 +55,21 @@ describe("TenantActivityLogToolbar", () => {
expect(exportUrl.searchParams.get("pageSize")).toBe("25");
expect(exportUrl.searchParams.get("tenantId")).toBeNull();
expect(exportUrl.searchParams.get("page")).toBeNull();
expect(exportUrl.searchParams.get("export")).toBe("csv");
});
it("replaces an existing export value with csv", () => {
it("drops a stale export param from the current search", () => {
renderToolbar("/acme/settings/logs?export=json&actor=user-1");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/acme/settings/logs");
expect(exportUrl.pathname).toBe("/acme/settings/logs/export");
expect(exportUrl.searchParams.get("actor")).toBe("user-1");
expect(exportUrl.searchParams.get("export")).toBe("csv");
expect(exportUrl.searchParams.get("export")).toBeNull();
});
it("creates a valid tenant-relative CSV export href without existing search params", () => {
renderToolbar("/acme/settings/logs");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/acme/settings/logs?export=csv");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/acme/settings/logs/export");
});
});
@@ -6,16 +6,19 @@ import { Button } from "~/components/ui/button";
type Props = {
filters: FilterablePropertyDto[];
// Path of the CSV export resource route; active filters are carried over.
exportTo: string;
};
export default function TenantActivityLogToolbar({ filters }: Props) {
export default function TenantActivityLogToolbar({ filters, exportTo }: Props) {
const { t } = useTranslation();
const location = useLocation();
const exportLabel = getFallbackTranslation(t("shared.export"), "Export");
const exportSearchParams = new URLSearchParams(location.search);
exportSearchParams.delete("page");
exportSearchParams.set("export", "csv");
const exportHref = `${location.pathname}?${exportSearchParams.toString()}`;
exportSearchParams.delete("export");
const exportQuery = exportSearchParams.toString();
const exportHref = exportQuery ? `${exportTo}?${exportQuery}` : exportTo;
return (
<div className="flex items-center gap-2">
@@ -1,5 +1,5 @@
import { Link } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import clsx from "clsx";
import { lazy, Suspense, useEffect, useId, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -69,7 +69,7 @@ interface TopItemDto {
tabTitle?: string;
}
function TopItemsData({ title, items, viewMoreRoute, fallbackName, bgClassName }: TopItemDto) {
function TopItemsData({ title: _title, items, viewMoreRoute, fallbackName, bgClassName }: TopItemDto) {
const { authenticated } = useRootData();
const formatters = useLocaleFormatters();
const maxCount = useMemo(() => Math.max(0, ...items.map((item) => item.count)), [items]);
@@ -249,7 +249,21 @@ export default function AnalyticsOverview({ overview, withUsers, rootUrl }: { ov
<path strokeLinecap="round" strokeLinejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5" />
</svg>
) : (
<img className="h-4 w-4" src={`http://www.google.com/s2/favicons?domain=${item.name}&sz=256`} alt={item.name} />
<svg
className="text-muted-foreground h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 21a9 9 0 1 0 0-18m0 18c2.1 0 3.8-4 3.8-9S14.1 3 12 3m0 18c-2.1 0-3.8-4-3.8-9S9.9 3 12 3M3.5 9h17m-17 6h17"
/>
</svg>
),
name: UrlUtils.stripTrailingSlash(item.name?.replace("https://", "").replace("http://", "").replace("www.", "") ?? ""),
count: item.count,
@@ -2,6 +2,7 @@ import { ReactNode } from "react";
import CommandPalette from "../ui/commandPalettes/CommandPalette";
import SubframeAppShell from "./SubframeAppShell";
import SkipToContent from "../core/SkipToContent";
import { UiPreferencesProvider } from "./UiPreferencesContext";
interface Props {
layout: "app" | "admin" | "docs";
@@ -12,11 +13,13 @@ export default function AppLayout({ layout, children }: Props) {
// D-D0a: App-Rahmen ist jetzt Davids Subframe-Shell (SidebarWithSections + Topbar) statt der
// shadcn-Shell. Der CommandPalette-Wrapper bleibt (liefert den useCommandPalette-Kontext fuer die Topbar).
return (
<div>
<SkipToContent />
<CommandPalette key={layout} layout={layout}>
<SubframeAppShell layout={layout}>{children}</SubframeAppShell>
</CommandPalette>
</div>
<UiPreferencesProvider>
<div>
<SkipToContent />
<CommandPalette key={layout} layout={layout}>
<SubframeAppShell layout={layout}>{children}</SubframeAppShell>
</CommandPalette>
</div>
</UiPreferencesProvider>
);
}
@@ -0,0 +1,28 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter, useLocation } from "react-router";
import { describe, expect, it } from "vitest";
import { AppLink } from "./AppLink";
function LocationProbe() {
const location = useLocation();
return <output>{`${location.pathname}${location.search}`}</output>;
}
describe("AppLink", () => {
it("stays a semantic anchor in isolated presentational tests", () => {
render(<AppLink href="/acme/projects/p1">Project</AppLink>);
expect(screen.getByRole("link", { name: "Project" }).getAttribute("href")).toBe("/acme/projects/p1");
});
it("navigates through React Router when the app shell is present", () => {
render(
<MemoryRouter initialEntries={["/acme/projects"]}>
<AppLink href="/acme/projects/p1?tab=details">Project</AppLink>
<LocationProbe />
</MemoryRouter>,
);
fireEvent.click(screen.getByRole("link", { name: "Project" }));
expect(screen.getByRole("status").textContent).toBe("/acme/projects/p1?tab=details");
});
});
@@ -0,0 +1,42 @@
import { forwardRef, type ComponentPropsWithoutRef } from "react";
import { Link, useInRouterContext } from "react-router";
export type AppLinkProps = Omit<ComponentPropsWithoutRef<"a">, "href"> & {
href: string;
replace?: boolean;
preventScrollReset?: boolean;
};
/**
* Internal navigation for presentational screens.
*
* In the running app this uses React Router, preserving the shell and its page
* transition. Isolated screen/component tests do not always mount a router, so
* the same component deliberately falls back to a semantic anchor there.
* Downloads, OAuth hops, mailto/tel and external URLs must keep using <a>.
*/
export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(function AppLink(
{ href, replace, preventScrollReset, children, ...anchorProps },
ref,
) {
const inRouter = useInRouterContext();
if (!inRouter) {
return (
<a ref={ref} href={href} {...anchorProps}>
{children}
</a>
);
}
return (
<Link
ref={ref}
to={href}
replace={replace}
preventScrollReset={preventScrollReset}
{...anchorProps}
>
{children}
</Link>
);
});
@@ -0,0 +1,71 @@
// @vitest-environment jsdom
import { useLayoutEffect } from "react";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { AppShellSidebarContext, useRecommendedSidebarCollapse } from "./AppShellSidebarContext";
function BoardWorkspace({ workspaceKey }: { workspaceKey: string | null }) {
useRecommendedSidebarCollapse(workspaceKey);
return null;
}
function BoardWorkspaceWithLayoutProbe({ onLayout }: { onLayout: () => void }) {
useRecommendedSidebarCollapse("projects:pipeline-a");
useLayoutEffect(() => {
onLayout();
}, [onLayout]);
return null;
}
describe("useRecommendedSidebarCollapse", () => {
it("requests a collapse when a board opens and whenever its board identity changes", () => {
const collapseSidebarIfPreferred = vi.fn();
const value = { collapseSidebar: vi.fn(), collapseSidebarIfPreferred };
const { rerender } = render(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-a" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledOnce();
rerender(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-a" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledOnce();
rerender(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-b" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledTimes(2);
});
it("does nothing when no board is available", () => {
const collapseSidebarIfPreferred = vi.fn();
render(
<AppShellSidebarContext.Provider value={{ collapseSidebar: vi.fn(), collapseSidebarIfPreferred }}>
<BoardWorkspace workspaceKey={null} />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).not.toHaveBeenCalled();
});
it("requests the collapse during layout before the board can paint", () => {
const order: string[] = [];
const collapseSidebarIfPreferred = vi.fn(() => order.push("collapse"));
render(
<AppShellSidebarContext.Provider value={{ collapseSidebar: vi.fn(), collapseSidebarIfPreferred }}>
<BoardWorkspaceWithLayoutProbe onLayout={() => order.push("layout-probe")} />
</AppShellSidebarContext.Provider>
);
expect(order).toEqual(["collapse", "layout-probe"]);
});
});
@@ -0,0 +1,25 @@
import { createContext, useContext, useLayoutEffect } from "react";
export type AppShellSidebarControls = {
collapseSidebar: () => void;
collapseSidebarIfPreferred: () => void;
};
const NOOP_CONTROLS: AppShellSidebarControls = {
collapseSidebar: () => undefined,
collapseSidebarIfPreferred: () => undefined,
};
export const AppShellSidebarContext = createContext<AppShellSidebarControls>(NOOP_CONTROLS);
export function useAppShellSidebar(): AppShellSidebarControls {
return useContext(AppShellSidebarContext);
}
export function useRecommendedSidebarCollapse(workspaceKey: string | null): void {
const { collapseSidebarIfPreferred } = useAppShellSidebar();
useLayoutEffect(() => {
if (workspaceKey) collapseSidebarIfPreferred();
}, [collapseSidebarIfPreferred, workspaceKey]);
}
@@ -17,17 +17,21 @@ type Props = {
// section).
// - "Remind me in 7 days" → POSTs to a tiny resource route which sets a
// short-lived UX cookie. While that cookie is in the future the tenant
// layout omits the banner entirely.
// layout omits the banner entirely. The route lives under /auth/* so it
// stays reachable on the tenant app host (the host-routing runtime
// 404s all other /api/* paths there).
//
// The banner also offers a local "dismiss for this page-load" close button
// so the user can hide it without committing to either action.
const REMIND_ACTION_PATH = "/auth/password-policy-remind";
export default function PasswordPolicyBanner({ changePasswordHref }: Props) {
const { t } = useTranslation("auth");
const fetcher = useFetcher();
const [locallyDismissed, setLocallyDismissed] = useState(false);
if (locallyDismissed) return null;
if (fetcher.state !== "idle" && fetcher.formAction === "/api/password-policy-remind") {
if (fetcher.state !== "idle" && fetcher.formAction === REMIND_ACTION_PATH) {
// Optimistically hide while the remind cookie is being set so the user
// gets immediate feedback on click.
return null;
@@ -61,7 +65,7 @@ export default function PasswordPolicyBanner({ changePasswordHref }: Props) {
>
{t("passwordPolicyBanner.changeNow")}
</Link>
<fetcher.Form method="post" action="/api/password-policy-remind">
<fetcher.Form method="post" action={REMIND_ACTION_PATH}>
<button
type="submit"
data-testid="password-policy-banner-remind"
@@ -0,0 +1,136 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { Link, MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RouteContentTransition } from "./RouteContentTransition";
const originalAnimate = HTMLElement.prototype.animate;
const originalMatchMedia = window.matchMedia;
function renderTransition() {
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/second">Next</Link>
<Routes>
<Route
path="*"
element={
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
}
/>
</Routes>
</MemoryRouter>
);
}
describe("RouteContentTransition", () => {
afterEach(() => {
HTMLElement.prototype.animate = originalAnimate;
window.matchMedia = originalMatchMedia;
vi.restoreAllMocks();
});
it("animates the existing content wrapper only after a pathname change", () => {
const cancel = vi.fn();
const animate = vi.fn(() => ({ cancel }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
renderTransition();
expect(animate).not.toHaveBeenCalled();
const wrapper = document.querySelector('[data-route-content-transition="true"]');
fireEvent.click(screen.getByRole("link", { name: "Next" }));
expect(document.querySelector('[data-route-content-transition="true"]')).toBe(wrapper);
expect(animate).toHaveBeenCalledWith(
[
{ opacity: 0.15, filter: "blur(5px)" },
{ opacity: 1, filter: "blur(0px)" },
],
expect.objectContaining({ duration: 420, easing: "cubic-bezier(0.22, 1, 0.36, 1)" })
);
});
it("does not animate when reduced motion is requested", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: true }) as MediaQueryList);
renderTransition();
fireEvent.click(screen.getByRole("link", { name: "Next" }));
expect(animate).not.toHaveBeenCalled();
});
it("does not animate filter-only navigation", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/first?q=compact">Change filter</Link>
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("link", { name: "Change filter" }));
expect(animate).not.toHaveBeenCalled();
});
it("animates structural tab and view changes on the same pathname", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first?tab=overview"]}>
<Link to="/first?tab=details">Open details tab</Link>
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("link", { name: "Open details tab" }));
expect(animate).toHaveBeenCalledOnce();
});
it("animates marked page content without touching a stable inner sidebar", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/second">Next inner page</Link>
<Routes>
<Route
path="*"
element={
<RouteContentTransition>
<aside data-testid="inner-sidebar">Inner sidebar</aside>
<section data-testid="page-content" data-route-transition-content="true">
Page content
</section>
</RouteContentTransition>
}
/>
</Routes>
</MemoryRouter>
);
const wrapper = document.querySelector<HTMLElement>('[data-route-content-transition="true"]');
const pageContent = screen.getByTestId("page-content");
fireEvent.click(screen.getByRole("link", { name: "Next inner page" }));
expect(animate).toHaveBeenCalledOnce();
expect(animate.mock.contexts[0]).toBe(pageContent);
expect(animate.mock.contexts[0]).not.toBe(wrapper);
});
});
@@ -0,0 +1,75 @@
import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import { useLocation } from "react-router";
import { useUiPreferences } from "./UiPreferencesContext";
const ROUTE_TRANSITION_DURATION_MS = 420;
const ROUTE_TRANSITION_TARGET_SELECTOR = '[data-route-transition-content="true"]';
// Tabs and view-mode routes render a genuinely different subpage while keeping
// the same pathname. Filters/search/pagination deliberately stay out: animating
// every query refinement would make dense working screens feel unstable.
const STRUCTURAL_SEARCH_PARAMS = ["tab", "view"] as const;
/**
* Adds a restrained transition after real pathname changes. The wrapper stays
* mounted, so route state, forms and dialogs are not reset by the animation.
*
* Blur plus a pronounced fade makes the route change clearly visible without
* moving or scaling the content column. Inner sidebars stay outside the marked
* page target and therefore remain visually stable.
*/
export function RouteContentTransition({ children }: { children: ReactNode }) {
const location = useLocation();
const { preferences } = useUiPreferences();
const contentRef = useRef<HTMLDivElement>(null);
const transitionKey = useMemo(() => {
const params = new URLSearchParams(location.search);
return `${location.pathname}?${STRUCTURAL_SEARCH_PARAMS.map((key) => `${key}=${params.get(key) ?? ""}`).join("&")}`;
}, [location.pathname, location.search]);
const previousTransitionKeyRef = useRef(transitionKey);
const animationRef = useRef<Animation | null>(null);
// Start before the browser paints the new route. useEffect runs one frame
// later, which made fast subpages briefly appear complete before fading in
// and was perceived as a missing/inconsistent transition.
useLayoutEffect(() => {
if (previousTransitionKeyRef.current === transitionKey) return;
previousTransitionKeyRef.current = transitionKey;
const content = contentRef.current;
const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
if (!content || !preferences.visualEffectsEnabled || reduceMotion || typeof content.animate !== "function") return;
const target = content.querySelector<HTMLElement>(ROUTE_TRANSITION_TARGET_SELECTOR) ?? content;
animationRef.current?.cancel();
animationRef.current = target.animate(
[
{ opacity: 0.15, filter: "blur(5px)" },
{ opacity: 1, filter: "blur(0px)" },
],
{
duration: ROUTE_TRANSITION_DURATION_MS,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
fill: "both",
}
);
return () => {
animationRef.current?.cancel();
animationRef.current = null;
};
}, [transitionKey, preferences.visualEffectsEnabled]);
useEffect(
() => () => {
animationRef.current?.cancel();
},
[]
);
return (
<div ref={contentRef} className="pb-20 sm:pb-0" data-route-content-transition="true">
{children}
</div>
);
}
@@ -1,20 +1,30 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { UI_ACTION_IDS, UI_SURFACE_IDS, getSidebarSurfaceId, type UiLayout } from "~/application/ui/uiRegistry";
import SubframeAppShell from "./SubframeAppShell";
import { useAppShellSidebar } from "./AppShellSidebarContext";
// D-D0a — Contract-Test der neuen Subframe-App-Shell: stabile Shell-Surface-/Action-data-ui-ids
// (analog zum bisherigen ShadcnSidebarLayout-Test), damit der Reachability-Kontrakt erhalten bleibt.
const { commandPaletteToggle } = vi.hoisted(() => ({ commandPaletteToggle: vi.fn() }));
vi.mock("~/components/ui/commandPalettes/CommandPalette", () => ({
useCommandPalette: () => ({ toggle: vi.fn() }),
useCommandPalette: () => ({ toggle: commandPaletteToggle }),
}));
vi.mock("~/modules/onboarding/components/OnboardingSession", () => ({ default: () => null }));
vi.mock("~/utils/data/useTitleData", () => ({ useTitleData: () => "Dashboard" }));
vi.mock("~/utils/data/useTitleData", () => ({
useTitleData: () => "Dashboard",
useBreadcrumbTrail: () => [
{ label: "Parent", href: "/parent" },
{ label: "Dashboard", href: "/" },
],
shouldShowParentNavCrumb: () => false,
}));
vi.mock("~/utils/data/useAppOrAdminData", () => ({
useAppOrAdminData: () => ({
@@ -35,11 +45,23 @@ vi.mock("../layouts/sidebars/shadcn/nav-actions", () => ({
NavActions: () => <button data-ui-id="ui.action.shell.search">Search</button>,
}));
vi.mock("~/application/sidebar/AppSidebar", () => ({ AppSidebar: () => [] }));
let mockedAppSidebarItems: any[] = [];
function CollapseSidebarButton() {
const { collapseSidebar } = useAppShellSidebar();
return <button onClick={collapseSidebar}>Collapse sidebar</button>;
}
vi.mock("~/application/sidebar/AppSidebar", () => ({ AppSidebar: () => mockedAppSidebarItems }));
vi.mock("~/application/sidebar/AdminSidebar", () => ({ AdminSidebar: () => [] }));
vi.mock("~/application/sidebar/DocsSidebar", () => ({ DocsSidebar: () => [] }));
describe("SubframeAppShell UI IDs", () => {
afterEach(() => {
mockedAppSidebarItems = [];
commandPaletteToggle.mockReset();
});
function renderShell(layout: UiLayout) {
const router = createMemoryRouter(
[
@@ -70,11 +92,184 @@ describe("SubframeAppShell UI IDs", () => {
expect(document.querySelector(`[data-ui-id="${getSidebarSurfaceId(layout)}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellHeader}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellBreadcrumb}"]`)).toBeInTheDocument();
expect(screen.getByRole("link", { name: "Parent" }).firstElementChild).toHaveClass("text-text-neutral-secondary");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellBreadcrumbCurrent}"]`)).toHaveTextContent("Dashboard");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellNavActions}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.sidebarTrigger}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.search}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.searchMobile}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellMain}"]`)).toContainElement(screen.getByText("Page content"));
expectNoDuplicateDataUiIds();
});
it("never renders the notification bell as a dead link", () => {
// The bell fell back to href="#" whenever no tenant was in scope, which made
// it dead on every admin page (admin audit 2026-07-26, A11Y-01). A surface
// without a notification centre omits the bell instead.
for (const layout of ["app", "admin", "docs"] as UiLayout[]) {
renderShell(layout);
const bell = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.notifications}"]`);
if (bell) {
expect(bell.getAttribute("href"), `${layout} bell href`).not.toBe("#");
expect(bell.getAttribute("href"), `${layout} bell href`).toBeTruthy();
}
cleanup();
}
});
it("points the admin bell at the admin notification centre with accessible markup", () => {
renderShell("admin");
const bell = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.notifications}"]`);
expect(bell).toBeInTheDocument();
expect(bell?.tagName).toBe("A");
expect(bell?.getAttribute("href")).toContain("notifications");
expect(bell).toHaveAttribute("aria-label");
expect(bell).toHaveClass("focus-visible:shadow-focus");
expect(bell?.querySelector("button")).toBeNull();
});
it("opens the same command palette from the desktop field and mobile icon triggers", () => {
renderShell("app");
const desktopTrigger = document.querySelector<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.search}"]`);
const mobileTrigger = document.querySelector<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.searchMobile}"]`);
expect(desktopTrigger).toHaveClass("hidden", "md:flex");
expect(mobileTrigger).toHaveClass("md:hidden");
expect(desktopTrigger?.tagName).toBe("BUTTON");
expect(desktopTrigger?.querySelector("input")).toBeNull();
desktopTrigger?.focus();
expect(desktopTrigger).toHaveFocus();
fireEvent.click(desktopTrigger!);
fireEvent.click(mobileTrigger!);
expect(commandPaletteToggle).toHaveBeenCalledTimes(2);
});
it("uses named native controls for shell icon actions", () => {
renderShell("app");
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
const collapseTrigger = sidebar?.querySelector("button");
const userMenu = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.more}"]`);
expect(collapseTrigger).toHaveAttribute("aria-label");
expect(collapseTrigger?.getAttribute("aria-label")).not.toBe("");
// The bell's own contract moved to the admin-surface test above: without a
// tenant in scope the app layout has no notification target, so the bell is
// omitted rather than rendered as a dead link.
expect(userMenu?.tagName).toBe("BUTTON");
expect(userMenu).toHaveAttribute("aria-label");
expect(userMenu).toHaveClass("focus-visible:shadow-focus");
expect(userMenu).toBeEmptyDOMElement();
});
it("marks internal sidebar links for client-side navigation", () => {
mockedAppSidebarItems = [
{
id: "ui.nav.test.main",
title: "Main",
path: "",
items: [{ id: "ui.nav.test.target", title: "Target", path: "/target" }],
},
];
const router = createMemoryRouter(
[
{
path: "*",
element: (
<SubframeAppShell layout="app">
<section>Page content</section>
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
expect(screen.getByRole("link", { name: "Target" })).toHaveAttribute("data-navigation-kind", "client");
});
it("closes the mobile sidebar after internal navigation", () => {
mockedAppSidebarItems = [
{
id: "ui.nav.test.main",
title: "Main",
path: "",
items: [{ id: "ui.nav.test.target", title: "Target", path: "/target" }],
},
];
const router = createMemoryRouter(
[
{
path: "*",
element: (
<SubframeAppShell layout="app">
<section>Page content</section>
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
expect(sidebar).toHaveClass("max-md:-translate-x-full");
fireEvent.click(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.sidebarTrigger}"]`)!);
expect(sidebar).toHaveClass("max-md:translate-x-0");
fireEvent.click(screen.getByRole("link", { name: "Target" }));
expect(sidebar).toHaveClass("max-md:-translate-x-full");
});
it("keeps the sidebar width independent from route content", () => {
renderShell("app");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`)).toHaveClass("w-60", "shrink-0");
});
it("lets nested screens collapse the desktop sidebar without toggling it back open", () => {
const router = createMemoryRouter(
[
{
path: "/",
element: (
<SubframeAppShell layout="app">
<CollapseSidebarButton />
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
expect(sidebar).toHaveClass("w-60");
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
expect(sidebar).toHaveClass("w-16");
});
it("contains page scrolling inside the shell viewport", () => {
renderShell("app");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shell}"]`)).toHaveClass("h-screen", "overflow-hidden");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellInset}"]`)).toHaveClass("h-full", "min-h-0", "overflow-hidden");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellMain}"]`)).toHaveClass(
"min-h-0",
"flex-1",
"overflow-auto",
"overscroll-y-contain"
);
});
});
@@ -1,26 +1,20 @@
import { useMemo, useRef, useState } from "react";
import { useFetcher, useLocation, useNavigate, useParams, useSearchParams, useSubmit } from "react-router";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useFetcher, useLocation, useNavigate, useParams, useSearchParams, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherBell,
FeatherLogOut,
FeatherMenu,
FeatherMoon,
FeatherSettings,
FeatherSun,
FeatherUserSearch,
} from "@subframe/core";
import { FeatherBell, FeatherLogOut, FeatherMenu, FeatherMoon, FeatherSearch, FeatherSettings, FeatherSun, FeatherUserSearch } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { SidebarWithSections } from "~/ui/components/SidebarWithSections";
import { Breadcrumbs } from "~/ui/components/Breadcrumbs";
import { SearchInput } from "~/ui/components/SearchInput";
import { IconButton } from "~/ui/components/IconButton";
import { Avatar } from "~/ui/components/Avatar";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { BadgeShortcut } from "~/ui/components/BadgeShortcut";
import { useCommandPalette } from "~/components/ui/commandPalettes/CommandPalette";
import { useTitleData } from "~/utils/data/useTitleData";
import { McpConnectLauncher } from "~/components/mcp/McpConnectLauncher";
import { NotificationToasts, useShellNotifications } from "~/components/notifications/NotificationToasts";
import { shouldShowParentNavCrumb, useBreadcrumbTrail, useTitleData } from "~/utils/data/useTitleData";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import { UI_ACTION_IDS, UI_SURFACE_IDS, getSidebarSurfaceId } from "~/application/ui/uiRegistry";
@@ -32,12 +26,20 @@ import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
import UrlUtils from "~/utils/app/UrlUtils";
import UserDisplayUtils from "~/utils/app/UserDisplayUtils";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { DARK_MODE_IN_APP } from "~/application/Constants";
import { RouteContentTransition } from "./RouteContentTransition";
import { useIsMobile } from "~/hooks/use-mobile";
import { AppShellSidebarContext } from "./AppShellSidebarContext";
import { useUiPreferences } from "./UiPreferencesContext";
type UiLayout = "app" | "admin" | "docs";
function isInternalNavigationPath(to: string) {
return to.startsWith("/") && !to.startsWith("//");
}
// D-D0a — App-Shell nach Davids Subframe-Design (DefaultPageLayout: SidebarWithSections + HeaderNavigation).
// Ersetzt die shadcn-Shell. Sidebar mit funktionierendem Collapse-Toggle; Topbar = Breadcrumb + Suchfeld
// (-> Cmd+K) + Notification-Bell + User-Avatar-Dropdown (Profil/Theme/Logout + "Arbeitsbereich wechseln"
@@ -51,18 +53,130 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
const appData = useAppOrAdminData();
const rootData = useRootData();
const title = useTitleData() ?? "";
const breadcrumbTrail = useBreadcrumbTrail();
const commandPalette = useCommandPalette();
const fetcher = useFetcher();
const submit = useSubmit();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const mainElement = useRef<HTMLElement>(null);
const sidebarElement = useRef<HTMLElement>(null);
const sidebarTriggerElement = useRef<HTMLButtonElement>(null);
const restoreMobileTriggerFocus = useRef(false);
const isMobile = useIsMobile();
const { preferences, preferencesReady } = useUiPreferences();
const shellNotifications = useShellNotifications(layout === "app" && params.tenant ? params.tenant : null);
const [collapsed, setCollapsed] = useState(false); // Desktop-Collapse (Davids Toggle)
const [mobileOpen, setMobileOpen] = useState(false); // Mobile-Drawer
const collapseSidebar = useCallback(() => {
restoreMobileTriggerFocus.current = false;
setCollapsed(true);
setMobileOpen(false);
}, []);
const collapseSidebarIfPreferred = useCallback(() => {
if (preferencesReady && preferences.autoCollapseSidebar) collapseSidebar();
}, [collapseSidebar, preferences.autoCollapseSidebar, preferencesReady]);
const sidebarControls = useMemo(
() => ({ collapseSidebar, collapseSidebarIfPreferred }),
[collapseSidebar, collapseSidebarIfPreferred]
);
const sidebarSurfaceId = getSidebarSurfaceId(layout);
function closeMobileSidebar({ restoreFocus = false }: { restoreFocus?: boolean } = {}) {
restoreMobileTriggerFocus.current = restoreFocus;
setMobileOpen(false);
}
useEffect(() => {
if (!isMobile || !mobileOpen) {
if (restoreMobileTriggerFocus.current) {
restoreMobileTriggerFocus.current = false;
window.requestAnimationFrame(() => sidebarTriggerElement.current?.focus());
}
return;
}
const sidebar = sidebarElement.current;
if (!sidebar) return;
const focusableSelector = [
"a[href]",
"button:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
"textarea:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(",");
const focusableItems = () =>
Array.from(sidebar.querySelectorAll<HTMLElement>(focusableSelector)).filter(
(element) => element.getClientRects().length > 0 && window.getComputedStyle(element).visibility !== "hidden"
);
window.requestAnimationFrame(() => focusableItems()[0]?.focus());
function handleKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
closeMobileSidebar({ restoreFocus: true });
return;
}
if (event.key !== "Tab") return;
const items = focusableItems();
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items.at(-1)!;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [isMobile, mobileOpen]);
useEffect(() => {
function handleSidebarShortcut(event: KeyboardEvent) {
if (!isMobile || event.key.toLowerCase() !== "e" || (!event.ctrlKey && !event.metaKey)) return;
event.preventDefault();
if (mobileOpen) {
closeMobileSidebar({ restoreFocus: true });
} else {
setMobileOpen(true);
}
}
document.addEventListener("keydown", handleSidebarShortcut);
return () => document.removeEventListener("keydown", handleSidebarShortcut);
}, [isMobile, mobileOpen]);
// How much of the viewport the sidebar takes, published for chrome that sits
// outside this shell — the save toast centres over the content rather than
// over the whole window. On mobile the sidebar is off-canvas and takes none.
useEffect(() => {
const root = document.documentElement;
root.style.setProperty("--app-content-inset-left", isMobile ? "0px" : collapsed ? "4rem" : "15rem");
return () => {
root.style.removeProperty("--app-content-inset-left");
};
}, [collapsed, isMobile]);
// Notification target per surface. `null` means the surface has no notification
// centre, and the bell is then omitted rather than rendered as a dead link.
const notificationsHref =
layout === "admin" ? adminPath("notifications", { mode: "host-aware" }) : params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : null;
// ---- Menü bauen (identisches Gating wie shadcn-Shell) ----
function getPath(item: SideBarItem): string {
return UrlUtils.replaceVariables(params, item.path) ?? "";
@@ -77,7 +191,15 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
return exact ? currentPath === itemPath : currentPath === itemPath || currentPath.startsWith(`${itemPath}/`);
}
function isCurrent(item: SideBarItem): boolean {
return pathMatchesCurrent(getPath(item), item.exact);
// excludePaths trump activePaths: a broad prefix match (e.g. Boards on
// /projects) must not light up on sibling entries' subroutes (Plantafel).
if (item.excludePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path))) {
return false;
}
return (
pathMatchesCurrent(getPath(item), item.exact) ||
(item.activePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path)) ?? false)
);
}
function currentIsChild(item: SideBarItem): boolean {
return item.items?.some((child) => isCurrent(child) || currentIsChild(child)) ?? false;
@@ -100,14 +222,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
return !item.tenantUserTypes || (currentRole !== null && item.tenantUserTypes.includes(currentRole));
}
function checkUserRolePermissions(item: SideBarItem) {
return !item.permission || getUserHasPermission(appData, item.permission);
const hasRequired = !item.permission || getUserHasPermission(appData, item.permission);
const hasAny = !item.anyPermissions || item.anyPermissions.some((permission) => getUserHasPermission(appData, permission));
return hasRequired && hasAny;
}
function getVisibleItem(item: SideBarItem): SideBarItem | null {
if (item.hidden === true || !allowCurrentUserType(item) || !allowCurrentTenantUserType(item)) return null;
const items = item.items?.map((child) => getVisibleItem(child)).filter((c): c is SideBarItem => c !== null) ?? [];
const contextItems = item.contextItems?.map((child) => getVisibleItem(child)).filter((c): c is SideBarItem => c !== null) ?? [];
const hasPermission = checkUserRolePermissions(item);
if (!hasPermission && items.length === 0) return null;
return { ...item, path: hasPermission ? item.path : "", redirectTo: hasPermission ? item.redirectTo : undefined, items };
if ((!hasPermission && items.length === 0 && contextItems.length === 0) || ((item.contextItems?.length ?? 0) > 0 && contextItems.length === 0)) return null;
const ownPathVisible = contextItems.some((child) => child.path === item.path);
return {
...item,
path: hasPermission && (contextItems.length === 0 || ownPathVisible) ? item.path : (contextItems[0]?.path ?? ""),
redirectTo: hasPermission ? item.redirectTo : undefined,
items,
contextItems,
};
}
function getMenuItems(): SideBarItem[] {
let menu: SideBarItem[] = [];
@@ -138,9 +270,66 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess]);
// Same entitlement decision the MCP runtime enforces server-side; the topbar
// entry must not advertise a connector the tenant cannot use.
const canConnectMcp = "productAccess" in appData ? appData.productAccess?.["mcp"]?.allowed === true : false;
const navMain = menu.filter((g) => g.type === "main");
const navSecondary = menu.filter((g) => g.type === "secondary");
// Sidebar entry responsible for the current route (longest matching own path
// or activePaths prefix, excludePaths respected — e.g. Plantafel over Boards).
// Used as crumb fallback for routes without a loader title and as clickable
// parent crumb on sub-pages.
const activeNavItem = useMemo(() => {
const flat: SideBarItem[] = [];
const walk = (items: SideBarItem[]) =>
items.forEach((item) => {
flat.push(item);
if (item.items) walk(item.items);
});
menu.forEach((group) => walk(group.items));
const currentPath = normalizePath(location.pathname);
const matchLength = (rawPath: string | undefined): number => {
const candidate = normalizePath(rawPath ?? "");
if (!candidate) return 0;
return currentPath === candidate || currentPath.startsWith(`${candidate}/`) ? candidate.length : 0;
};
let best: { title: string; path: string; length: number; contextPaths: (string | undefined)[] } | null = null;
for (const item of flat) {
if (item.excludePaths?.some((path) => matchLength(path) > 0)) continue;
const length = Math.max(matchLength(item.path), ...(item.activePaths?.map(matchLength) ?? [0]));
if (length > 0 && (!best || length > best.length)) {
best = {
title: item.title?.toString() ?? "",
path: normalizePath(item.path ?? ""),
length,
// Pages with their own row in the inner sub-sidenav do not get this
// entry as a parent crumb — see shouldShowParentNavCrumb.
contextPaths: item.contextItems?.map((context) => context.path) ?? [],
};
}
}
return best;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [menu, location.pathname]);
const currentCrumbLabel = breadcrumbTrail.at(-1)?.label || title || activeNavItem?.title || t("app.sidebar.dashboard");
// Clickable parent crumb on sub-pages: the responsible nav entry, unless it
// IS the current page or already covered by the trail (by label or by path).
const parentNavCrumb =
activeNavItem &&
shouldShowParentNavCrumb({
navPath: activeNavItem.path,
navTitle: activeNavItem.title,
currentPathname: location.pathname,
currentCrumbLabel,
trail: breadcrumbTrail,
navContextPaths: activeNavItem.contextPaths,
})
? activeNavItem
: null;
// ---- User + Theme-Toggle + Tenant-Switch ----
const isDarkMode = rootData.userSession?.lightOrDarkMode === "dark";
function onThemeToggle() {
@@ -164,30 +353,72 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
function renderNavItem(item: SideBarItem) {
const href = item.redirectTo || item.path;
const label = item.title?.toString() ?? "";
return (
<a key={item.id ?? href ?? label} href={href || undefined} title={label} className="w-full no-underline" {...uiIdAttrs(item)}>
<SidebarWithSections.NavItem
icon={item.icon}
selected={item.isActive}
variant={collapsed ? "icon-only" : "icon-and-text"}
className={item.disabled ? "pointer-events-none opacity-50" : undefined}
const navContent = (
<SidebarWithSections.NavItem
icon={item.icon}
selected={item.isActive}
variant={collapsed ? "icon-only" : "icon-and-text"}
className={item.disabled ? "pointer-events-none opacity-50" : undefined}
>
{label}
</SidebarWithSections.NavItem>
);
if (href && isInternalNavigationPath(href)) {
return (
<Link
key={item.id ?? href ?? label}
to={href}
title={label}
className="w-full no-underline"
data-navigation-kind="client"
onClick={() => setMobileOpen(false)}
{...uiIdAttrs(item)}
>
{label}
</SidebarWithSections.NavItem>
{navContent}
</Link>
);
}
return (
<a
key={item.id ?? href ?? label}
href={href || undefined}
title={label}
className="w-full no-underline"
data-navigation-kind="document"
onClick={() => setMobileOpen(false)}
{...uiIdAttrs(item)}
>
{navContent}
</a>
);
}
return (
<div className="flex h-screen w-full items-stretch bg-surface-neutral-primary" data-ui-id={UI_SURFACE_IDS.shell}>
<AppShellSidebarContext.Provider value={sidebarControls}>
<div className="bg-surface-neutral-primary flex h-screen w-full items-stretch overflow-hidden" data-ui-id={UI_SURFACE_IDS.shell}>
{/* Mobile-Backdrop */}
{mobileOpen ? <div className="fixed inset-0 z-40 bg-surface-neutral-overlay md:hidden" onClick={() => setMobileOpen(false)} aria-hidden /> : null}
{mobileOpen ? (
<div className="bg-surface-neutral-overlay fixed inset-0 z-40 md:hidden" onClick={() => closeMobileSidebar({ restoreFocus: true })} aria-hidden />
) : null}
<SidebarWithSections
ref={sidebarElement}
data-ui-id={sidebarSurfaceId}
data-ui-layout={layout}
role={isMobile ? "dialog" : undefined}
aria-modal={isMobile && mobileOpen ? true : undefined}
aria-hidden={isMobile && !mobileOpen ? true : undefined}
aria-label={isMobile ? t("components.sidebar.title") : undefined}
inert={isMobile && !mobileOpen}
variant={collapsed ? "closed" : "open"}
onToggleCollapse={() => setCollapsed((v) => !v)}
toggleLabel={t("components.sidebar.toggle")}
onLogoClick={
layout === "app" && params.tenant
? () => navigate(appPath({ tenantSlug: params.tenant!, path: "dashboard", mode: "host-aware" }))
: undefined
}
logoLabel={t("app.sidebar.dashboard")}
className={SubframeCore.twClassNames(
"z-50 max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:transition-transform",
mobileOpen ? "max-md:translate-x-0" : "max-md:-translate-x-full"
@@ -195,12 +426,7 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
>
<div data-ui-id={`${sidebarSurfaceId}.content`} className="flex w-full flex-col gap-1">
{navMain.map((group) => (
<SidebarWithSections.NavSection
key={group.id ?? group.title}
label={group.title}
showLabel={!collapsed && !!group.title}
{...uiIdAttrs(group)}
>
<SidebarWithSections.NavSection key={group.id ?? group.title} label={group.title} showLabel={!collapsed && !!group.title} {...uiIdAttrs(group)}>
{group.items.map((item) => renderNavItem(item))}
</SidebarWithSections.NavSection>
))}
@@ -209,17 +435,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
</div>
</SidebarWithSections>
<div className="flex h-full min-w-0 grow flex-col" data-ui-id={UI_SURFACE_IDS.shellInset}>
{/* macOS-style unread-notification toasts, top-right below the header. */}
{layout === "app" && params.tenant ? <NotificationToasts tenantSlug={params.tenant} items={shellNotifications.items} /> : null}
<div className="flex h-full min-h-0 min-w-0 grow flex-col overflow-hidden" data-ui-id={UI_SURFACE_IDS.shellInset}>
{/* Topbar (Davids HeaderNavigation: Breadcrumb + Suche + Bell + Avatar) */}
<header
className="flex h-14 w-full shrink-0 items-center justify-between gap-2 border-b border-solid border-border-default bg-surface-neutral-secondary pl-6 pr-3 py-3 mobile:px-4"
className="border-border-default bg-surface-neutral-secondary mobile:px-4 flex h-14 w-full shrink-0 items-center justify-between gap-2 border-b border-solid py-3 pr-3 pl-6"
data-ui-id={UI_SURFACE_IDS.shellHeader}
>
<div className="flex min-w-0 items-center gap-3" data-ui-id={UI_SURFACE_IDS.shellBreadcrumb}>
<button
ref={sidebarTriggerElement}
type="button"
className="inline-flex h-8 w-8 items-center justify-center rounded-md text-icon-neutral-secondary hover:bg-surface-neutral-tertiary md:hidden"
onClick={() => setMobileOpen((v) => !v)}
className="text-icon-neutral-secondary hover:bg-surface-neutral-tertiary inline-flex h-8 w-8 items-center justify-center rounded-md md:hidden"
onClick={() => {
if (mobileOpen) closeMobileSidebar({ restoreFocus: true });
else setMobileOpen(true);
}}
aria-label={t("shared.menu")}
data-ui-id={UI_ACTION_IDS.sidebarTrigger}
>
@@ -228,48 +461,119 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
<Breadcrumbs>
{currentTenant ? (
<>
<Breadcrumbs.Item>{currentTenant.name}</Breadcrumbs.Item>
{layout === "app" && params.tenant ? (
<Link to={appPath({ tenantSlug: params.tenant, path: "dashboard", mode: "host-aware" })} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{currentTenant.name}</Breadcrumbs.Item>
</Link>
) : (
<Breadcrumbs.Item className="text-text-neutral-secondary">{currentTenant.name}</Breadcrumbs.Item>
)}
<Breadcrumbs.Divider />
</>
) : null}
{parentNavCrumb ? (
<>
<Link to={parentNavCrumb.path} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{parentNavCrumb.title}</Breadcrumbs.Item>
</Link>
<Breadcrumbs.Divider />
</>
) : null}
{breadcrumbTrail.slice(0, -1).map((crumb) => (
<Fragment key={crumb.href}>
<Link to={crumb.href} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{crumb.label}</Breadcrumbs.Item>
</Link>
<Breadcrumbs.Divider />
</Fragment>
))}
<Breadcrumbs.Item active data-ui-id={UI_SURFACE_IDS.shellBreadcrumbCurrent}>
{title || t("app.sidebar.dashboard")}
{currentCrumbLabel}
</Breadcrumbs.Item>
</Breadcrumbs>
</div>
<div className="flex items-center gap-2 self-stretch pl-1" data-ui-id={UI_SURFACE_IDS.shellNavActions}>
<div
role="button"
tabIndex={0}
className="hidden cursor-pointer md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
{/*
MCP lives left of the search bar: connecting an AI client is a
per-user setup step, not a navigation target, so it stays out of
the sidebar. Hidden entirely when the tenant has no MCP module.
*/}
{layout === "app" && params.tenant && canConnectMcp ? <McpConnectLauncher tenantSlug={params.tenant} /> : null}
<button
type="button"
className="border-border-strong bg-surface-neutral-primary text-text-neutral-secondary hover:bg-surface-neutral-secondary focus-visible:bg-surface-neutral-secondary focus-visible:shadow-focus hidden h-8 min-w-[192px] cursor-pointer items-center gap-2.5 rounded-sm border px-3 text-left outline-none md:flex md:max-w-[320px] md:grow"
onClick={() => commandPalette.toggle()}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
commandPalette.toggle();
}
}}
aria-label={t("shared.search")}
data-ui-id={UI_ACTION_IDS.search}
>
<SearchInput className="pointer-events-none h-auto w-full min-w-0 max-w-none" size="small" fillContainer placeholder={t("shared.searchPlaceholder")} />
</div>
<a href={params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : "#"} aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })} data-ui-id={UI_ACTION_IDS.notifications}>
<IconButton variant="ghost" size="small" icon={<FeatherBell />} />
</a>
<FeatherSearch className="text-icon-neutral-tertiary size-4 shrink-0" />
<span className="text-body-default-regular-0 font-body-default-regular-0 min-w-0 grow truncate">{t("shared.searchPlaceholder")}</span>
<BadgeShortcut className="shrink-0">K</BadgeShortcut>
</button>
<IconButton
variant="ghost"
size="small"
icon={<FeatherSearch />}
className="md:hidden"
onClick={() => commandPalette.toggle()}
aria-label={t("shared.search")}
data-ui-id={UI_ACTION_IDS.searchMobile}
/>
{/*
The bell used to fall back to `href="#"` whenever no tenant was in
scope, which made it a dead link on every admin page (admin audit
2026-07-26, A11Y-01). The admin surface has its own notification
centre, so each layout now points at its own target.
*/}
{notificationsHref ? (
<Link
to={notificationsHref}
aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })}
className="hover:bg-surface-neutral-tertiary rounded-round focus-visible:shadow-focus relative flex h-8 w-8 items-center justify-center focus-visible:outline-none"
data-ui-id={UI_ACTION_IDS.notifications}
>
<SubframeCore.IconWrapper
aria-hidden="true"
className="text-icon-neutral-secondary inline-flex h-5 w-5 items-center justify-center [&>svg]:h-full [&>svg]:w-full"
>
<FeatherBell />
</SubframeCore.IconWrapper>
{shellNotifications.unreadCount > 0 ? (
<span
className="rounded-round bg-surface-feedback-solid-information text-text-neutral-on-solid absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center px-1 text-[10px] leading-none font-semibold"
data-ui-id="ui.notifications.bell.unreadCount"
>
{shellNotifications.unreadCount > 9 ? "9+" : shellNotifications.unreadCount}
</span>
) : null}
</Link>
) : null}
{user ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<Avatar className="cursor-pointer" border image={user.avatar ?? undefined} data-ui-id={UI_ACTION_IDS.more}>
<SubframeCore.DropdownMenu.Root modal={false}>
<div className="relative">
<Avatar aria-hidden="true" className="cursor-pointer" border image={user.avatar ?? undefined}>
{UserDisplayUtils.avatarText(user)}
</Avatar>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
aria-label={t("shell.profile.userMenu")}
className="rounded-round focus-visible:shadow-focus absolute inset-0 border-0 bg-transparent p-0 focus-visible:outline-none"
data-ui-id={UI_ACTION_IDS.more}
/>
</SubframeCore.DropdownMenu.Trigger>
</div>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu className="min-w-56">
<DropdownMenu.DropdownUserItem title={UserDisplayUtils.fullName(user)} subtitle={user.email} image={user.avatar ?? undefined} />
<DropdownMenu.DropdownUserItem
title={UserDisplayUtils.fullName(user)}
subtitle={user.email}
image={user.avatar ?? undefined}
initials={UserDisplayUtils.avatarText(user)}
/>
<DropdownMenu.DropdownDivider />
{layout === "app" && params.tenant ? (
<DropdownMenu.DropdownItem
@@ -292,11 +596,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
<>
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownNestedItem label={t("account.selectTenant.title")} icon={<FeatherUserSearch />}>
{myTenants.map((tenant) => (
<a key={tenant.id} href={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })} className="no-underline">
<DropdownMenu.DropdownItem selected={tenant.id === currentTenant.id}>{tenant.name}</DropdownMenu.DropdownItem>
</a>
))}
{/* The anchors are inline by default, which cut the selected row's
background off after the tenant name. `block w-full` lets each row
span the card like the trigger above it; the padding keeps the
expanded list from sitting flush against the trigger and the card edge. */}
<div className="flex w-full flex-col gap-1 pt-2 pb-1">
{myTenants.map((tenant) => (
<a
key={tenant.id}
href={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })}
className="block w-full no-underline"
>
{/* pl-9 lines the tenant name up with the trigger's label (px-3 + icon + gap). */}
<DropdownMenu.DropdownItem className="py-1.5 pr-3 pl-9" selected={tenant.id === currentTenant.id}>
{tenant.name}
</DropdownMenu.DropdownItem>
</a>
))}
</div>
</DropdownMenu.DropdownNestedItem>
</>
) : null}
@@ -308,13 +625,21 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
</div>
</header>
<main id="main-content" ref={mainElement} className="flex-1 overflow-auto focus:outline-hidden" tabIndex={-1} data-ui-id={UI_SURFACE_IDS.shellMain}>
<div key={params.tenant} className="pb-20 sm:pb-0">
{children}
</div>
<main
id="main-content"
ref={mainElement}
// scrollbar-gutter: stable reserves the scrollbar's space so the content
// column does not shift sideways when a route toggles the vertical
// scrollbar (no horizontal "bounce"). No-op with macOS overlay scrollbars.
className="min-h-0 flex-1 overflow-auto overscroll-y-contain [scrollbar-gutter:stable] focus:outline-hidden"
tabIndex={-1}
data-ui-id={UI_SURFACE_IDS.shellMain}
>
<RouteContentTransition>{children}</RouteContentTransition>
</main>
</div>
</div>
</div>
</AppShellSidebarContext.Provider>
);
}
@@ -0,0 +1,113 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { UI_PREFERENCES_STORAGE_KEY, UiPreferencesProvider, useUiPreferences } from "./UiPreferencesContext";
const originalLocalStorage = Object.getOwnPropertyDescriptor(window, "localStorage");
const originalGetAnimations = document.getAnimations;
function memoryStorage(): Storage {
const values = new Map<string, string>();
return {
get length() {
return values.size;
},
clear: () => values.clear(),
getItem: (key) => values.get(key) ?? null,
key: (index) => [...values.keys()][index] ?? null,
removeItem: (key) => values.delete(key),
setItem: (key, value) => values.set(key, value),
};
}
function PreferenceControls() {
const { preferences, preferencesReady, setAutoCollapseSidebar, setVisualEffectsEnabled } = useUiPreferences();
return (
<>
<output>ready:{String(preferencesReady)}</output>
<button onClick={() => setAutoCollapseSidebar(!preferences.autoCollapseSidebar)}>
auto:{String(preferences.autoCollapseSidebar)}
</button>
<button onClick={() => setVisualEffectsEnabled(!preferences.visualEffectsEnabled)}>
effects:{String(preferences.visualEffectsEnabled)}
</button>
</>
);
}
describe("UiPreferencesProvider", () => {
beforeEach(() => {
Object.defineProperty(window, "localStorage", { configurable: true, value: memoryStorage() });
});
afterEach(() => {
if (originalLocalStorage) Object.defineProperty(window, "localStorage", originalLocalStorage);
else delete (window as Partial<Window>).localStorage;
document.getAnimations = originalGetAnimations;
delete document.documentElement.dataset.hgVisualEffects;
vi.restoreAllMocks();
});
it("restores browser-local preferences and applies the visual-effects mode", async () => {
window.localStorage.setItem(
UI_PREFERENCES_STORAGE_KEY,
JSON.stringify({ autoCollapseSidebar: false, visualEffectsEnabled: false })
);
const cancel = vi.fn();
document.getAnimations = vi.fn(() => [{ cancel }] as unknown as Animation[]);
render(
<UiPreferencesProvider>
<PreferenceControls />
</UiPreferencesProvider>
);
await waitFor(() => expect(screen.getByRole("button", { name: "auto:false" })).toBeInTheDocument());
expect(screen.getByText("ready:true")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "effects:false" })).toBeInTheDocument();
expect(document.documentElement).toHaveAttribute("data-hg-visual-effects", "off");
expect(cancel).toHaveBeenCalledOnce();
});
it("does not expose the default auto-collapse value as ready before stored preferences load", async () => {
window.localStorage.setItem(
UI_PREFERENCES_STORAGE_KEY,
JSON.stringify({ autoCollapseSidebar: false, visualEffectsEnabled: true })
);
const renderStates: Array<{ ready: boolean; autoCollapse: boolean }> = [];
function PreferenceLifecycleProbe() {
const { preferences, preferencesReady } = useUiPreferences();
renderStates.push({ ready: preferencesReady, autoCollapse: preferences.autoCollapseSidebar });
return null;
}
render(
<UiPreferencesProvider>
<PreferenceLifecycleProbe />
</UiPreferencesProvider>
);
await waitFor(() => expect(renderStates.at(-1)).toEqual({ ready: true, autoCollapse: false }));
expect(renderStates).not.toContainEqual({ ready: true, autoCollapse: true });
});
it("persists changes and enables or disables effects immediately", () => {
render(
<UiPreferencesProvider>
<PreferenceControls />
</UiPreferencesProvider>
);
fireEvent.click(screen.getByRole("button", { name: "auto:true" }));
fireEvent.click(screen.getByRole("button", { name: "effects:true" }));
expect(JSON.parse(window.localStorage.getItem(UI_PREFERENCES_STORAGE_KEY) ?? "{}")).toEqual({
autoCollapseSidebar: false,
visualEffectsEnabled: false,
});
expect(document.documentElement).toHaveAttribute("data-hg-visual-effects", "off");
});
});
@@ -0,0 +1,110 @@
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState, type ReactNode } from "react";
export type UiPreferences = {
autoCollapseSidebar: boolean;
visualEffectsEnabled: boolean;
};
export const UI_PREFERENCES_STORAGE_KEY = "hg.ui-preferences.v1";
export const DEFAULT_UI_PREFERENCES: UiPreferences = {
autoCollapseSidebar: true,
visualEffectsEnabled: true,
};
type UiPreferencesContextValue = {
preferences: UiPreferences;
preferencesReady: boolean;
setAutoCollapseSidebar: (enabled: boolean) => void;
setVisualEffectsEnabled: (enabled: boolean) => void;
};
const NOOP_CONTEXT: UiPreferencesContextValue = {
preferences: DEFAULT_UI_PREFERENCES,
preferencesReady: true,
setAutoCollapseSidebar: () => undefined,
setVisualEffectsEnabled: () => undefined,
};
const UiPreferencesContext = createContext<UiPreferencesContextValue>(NOOP_CONTEXT);
function parseStoredPreferences(raw: string | null): UiPreferences {
if (!raw) return DEFAULT_UI_PREFERENCES;
try {
const value = JSON.parse(raw) as Partial<UiPreferences>;
return {
autoCollapseSidebar:
typeof value.autoCollapseSidebar === "boolean" ? value.autoCollapseSidebar : DEFAULT_UI_PREFERENCES.autoCollapseSidebar,
visualEffectsEnabled:
typeof value.visualEffectsEnabled === "boolean" ? value.visualEffectsEnabled : DEFAULT_UI_PREFERENCES.visualEffectsEnabled,
};
} catch {
return DEFAULT_UI_PREFERENCES;
}
}
function readStoredPreferences(): UiPreferences {
try {
return parseStoredPreferences(window.localStorage.getItem(UI_PREFERENCES_STORAGE_KEY));
} catch {
return DEFAULT_UI_PREFERENCES;
}
}
function applyVisualEffectsPreference(enabled: boolean): void {
if (typeof document === "undefined") return;
document.documentElement.dataset.hgVisualEffects = enabled ? "on" : "off";
if (!enabled) document.getAnimations?.().forEach((animation) => animation.cancel());
}
export function UiPreferencesProvider({ children }: { children: ReactNode }): React.JSX.Element {
const [preferences, setPreferences] = useState<UiPreferences>(DEFAULT_UI_PREFERENCES);
const [preferencesReady, setPreferencesReady] = useState(false);
useLayoutEffect(() => {
const stored = readStoredPreferences();
setPreferences(stored);
setPreferencesReady(true);
applyVisualEffectsPreference(stored.visualEffectsEnabled);
const handleStorage = (event: StorageEvent) => {
if (event.key !== UI_PREFERENCES_STORAGE_KEY) return;
const next = parseStoredPreferences(event.newValue);
setPreferences(next);
applyVisualEffectsPreference(next.visualEffectsEnabled);
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
const updatePreferences = useCallback((patch: Partial<UiPreferences>) => {
setPreferencesReady(true);
setPreferences((current) => {
const next = { ...current, ...patch };
try {
window.localStorage.setItem(UI_PREFERENCES_STORAGE_KEY, JSON.stringify(next));
} catch {
// A blocked storage API must not make a purely visual preference fatal.
}
applyVisualEffectsPreference(next.visualEffectsEnabled);
return next;
});
}, []);
const value = useMemo<UiPreferencesContextValue>(
() => ({
preferences,
preferencesReady,
setAutoCollapseSidebar: (enabled) => updatePreferences({ autoCollapseSidebar: enabled }),
setVisualEffectsEnabled: (enabled) => updatePreferences({ visualEffectsEnabled: enabled }),
}),
[preferences, preferencesReady, updatePreferences]
);
return <UiPreferencesContext.Provider value={value}>{children}</UiPreferencesContext.Provider>;
}
export function useUiPreferences(): UiPreferencesContextValue {
return useContext(UiPreferencesContext);
}
@@ -3,10 +3,12 @@ import { useTranslation } from "react-i18next";
import Modal from "~/components/ui/modals/Modal";
import { LogWithDetails } from "~/utils/db/logs.db.server";
import { redactDiagnosticJsonString } from "~/utils/redaction";
import { useCopyToast } from "~/hooks/use-copy-toast";
export default function LogDetailsButton({ item }: { item: LogWithDetails }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const copyText = useCopyToast();
function stringifyDetails() {
return redactDiagnosticJsonString(item.details);
@@ -27,9 +29,7 @@ export default function LogDetailsButton({ item }: { item: LogWithDetails }) {
<div>
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(stringifyDetails());
}}
onClick={() => void copyText(stringifyDetails(), { successKey: "models.log.detailsCopied" })}
className="bg-theme-100 text-theme-700 hover:bg-theme-200 focus:ring-ring inline-flex items-center rounded-md border border-transparent px-3 py-2 text-sm font-medium leading-4 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
>
{t("shared.copy")}
@@ -90,7 +90,8 @@ describe("log action i18n", () => {
.filter((action): action is string => typeof action === "string");
});
expect(actions).toEqual(expect.arrayContaining(["admin.pricing.plan.created", "portal.pricing.plan.updated"]));
expect(actions).toEqual(expect.arrayContaining(["admin.pricing.plan.created", "admin.pricing.deletedPlan"]));
expect(actions).not.toContain("admin.pricing.createdPlans");
for (const action of actions) {
expect(getLogActionI18nKey(action), action).toBeDefined();
}
@@ -42,33 +42,33 @@ describe("AdminAuditLogToolbar", () => {
expect(screen.getByText("models.tenant.object")).toBeInTheDocument();
});
it("preserves active filters while replacing stale pagination with CSV export", () => {
it("preserves active filters while dropping stale pagination on the export href", () => {
renderToolbar("/audit-trails?q=login&action=auth&url=%2Flogin&tenantId=tenant-1&page=3&pageSize=25");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/audit-trails");
expect(exportUrl.pathname).toBe("/audit-trails-export");
expect(exportUrl.searchParams.get("q")).toBe("login");
expect(exportUrl.searchParams.get("action")).toBe("auth");
expect(exportUrl.searchParams.get("url")).toBe("/login");
expect(exportUrl.searchParams.get("tenantId")).toBe("tenant-1");
expect(exportUrl.searchParams.get("pageSize")).toBe("25");
expect(exportUrl.searchParams.get("page")).toBeNull();
expect(exportUrl.searchParams.get("export")).toBe("csv");
});
it("replaces an existing export value with csv", () => {
it("drops a stale export param from the current search", () => {
renderToolbar("/audit-trails?export=json&userId=user-1");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/audit-trails-export");
expect(exportUrl.searchParams.get("userId")).toBe("user-1");
expect(exportUrl.searchParams.get("export")).toBe("csv");
expect(exportUrl.searchParams.get("export")).toBeNull();
});
it("creates a valid CSV export href without existing search params", () => {
renderToolbar("/audit-trails");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/audit-trails?export=csv");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/audit-trails-export");
});
});
@@ -15,8 +15,9 @@ export default function AdminAuditLogToolbar({ filters }: Props) {
const exportLabel = getFallbackTranslation(t("shared.export"), "Export");
const exportSearchParams = new URLSearchParams(location.search);
exportSearchParams.delete("page");
exportSearchParams.set("export", "csv");
const exportHref = adminPath(`audit-trails?${exportSearchParams.toString()}`, { mode: "host-aware" });
exportSearchParams.delete("export");
const exportQuery = exportSearchParams.toString();
const exportHref = adminPath(exportQuery ? `audit-trails-export?${exportQuery}` : "audit-trails-export", { mode: "host-aware" });
return (
<div className="flex items-center gap-2">
@@ -1,4 +1,4 @@
import type { ReactNode } from "react";
import type { ComponentProps, ReactNode } from "react";
import { twClassNames } from "~/ui/utils";
import { Card } from "~/ui/components/Card";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
@@ -9,9 +9,9 @@ type CardSize = "small" | "medium" | "large" | "extra-large";
type SubtitleVariant = "regular-0" | "regular-150" | "medium-150";
const SUBTITLE_CLS: Record<SubtitleVariant, string> = {
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary",
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary",
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary",
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary",
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary",
};
// Gemeinsames Auth-Layout nach Davids WF-P2-Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
@@ -30,6 +30,7 @@ export function AuthShell({
cardClassName = "max-w-[448px]",
showLogo = true,
logoIconOnly = false,
logoSize = "64",
titleAlign = "center",
headerGap = "gap-1.5",
subtitleVariant = "regular-150",
@@ -47,6 +48,8 @@ export function AuthShell({
showLogo?: boolean;
/** Icon-only-Logo (wie Davids Auth-Screens, Logo size=64 hideText) statt vollem Wortmarken-Logo. */
logoIconOnly?: boolean;
/** Visuelle Logo-Groesse. Auth-Defaults bleiben bei 64; breite Mehrschritt-Flows duerfen kompakter sein. */
logoSize?: ComponentProps<typeof Logo>["size"];
/** Titel-/Untertitel-Ausrichtung. David: Login=center, Signup/Forgot/Reset/2FA=start. */
titleAlign?: "center" | "start";
/** Abstand Titel<->Untertitel. David: S01 Login = gap-1.5, sonst gap-1. */
@@ -60,7 +63,7 @@ export function AuthShell({
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
data-ui-id={dataUiId}
>
{showLogo ? <Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
{showLogo ? <Logo size={logoSize} showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
<Card size={cardSize} variant="default" className={twClassNames("items-stretch", cardClassName)}>
<div className={twClassNames("flex w-full flex-col", headerGap, titleAlign === "center" ? "items-center" : "items-start")}>
<h1 className="text-heading- font-heading- text-text-neutral-primary">{title}</h1>
@@ -130,7 +133,7 @@ export function AuthDivider({ label, labelSize = "small" }: { label: ReactNode;
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
<span
className={twClassNames(
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary",
{
"text-body-extra-small-regular-150 font-body-extra-small-regular-150":
labelSize === "extra-small",
@@ -0,0 +1,61 @@
import "@testing-library/jest-dom";
import { cleanup, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import Icon from "./Icon";
import Logo from "./Logo";
import LogoLightMode from "./LogoLightMode";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => ({ "shared.icon": "Symbol", "shared.logo": "Logo" })[key] ?? key,
}),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
appConfiguration: {
app: { name: "HiveGrid" },
branding: {
icon: "/icon-light.svg",
iconDarkMode: "/icon-dark.svg",
logo: "/logo-light.svg",
logoDarkMode: "/logo-dark.svg",
},
},
}),
}));
afterEach(cleanup);
describe("brand asset alt text", () => {
it("localizes the configured product logo label", () => {
render(
<MemoryRouter>
<Logo />
</MemoryRouter>
);
expect(screen.getAllByAltText("HiveGrid Logo")).toHaveLength(2);
});
it("localizes the configured product icon label", () => {
render(
<MemoryRouter>
<Icon />
</MemoryRouter>
);
expect(screen.getAllByAltText("HiveGrid Symbol")).toHaveLength(2);
});
it("localizes the light-mode product logo label", () => {
render(
<MemoryRouter>
<LogoLightMode />
</MemoryRouter>
);
expect(screen.getByAltText("HiveGrid Logo")).toBeInTheDocument();
});
});
@@ -3,6 +3,7 @@ import { Link } from "react-router";
import { iconLight, iconDark } from "~/assets/brand/default";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,17 +13,20 @@ interface Props {
export default function Icon({ className = "", size = "h-9", fromConfig = true }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const iconAlt = productName ? `${productName} ${t("shared.icon")}` : t("shared.icon");
return (
<Link to="/" className={clsx(className, "flex")}>
{fromConfig && appConfiguration?.branding.icon ? (
<Fragment>
<img className={clsx(size, "hidden w-auto dark:block")} src={appConfiguration.branding.iconDarkMode ?? appConfiguration.branding.icon} alt="Icon" />
<img className={clsx(size, "w-auto dark:hidden")} src={appConfiguration.branding.icon} alt="Icon" />
<img className={clsx(size, "hidden w-auto dark:block")} src={appConfiguration.branding.iconDarkMode ?? appConfiguration.branding.icon} alt={iconAlt} />
<img className={clsx(size, "w-auto dark:hidden")} src={appConfiguration.branding.icon} alt={iconAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "hidden w-auto dark:block")} src={iconDark} alt="Logo" />
<img className={clsx(size, "w-auto dark:hidden")} src={iconLight} alt="Logo" />
<img className={clsx(size, "hidden w-auto dark:block")} src={iconDark} alt={iconAlt} />
<img className={clsx(size, "w-auto dark:hidden")} src={iconLight} alt={iconAlt} />
</Fragment>
)}
</Link>
@@ -3,6 +3,7 @@ import clsx from "clsx";
import { Link } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,6 +13,9 @@ interface Props {
export default function Logo({ className = "", size = "h-9", to }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const logoAlt = productName ? `${productName} ${t("shared.logo")}` : t("shared.logo");
return (
<Link to={to ?? "/"} className={clsx(className, "flex")}>
{/* <BrandLogo className="h-10 w-auto mx-auto" /> */}
@@ -20,14 +24,14 @@ export default function Logo({ className = "", size = "h-9", to }: Props) {
<img
className={clsx(size, "mx-auto hidden w-auto dark:block")}
src={appConfiguration.branding.logoDarkMode ?? appConfiguration.branding.logo}
alt="Logo"
alt={logoAlt}
/>
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={appConfiguration.branding.logo} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={appConfiguration.branding.logo} alt={logoAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "mx-auto hidden w-auto dark:block")} src={logoDark} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={logoLight} alt="Logo" />
<img className={clsx(size, "mx-auto hidden w-auto dark:block")} src={logoDark} alt={logoAlt} />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={logoLight} alt={logoAlt} />
</Fragment>
)}
</Link>
@@ -3,6 +3,7 @@ import clsx from "clsx";
import { Link } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,16 +13,19 @@ interface Props {
export default function LogoLightMode({ className = "", size = "h-9", to }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const logoAlt = productName ? `${productName} ${t("shared.logo")}` : t("shared.logo");
return (
<Link to={to ?? "/"} className={clsx(className, "flex")}>
{/* <BrandLogo className="h-10 w-auto mx-auto" /> */}
{appConfiguration?.branding.logo ? (
<Fragment>
<img className={clsx(size, "mx-auto w-auto")} src={appConfiguration.branding.logo} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto")} src={appConfiguration.branding.logo} alt={logoAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "mx-auto w-auto")} src={logoLight} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto")} src={logoLight} alt={logoAlt} />
</Fragment>
)}
</Link>
@@ -0,0 +1,30 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import Captcha from "./Captcha";
describe("Captcha CAP status contract", () => {
it("reports solve, reset and client errors to the enclosing form", () => {
const onStatusChange = vi.fn();
const { container } = render(
<Captcha enabled provider="cap" instanceUrl="https://captcha.example.test" sitekey="registration" onStatusChange={onStatusChange} />
);
const widget = container.querySelector("cap-widget");
expect(widget).not.toBeNull();
expect(onStatusChange).toHaveBeenLastCalledWith("pending");
widget!.dispatchEvent(new CustomEvent("solve"));
expect(onStatusChange).toHaveBeenLastCalledWith("solved");
widget!.dispatchEvent(new CustomEvent("reset"));
expect(onStatusChange).toHaveBeenLastCalledWith("pending");
widget!.dispatchEvent(new CustomEvent("error"));
expect(onStatusChange).toHaveBeenLastCalledWith("error");
});
it("renders nothing when the public provider configuration is incomplete", () => {
const { container } = render(<Captcha enabled provider="cap" />);
expect(container).toBeEmptyDOMElement();
});
});
@@ -1,4 +1,6 @@
import { createElement, useEffect, useRef } from "react";
import type { Ref } from "react";
import { getCurrentDocumentCspNonce } from "~/utils/security/documentCspNonce";
interface Props {
/** Render the captcha widget. When false (or unconfigured) nothing is rendered. */
@@ -9,6 +11,8 @@ interface Props {
instanceUrl?: string;
/** Public sitekey for this surface. */
sitekey?: string;
/** Reports whether a reusable form may submit a fresh proof. */
onStatusChange?: (status: "pending" | "solved" | "error") => void;
}
// mCaptcha's vanilla glue mounts the widget into an element with this id and
@@ -23,13 +27,33 @@ const MOUNT_ID = "mcaptcha__widget-container";
* hidden token field (`cap-token` or `mcaptcha__token`), so it is submitted
* with the form and verified server-side by `@hivegrid/captcha`.
*
* Client load failures are non-fatal. The server verifier applies
* CAPTCHA_FAIL_OPEN for provider outages, while a missing token remains a hard
* failure when captcha is required.
* Client load failures leave the form unsolved. The server verifier fails
* closed in deployed runtimes; a local development/test process may explicitly
* opt into fail-open behavior.
*/
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey }: Props) {
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey, onStatusChange }: Props) {
const active = enabled && Boolean(instanceUrl && sitekey);
const initialized = useRef(false);
const capWidgetRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (!active) return;
onStatusChange?.("pending");
if (provider !== "cap") return;
const widget = capWidgetRef.current;
if (!widget) return;
const solved = () => onStatusChange?.("solved");
const reset = () => onStatusChange?.("pending");
const failed = () => onStatusChange?.("error");
widget.addEventListener("solve", solved);
widget.addEventListener("reset", reset);
widget.addEventListener("error", failed);
return () => {
widget.removeEventListener("solve", solved);
widget.removeEventListener("reset", reset);
widget.removeEventListener("error", failed);
};
}, [active, onStatusChange, provider]);
useEffect(() => {
if (!active || initialized.current) return;
@@ -62,15 +86,16 @@ export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, s
Cap's custom element injects <input name="cap-token"> into the
enclosing form when solved.
*/}
{createCapWidget(instanceUrl!, sitekey!)}
{createCapWidget(instanceUrl!, sitekey!, capWidgetRef)}
</>
);
}
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
}
function createCapWidget(instanceUrl: string, sitekey: string) {
function createCapWidget(instanceUrl: string, sitekey: string, ref: Ref<HTMLElement>) {
return createElement("cap-widget", {
ref,
required: true,
"data-cap-api-endpoint": `${instanceUrl.replace(/\/+$/, "")}/${sitekey}/`,
"data-ui-id": "ui.captcha.mount",
@@ -88,6 +113,8 @@ function loadCapAssets(instanceUrl: string): void {
script.defer = true;
script.src = scriptSrc;
script.dataset.capWidgetLoader = "true";
const nonce = getCurrentDocumentCspNonce(document);
if (nonce) script.nonce = nonce;
document.head.appendChild(script);
}
@@ -31,7 +31,7 @@ describe("CookiesList", () => {
fireEvent.click(screen.getByRole("button", { name: /cookies\.categories\.REQUIRED\.name/i }));
expect(screen.getByText("cookies.expiry.oneMonth")).toBeInTheDocument();
expect(screen.getAllByText("cookies.expiry.oneMonth").length).toBeGreaterThan(0);
expect(screen.queryByText("1 month")).not.toBeInTheDocument();
});
});
@@ -10,13 +10,23 @@ vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
Link: ({ children, to, onClick, className }: { children: React.ReactNode; to: string; onClick?: React.MouseEventHandler<HTMLAnchorElement>; className?: string }) => (
Link: ({
children,
to,
onClick,
className,
}: {
children: React.ReactNode;
to: string;
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
className?: string;
}) => (
<a href={to} onClick={onClick} className={className}>
{children}
</a>
),
useNavigate: () => navigate,
useLocation: () => ({ pathname: "/acme/settings/api/keys/new" }),
useLocation: () => ({ pathname: "/acme/api/keys/new" }),
useMatches: () => [],
};
});
@@ -37,7 +47,7 @@ describe("ApiKeyCreatedModal", () => {
});
it("labels the plaintext as one-time and copies it only when requested", async () => {
render(<ApiKeyCreatedModal apiKey={{ key: "tc_live_plaintext_secret_once", alias: "Primary integration" }} redirectTo="/acme/settings/api/keys" />);
render(<ApiKeyCreatedModal apiKey={{ key: "tc_live_plaintext_secret_once", alias: "Primary integration" }} redirectTo="/acme/api/keys" />);
expect(screen.getByText("models.apiKey.createdTitle")).toBeInTheDocument();
expect(screen.getByText("models.apiKey.aliasWithValue")).toBeInTheDocument();
@@ -5,6 +5,7 @@ import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import InputText from "~/components/ui/input/InputText";
import OpenModal from "~/components/ui/modals/OpenModal";
import { useCopyToast } from "~/hooks/use-copy-toast";
interface Props {
apiKey: {
@@ -19,10 +20,14 @@ export default function ApiKeyCreatedModal({ apiKey, redirectTo, action = "creat
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const isRotated = action === "rotated";
const copyText = useCopyToast();
async function copyApiKey() {
await navigator.clipboard.writeText(apiKey.key);
setCopied(true);
const didCopy = await copyText(apiKey.key, {
successKey: "models.apiKey.copied",
errorKey: "models.apiKey.copyFailed",
});
if (didCopy) setCopied(true);
}
return (
@@ -13,7 +13,7 @@ import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
interface Props {
item?: RedactedApiKeyWithDetails | null;
tenants?: Tenant[];
tenants?: Pick<Tenant, "id" | "name">[];
canUpdate?: boolean;
canDelete?: boolean;
canRotate?: boolean;
@@ -5,7 +5,6 @@ describe("API log details i18n", () => {
it("keeps visible API log labels behind semantic translation keys", () => {
const tableSource = readRepoFile("apps/web/app/components/core/apiKeys/ApiKeyLogsTable.tsx");
const keysSource = readRepoFile("apps/web/app/components/core/apiKeys/ApiKeysTable.tsx");
const summarySource = readRepoFile("apps/web/app/modules/api/components/ApiKeyLogsSummary.tsx");
const apiDetailsSource = readRepoFile("apps/web/app/modules/api/components/ApiKeyLogsDetails.tsx");
const logDetailsSource = readRepoFile("apps/web/app/components/app/events/LogDetailsButton.tsx");
@@ -15,7 +14,7 @@ describe("API log details i18n", () => {
expect(tableSource).toContain('t("shared.notSet")');
expect(apiDetailsSource).toContain('t("shared.notSet")');
expect(logDetailsSource).toContain("models.log.details");
for (const source of [tableSource, keysSource, summarySource, apiDetailsSource]) {
for (const source of [tableSource, keysSource, apiDetailsSource]) {
expect(source).toContain("useLocaleFormatters");
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
expect(source).not.toContain('from "~/utils/shared/NumberUtils"');
@@ -1,8 +1,17 @@
// API keys list (tenant settings + admin) on the interim ~/ui kit: search
// filters client-side, "Neu" links to the create route, rows link to the edit
// route. Keys render redacted only (prefix…last four); the raw secret never
// reaches this component (RedactedApiKeyWithDetails).
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
import EmptyState from "~/components/ui/emptyState/EmptyState";
import InputSearch from "~/components/ui/input/InputSearch";
import { Link } from "react-router";
import { FeatherPlus } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { FacetFilterBar } from "~/components/screens/shared/FacetFilterBar";
import { useLocaleFormatters } from "~/locale/format";
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
@@ -11,16 +20,14 @@ interface Props {
withTenant?: boolean;
canCreate?: boolean;
}
type Header = {
name?: string;
title: string;
};
type ApiKeyTableRow = {
item: RedactedApiKeyWithDetails;
redactedKey: string;
};
const cellText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
function getRedactedKey(item: RedactedApiKeyWithDetails) {
return [item.keyPrefix, item.keyLastFour ? `••••${item.keyLastFour}` : undefined].filter(Boolean).join("…") || "••••";
}
@@ -31,26 +38,16 @@ export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
const [searchInput, setSearchInput] = useState("");
const headers = useMemo(() => {
const nextHeaders: Header[] = [];
if (withTenant) {
nextHeaders.push({ name: "tenant", title: t("models.tenant.object") });
}
nextHeaders.push({ name: "key", title: t("models.apiKey.key") });
nextHeaders.push({ name: "alias", title: t("models.apiKey.alias") });
nextHeaders.push({ name: "usage", title: t("models.apiKey.usage") });
nextHeaders.push({ name: "expires", title: t("models.apiKey.expires") });
nextHeaders.push({ name: "createdAt", title: t("shared.createdAt") });
nextHeaders.push({ name: "createdByUser", title: t("shared.createdBy") });
return nextHeaders;
}, [t, withTenant]);
const filteredSortedRows = useMemo<ApiKeyTableRow[]>(() => {
if (!items) {
return [];
}
const normalizedSearchInput = searchInput.trim().toUpperCase();
const filtered = normalizedSearchInput ? items.filter((item) => item.tenant?.name?.toString()?.toUpperCase().includes(normalizedSearchInput)) : [...items];
const filtered = normalizedSearchInput
? items.filter((item) =>
[item.tenant?.name, item.alias, item.keyPrefix].some((value) => value?.toString().toUpperCase().includes(normalizedSearchInput))
)
: [...items];
return filtered
.sort((x, y) => {
@@ -65,117 +62,94 @@ export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
}));
}, [items, searchInput]);
// function deleteApiKey(item: ApiKey) {
// if (confirmDelete.current) {
// confirmDelete.current.setValue(item);
// confirmDelete.current.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
// }
// }
// function confirmDeleteApiKey(item: ApiKey) {
// const form = new FormData();
// form.set("action", "delete");
// form.set("id", item.id);
// submit(form, {
// method: "post",
// });
// }
return (
<div className="space-y-2">
<InputSearch value={searchInput} setValue={setSearchInput} onNewRoute={canCreate ? "new" : ""} />
{(() => {
if (filteredSortedRows.length === 0) {
return (
<div>
<EmptyState
className="bg-background"
captions={{
thereAreNo: t("shared.noRecords"),
}}
/>
</div>
);
} else {
return (
<div>
<div>
<div className="flex flex-col">
<div className="overflow-x-auto">
<div className="inline-block min-w-full py-2 align-middle">
<div className="border-border overflow-hidden border shadow-xs sm:rounded-lg">
<table className="divide-border min-w-full divide-y">
<thead className="bg-secondary">
<tr>
{headers.map((header, idx) => {
return (
<th
key={idx}
scope="col"
className="text-muted-foreground truncate px-3 py-2 text-left text-xs font-medium tracking-wider select-none"
>
<div className="text-muted-foreground flex items-center space-x-1">
<div>{header.title}</div>
</div>
</th>
);
})}
</tr>
</thead>
<tbody className="divide-border bg-background divide-y">
{filteredSortedRows.map(({ item, redactedKey }, idx) => {
return (
<tr key={idx}>
{withTenant && (
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
{item.tenant?.name ?? t("models.apiKey.adminTenant")}
</td>
)}
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<span className="font-mono text-xs" aria-label={`${t("models.apiKey.key")} ${redactedKey}`}>
{redactedKey}
</span>
{!item.active && <span className="ml-2 text-red-600">{t("shared.inactive")}</span>}
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">{item.alias}</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
{formatters.number(item._count.apiKeyLogs)}{" "}
{item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<time
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
title={item.expires ? formatters.dateTime(item.expires) : undefined}
>
{item.expires === null ? <span>-</span> : <span>{formatters.relativeDate(item.expires)}</span>}
</time>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt)}>
{formatters.dateTime(item.createdAt)}
</time>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<span className="text-muted-foreground text-xs">{item.createdByUser.email}</span>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<div className="flex items-center space-x-2">
<ButtonTertiary to={item.id}>{t("shared.edit")}</ButtonTertiary>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
);
<div className="flex w-full flex-col gap-4" data-ui-id="ui.settings.apiKeys.table">
{/* The same bar the calls and overview tabs carry — this list is fully
loaded, so the term filters client-side and there are no facets. */}
<FacetFilterBar
variant="inline"
uiId="ui.settings.apiKeys"
facets={[]}
onToggle={() => undefined}
search={searchInput}
onSearchChange={setSearchInput}
searchPlaceholder={t("shared.searchDot")}
onReset={() => setSearchInput("")}
labels={{ reset: t("shared.reset"), removeChip: t("settings.members.filters.removeChip") }}
trailing={
canCreate ? (
<Link to="new" data-ui-id="ui.settings.apiKeys.new">
<Button icon={<FeatherPlus />}>{t("shared.new")}</Button>
</Link>
) : undefined
}
})()}
/>
{filteredSortedRows.length === 0 ? (
<div data-ui-id="ui.settings.apiKeys.empty">
<EmptyState title={t("shared.noRecords")} />
</div>
) : (
<div className="w-full overflow-x-auto">
<Table
header={
<Table.HeaderRow>
{withTenant ? <Table.HeaderCell>{t("models.tenant.object")}</Table.HeaderCell> : null}
<Table.HeaderCell>{t("models.apiKey.key")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.alias")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.usage")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.expires")}</Table.HeaderCell>
<Table.HeaderCell>{t("shared.createdAt")}</Table.HeaderCell>
<Table.HeaderCell>{t("shared.createdBy")}</Table.HeaderCell>
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{filteredSortedRows.map(({ item, redactedKey }) => (
<Table.Row key={item.id} data-row-id={item.id}>
{withTenant ? <Table.Cell><span className={cellText}>{item.tenant?.name ?? t("models.apiKey.adminTenant")}</span></Table.Cell> : null}
<Table.Cell>
<div className="flex items-center gap-2">
<span className="font-mono text-body-small-regular-0 text-text-neutral-primary" aria-label={`${t("models.apiKey.key")} ${redactedKey}`}>
{redactedKey}
</span>
{!item.active ? <BadgeFeedback farbe="subtle-negative" size="small">{t("shared.inactive")}</BadgeFeedback> : null}
</div>
</Table.Cell>
<Table.Cell><span className={cellText}>{item.alias}</span></Table.Cell>
<Table.Cell>
<span className={cellText}>
{formatters.number(item._count.apiKeyLogs)} {item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
</span>
</Table.Cell>
<Table.Cell>
<span className={cellText}>
<time
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
title={item.expires ? formatters.dateTime(item.expires) : undefined}
>
{item.expires === null ? "-" : formatters.relativeDate(item.expires)}
</time>
</span>
</Table.Cell>
<Table.Cell>
<span className={cellText}>
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt)}>
{formatters.dateTime(item.createdAt)}
</time>
</span>
</Table.Cell>
<Table.Cell><span className={cellText}>{item.createdByUser.email}</span></Table.Cell>
<Table.Cell>
<Link to={item.id}>
<Button variant="tertiary" size="small">{t("shared.edit")}</Button>
</Link>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
</div>
);
}
@@ -7,6 +7,7 @@ import InputText from "~/components/ui/input/InputText";
import CollapsibleRow from "~/components/ui/tables/CollapsibleRow";
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
import { useLocaleFormatters } from "~/locale/format";
import { getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon, PlusIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -66,7 +67,7 @@ export default function PricingFeaturesForm({ items, setItems }: Props) {
{item.type === SubscriptionFeatureLimitType.MONTHLY && <span>{t("admin.pricing.features.limitTypes.monthly")}</span>}
{item.type === SubscriptionFeatureLimitType.MAX && <span>{t("admin.pricing.features.limitTypes.max")}</span>}
{item.type === SubscriptionFeatureLimitType.UNLIMITED && <span>{t("admin.pricing.features.limitTypes.unlimited")}</span>}
<div>{t(item.title)}</div>
<div>{getSubscriptionFeatureTitle(t, item, { 0: formatters.number(item.value) })}</div>
{(item.type === SubscriptionFeatureLimitType.MONTHLY || item.type === SubscriptionFeatureLimitType.MAX) && <div>{formatters.number(item.value)}</div>}
</>
) : (
@@ -14,7 +14,6 @@ import ToggleBillingPeriod from "../settings/subscription/ToggleBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import PricingFeaturesTable from "./PricingFeaturesTable";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import FlatPrices from "./FlatPrices";
import UsageBasedPrices from "./UsageBasedPrices";
@@ -49,15 +48,10 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
const navigate = useNavigate();
const submit = useSubmit();
let pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
const pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
name: t("pricing." + PricingModel[value]),
value,
}));
if (isPortalPlan) {
pricingModels = pricingModels.filter(
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED
);
}
const inputTitle = useRef<RefInputText>(null);
const confirmRemove = useRef<RefConfirmModal>(null);
@@ -433,6 +427,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
usageBasedPrices={usageBasedPrices}
billingProviderCoupon={null}
isPreview={true}
showFeatures
/>
</div>
</SettingSection>
@@ -360,7 +360,7 @@ export default function UsageBasedPricesUnit({ item, onUpdate, disabled }: Props
<TrashIcon className="text-muted-foreground h-4 w-4" />
</div>
),
onClick: (idx, i) => removeTier(idx),
onClick: (idx, _i) => removeTier(idx),
disabled: () => disabled || allTiers.length === 1,
},
]}
@@ -380,7 +380,7 @@ export default function UsageBasedPricesUnit({ item, onUpdate, disabled }: Props
<TrashIcon className="text-muted-foreground h-4 w-4" />
</div>
),
onClick: (idx, i) => removeTier(idx),
onClick: (idx, _i) => removeTier(idx),
disabled: () => disabled || allTiers.length === 1,
},
]}
@@ -16,7 +16,7 @@ interface Props {
canReorder?: boolean;
}
export default function PermissionsTable({ items, className, canCreate, canUpdate = true, tenantId, canReorder }: Props) {
export default function PermissionsTable({ items, className: _className, canCreate: _canCreate, canUpdate = true, tenantId: _tenantId, canReorder }: Props) {
const { t } = useTranslation();
const [actions, setActions] = useState<any[]>([]);
@@ -24,7 +24,7 @@ interface Props {
};
}
export default function UserRolesTable({ items, roles, className, onChange, tenantId = null, disabled, onRoleClick, actions }: Props) {
export default function UserRolesTable({ items, roles, className: _className, onChange, tenantId = null, disabled, onRoleClick, actions }: Props) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
@@ -35,6 +35,10 @@ describe("roleDisplay", () => {
"translated:models.role.defaultRoles.names.billingAdmin"
);
expect(roleDisplayName({ name: "Regional Admin", description: "Custom tenant role" }, t)).toBe("Regional Admin");
expect(roleDisplayName({ name: "Geschäftsführer", description: null }, t)).toBe(
"translated:models.role.templateRoles.names.managingDirector"
);
expect(roleDisplayName({ name: "Monteur", description: null }, t)).toBe("translated:models.role.templateRoles.names.fieldTechnician");
});
it("localizes seeded default role descriptions without changing custom descriptions", () => {
@@ -66,6 +70,18 @@ describe("roleDisplay", () => {
expect(roleDisplayDescription({ name: "Approver", description: "Genehmigt Rechnungen." }, tNs)).toBe("Genehmigt Rechnungen.");
});
it("localizes legacy German SHK descriptions for existing tenants", () => {
expect(
roleDisplayDescription(
{
name: "Vertriebsleiter",
description: "Leitung Vertrieb: CRM- und Lead-Verwaltung, Vertriebs-Reports und Umsatzkennzahlen.",
},
t
)
).toBe("translated:models.role.templateRoles.descriptions.salesManager");
});
it("keeps the raw database value when no translator is provided", () => {
expect(roleDisplayName({ name: "SuperUser", description: "Has all app permissions" })).toBe("SuperUser");
expect(roleDisplayDescription({ name: "SuperUser", description: "Has all app permissions" })).toBe("Has all app permissions");
@@ -84,6 +100,12 @@ describe("roleDisplay", () => {
expect(permissionDisplayDescription({ name: "app.settings.members.view", description: "Default permission app.settings.members.view" }, t)).toBe(
"translated:models.permission.defaultPermissions.description"
);
expect(permissionDisplayName({ name: "portal.admin", description: "Default permission portal.admin" }, t)).toBe(
"translated:models.permission.defaultPermissions.title"
);
expect(permissionDisplayName({ name: "portal.activity.manage", description: "Default permission portal.activity.manage" }, t)).toBe(
"translated:models.permission.defaultPermissions.title"
);
});
it("has translation coverage for every default permission seed scope and action", () => {
@@ -58,6 +58,28 @@ const DEFAULT_ROLE_DESCRIPTION_KEYS: Record<string, string> = {
"Has regular permissions": "regularPermissions",
};
const SHK_TEMPLATE_ROLE_NAME_KEYS: Record<string, string> = {
"Geschäftsführer": "managingDirector",
Vertriebsleiter: "salesManager",
Vertriebler: "salesRepresentative",
"Büro/Backoffice": "backOffice",
Marketing: "marketing",
"Projektleiter/Bauleiter": "projectManager",
Monteur: "fieldTechnician",
};
// Existing tenants can still carry the original German seed copy. Resolve it
// at display time so they become locale-aware without overwriting tenant edits.
const LEGACY_SHK_TEMPLATE_ROLE_DESCRIPTION_KEYS: Record<string, string> = {
"Voller Zugriff auf alle Bereiche inklusive Nutzerverwaltung, Rollen und Abrechnung.": "managingDirector",
"Leitung Vertrieb: CRM- und Lead-Verwaltung, Vertriebs-Reports und Umsatzkennzahlen.": "salesManager",
"Vertrieb im Tagesgeschäft: eigene Kontakte und Projekte, Angebote und Termine.": "salesRepresentative",
"Backoffice: Kontakte, Projektabwicklung, Dateien, Personal, Terminbuchung und Rechnungswesen.": "backOffice",
"Marketing: Kampagnen, Formulare, Lead-Erfassung und Segmentierung.": "marketing",
"Projekt-/Bauleitung: eigene Projekte steuern, Plantafel, Aufgaben, Dateien und Abnahmen.": "projectManager",
"Feld/Baustelle: eigene Aufträge, Aufgaben, Abnahmen, Foto-Formulare und Dateien.": "fieldTechnician",
};
const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
view: "view",
create: "create",
@@ -69,6 +91,7 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
reset: "reset",
subscription: "subscription",
use: "use",
export: "export",
users: "users",
impersonate: "impersonate",
changePassword: "changePassword",
@@ -79,9 +102,13 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
read_own_pl: "read_own_pl",
read_all: "read_all",
write: "write",
write_all: "write_all",
bulk_reassign: "bulk_reassign",
change_stage: "change_stage",
manage_members: "manage_members",
// WF-P8 baseline: internal-note reader gate and pipeline handover.
read_internal_notes: "read_internal_notes",
handover: "handover",
read_volume_own: "read_volume_own",
read_volume_all: "read_volume_all",
read_aggregates: "read_aggregates",
@@ -108,6 +135,23 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
tenant_export: "tenant_export",
tenant_deletion: "tenant_deletion",
accept: "accept",
// P15 Telephony (AK-P15a) — initiate a provider-backed call.
call: "call",
// P15 Team-Chat (AK-P15b) — channel-scoped read/create capabilities.
read_own_channels: "read_own_channels",
create_channel: "create_channel",
create_dm: "create_dm",
read_all_channels: "read_all_channels",
manage_users: "manage_users",
manage_access: "manage_access",
delete_user: "delete_user",
assign: "assign",
merge: "merge",
track: "track",
bulk_send: "bulk_send",
recording: "recording",
enroll: "enroll",
start: "start",
};
const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
@@ -124,9 +168,11 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"app.plugins": "app.plugins",
"app.onboarding.demoData": "app.onboarding.demoData",
"app.onboarding.checklist": "app.onboarding.checklist",
// P26 Customer Portal (VA-P26a) — tenant-side configuration scope.
portal: "portal",
"portal.activity": "portalActivity",
"admin.account": "admin.account",
"admin.account.settings": "admin.account.settings",
"admin.accountTypes": "admin.accountTypes",
"admin.accounts": "admin.accounts",
"admin.apiKeys": "admin.apiKeys",
"admin.auditTrails": "admin.auditTrails",
@@ -139,6 +185,7 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"admin.marketing.funnels": "admin.marketing.funnels",
"admin.marketing.integrations": "admin.marketing.integrations",
"admin.marketing.leads": "admin.marketing.leads",
"admin.leads": "admin.leads",
"admin.metrics": "admin.metrics",
"admin.notifications": "admin.notifications",
"admin.pricing": "admin.pricing",
@@ -146,7 +193,6 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"admin.relationships": "admin.relationships",
"admin.roles": "admin.roles",
"admin.settings.authentication": "admin.settings.authentication",
"admin.settings.cookies": "admin.settings.cookies",
"admin.settings.danger": "admin.settings.danger",
"admin.settings.general": "admin.settings.general",
"admin.settings.internationalization": "admin.settings.internationalization",
@@ -199,11 +245,32 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
dashboard: "dashboard",
// P12 Automation (R-P12a) — typed automation rules, executions and guards.
automation: "automation",
// P15 Telephony (AK-P15a) — Aircall connection, calls and bindings.
telephony: "telephony",
// P15 Team-Chat (AK-P15b) — internal realtime collaboration.
chat: "chat",
// P21 Privacy/GDPR (AK-P21). Flat keys avoid colliding with the privacy leaf.
privacy: "privacy",
"privacy.user_export": "privacyUserExport",
"privacy.avv": "privacyAvv",
"privacy.subprocessors": "privacySubprocessors",
"admin_identity.users": "adminIdentityUsers",
"admin_identity.roles": "adminIdentityRoles",
"admin_identity.sessions": "adminIdentitySessions",
"admin_identity.audit": "adminIdentityAudit",
"admin_identity.impersonation": "adminIdentityImpersonation",
"admin_identity.tenants": "adminIdentityTenants",
"admin_sales.crm": "adminSalesCrm",
"admin_sales.communication": "adminSalesCommunication",
"admin_sales.email": "adminSalesEmail",
"admin_sales.phone": "adminSalesPhone",
"admin_sales.sequence": "adminSalesSequence",
"admin_sales.booking": "adminSalesBooking",
"admin_sales.quote": "adminSalesQuote",
"admin_sales.signature": "adminSalesSignature",
"admin_sales.reporting": "adminSalesReporting",
"admin_sales.automation": "adminSalesAutomation",
"admin_sales.integrations": "adminSalesIntegrations",
};
function humanizeIdentifier(value: string) {
@@ -270,8 +337,12 @@ function isDefaultPermissionDescription(item: DisplayItem) {
}
export function roleDisplayName(item: DisplayItem, t?: Translate) {
const key = DEFAULT_ROLE_NAME_KEYS[item.name];
return key && t ? t(`models.role.defaultRoles.names.${key}`) : item.name;
const defaultRoleKey = DEFAULT_ROLE_NAME_KEYS[item.name];
if (defaultRoleKey && t) {
return t(`models.role.defaultRoles.names.${defaultRoleKey}`);
}
const templateRoleKey = SHK_TEMPLATE_ROLE_NAME_KEYS[item.name];
return templateRoleKey && t ? t(`models.role.templateRoles.names.${templateRoleKey}`) : item.name;
}
export function roleDisplayDescription(item: DisplayItem, t?: Translate) {
@@ -284,6 +355,10 @@ export function roleDisplayDescription(item: DisplayItem, t?: Translate) {
return t(`models.role.defaultRoles.descriptions.${key}`);
}
if (t) {
const legacyTemplateKey = LEGACY_SHK_TEMPLATE_ROLE_DESCRIPTION_KEYS[description];
if (legacyTemplateKey) {
return t(`models.role.templateRoles.descriptions.${legacyTemplateKey}`);
}
const resolved = resolveStoredDescriptionKey(description, t);
if (resolved !== null) {
return resolved;
@@ -1,14 +1,14 @@
import clsx from "clsx";
import { useRef, useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Form, useActionData, useLocation, useNavigate, useNavigation, useParams } from "react-router";
import { Form, useActionData, useNavigate, useNavigation, useParams } from "react-router";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { NewMemberActionData } from "~/routes/app.$tenant/settings/members/new";
import { NewMemberActionData } from "~/routes/app.$tenant/settings/team/members/new";
import UrlUtils from "~/utils/app/UrlUtils";
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
import CheckPlanFeatureLimit from "../subscription/CheckPlanFeatureLimit";
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
import toast from "react-hot-toast";
import { toast } from "sonner";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
@@ -18,7 +18,6 @@ interface Props {
export default function NewMember({ featurePlanUsage }: Props) {
const params = useParams();
const location = useLocation();
const actionData = useActionData<NewMemberActionData>();
const { t } = useTranslation();
const navigate = useNavigate();
@@ -50,7 +49,7 @@ export default function NewMember({ featurePlanUsage }: Props) {
function close() {
if (params.tenant) {
navigate(UrlUtils.currentTenantUrl(params, "settings/members"), { replace: true });
navigate(UrlUtils.currentTenantUrl(params, "settings/team"), { replace: true });
} else {
navigate(adminPath("accounts/users", { mode: "host-aware" }), { replace: true });
}
@@ -15,6 +15,7 @@ import Modal from "~/components/ui/modals/Modal";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import { useLocaleFormatters } from "~/locale/format";
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
import { getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -52,7 +53,7 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
}
function getPriceAmount(product: SubscriptionProductDto, quantity = 1) {
const price = getPrice(product);
return formatters.currency(Number(price?.price ?? 0) * quantity, (price?.currency ?? currency).toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(Number(price?.price ?? 0) * quantity, (price?.currency ?? currency).toUpperCase());
}
function getPricePeriodSuffix(product: SubscriptionProductDto) {
@@ -198,7 +199,7 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
<XCircleIcon className="h-4 w-4 text-gray-300 opacity-70" />
)}
<span className="ml-3 truncate text-sm">
<span>{t(feature.title, { 0: feature.value })}</span>
<span>{getSubscriptionFeatureTitle(t, feature, { 0: feature.value })}</span>
</span>
</div>
</li>
@@ -11,7 +11,7 @@ interface Props {
hideContent?: boolean;
showRemaining?: boolean;
}
export default function CheckPlanFeatureLimit({ item, children, hideContent = true, showRemaining }: Props) {
export default function CheckPlanFeatureLimit({ item, children, hideContent = true, showRemaining: _showRemaining }: Props) {
const params = useParams();
const { t } = useTranslation();
function getTitle() {
@@ -24,7 +24,7 @@ export default function CheckPlanFeatureLimit({ item, children, hideContent = tr
<div>
{item && !item.enabled ? (
<div className="space-y-2">
<WarningBanner redirect={UrlUtils.currentTenantUrl(params, `settings/subscription`)} title={getTitle().toUpperCase()} text={``}>
<WarningBanner redirect={UrlUtils.currentTenantUrl(params, "settings/billing")} title={getTitle().toUpperCase()} text={``}>
<div className="mt-2">
<span>{t(item.message)}</span>
</div>
@@ -12,48 +12,31 @@ export default function MyPlanFeatureUsage({ item }: Props) {
return (
<div>
{item ? (
<div>
{/* {JSON.stringify(item)} */}
<div className="flex items-baseline space-x-1 font-medium">
<div className="flex flex-col gap-0.5">
<div className="text-foreground flex items-baseline gap-1 text-lg font-semibold tabular-nums">
{item.type === SubscriptionFeatureLimitType.INCLUDED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">
{/* <CheckIcon className={clsx(" text-center h-5 w-5")} /> */}
<span>{t("pricing.included")}</span>
</span>
<span>{t("pricing.included")}</span>
)}
{item.type === SubscriptionFeatureLimitType.NOT_INCLUDED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">
{/* <XIcon className={clsx(" text-center h-5 w-5")} /> */}
<span>{t("pricing.notIncluded")}</span>
</span>
<span>{t("pricing.notIncluded")}</span>
)}
{item.type === SubscriptionFeatureLimitType.MONTHLY && (
<span className="text-foreground flex items-baseline space-x-1 text-sm lowercase">
<span>
{item.used}/{item.value}
</span>
<span className="text-muted-foreground text-xs font-normal lowercase">
{item.period?.firstDay && item.period.lastDay ? (
<span>
({formatters.date(item.period.firstDay, { dateStyle: "medium" })} - {formatters.date(item.period.lastDay, { dateStyle: "medium" })})
</span>
) : (
<span>({t("pricing.thisMonth")})</span>
)}
</span>
</span>
<span>{formatters.number(item.used)} / {formatters.number(item.value)}</span>
)}
{item.type === SubscriptionFeatureLimitType.MAX && (
<span className="text-foreground lowercase">
{item.used}/{item.value}
</span>
<span>{formatters.number(item.used)} / {formatters.number(item.value)}</span>
)}
{item.type === SubscriptionFeatureLimitType.UNLIMITED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">{t("shared.unlimited")}</span>
<span>{t("shared.unlimited")}</span>
)}
</div>
{/* <span className="mt-2 text-red-700 text-xs font-normal">{item.message ?? ""}</span> */}
{item.type === SubscriptionFeatureLimitType.MONTHLY ? (
<span className="text-muted-foreground text-xs font-normal">
{item.period?.firstDay && item.period.lastDay
? `${formatters.date(item.period.firstDay, { dateStyle: "medium" })} – ${formatters.date(item.period.lastDay, { dateStyle: "medium" })}`
: t("pricing.thisMonth")}
</span>
) : null}
</div>
) : (
<span className=" text-muted-foreground">-</span>
@@ -0,0 +1,54 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import type { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import MySubscriptionFeatures from "./MySubscriptionFeatures";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
number: (value: number) => new Intl.NumberFormat("de-DE").format(value),
date: () => "01.07.2026",
}),
}));
function feature(overrides: Partial<PlanFeatureUsageDto>): PlanFeatureUsageDto {
return {
order: 1,
title: "Feature",
name: "feature",
type: SubscriptionFeatureLimitType.INCLUDED,
value: 1,
used: 0,
remaining: 1,
enabled: true,
message: "",
...overrides,
};
}
describe("MySubscriptionFeatures", () => {
it("shows only commercial quantity limits and the calculated storage pool", () => {
render(
<MySubscriptionFeatures
storageLimitGb={250}
features={[
feature({ name: "dashboard", type: SubscriptionFeatureLimitType.INCLUDED }),
feature({ name: "email-marketing", type: SubscriptionFeatureLimitType.MONTHLY, value: 10_000, used: 125 }),
feature({ name: "rate-limit-per-minute", type: SubscriptionFeatureLimitType.MAX, value: 600, used: 12 }),
feature({ name: "automation", type: SubscriptionFeatureLimitType.NOT_INCLUDED, value: 0 }),
]}
/>
);
expect(screen.getByText("app.subscription.features.storage")).toBeInTheDocument();
expect(screen.getByText("250 shared.storage.gb")).toBeInTheDocument();
expect(screen.getByText("app.subscription.features.emailMarketing")).toBeInTheDocument();
expect(screen.getByText("125 / 10.000")).toBeInTheDocument();
expect(screen.queryByText("dashboard")).not.toBeInTheDocument();
expect(screen.queryByText("rate-limit-per-minute")).not.toBeInTheDocument();
expect(screen.queryByText("app.subscription.features.automation")).not.toBeInTheDocument();
});
});
@@ -1,56 +1,67 @@
import { useTranslation } from "react-i18next";
import clsx from "clsx";
import MyPlanFeatureUsage from "./MyPlanFeatureUsage";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { useLocaleFormatters } from "~/locale/format";
interface Props {
features: PlanFeatureUsageDto[];
className?: string;
withCurrentPlan: boolean;
storageLimitGb?: number | null;
}
export default function MySubscriptionFeatures({
features,
className = "",
withCurrentPlan = false,
}: Props) {
const commercialLimitTitleKeys: Record<string, string> = {
"email-marketing": "app.subscription.features.emailMarketing",
automation: "app.subscription.features.automation",
"workflow-engine": "app.subscription.features.workflows",
"import-export": "app.subscription.features.importExport",
};
export default function MySubscriptionFeatures({ features, className = "", storageLimitGb = null }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const visibleFeatures = features.filter(
(feature) =>
commercialLimitTitleKeys[feature.name] &&
[SubscriptionFeatureLimitType.MONTHLY, SubscriptionFeatureLimitType.MAX, SubscriptionFeatureLimitType.UNLIMITED].includes(feature.type)
);
function getTitle(item: PlanFeatureUsageDto) {
const commercialTitleKey = commercialLimitTitleKeys[item.name];
if (commercialTitleKey) {
return t(commercialTitleKey);
}
if (item?.entity) {
return t(item.entity.titlePlural);
}
return item?.name ?? "";
return item?.title ?? "";
}
const hasLimits = storageLimitGb !== null || visibleFeatures.length > 0;
return (
<div className={className} data-ui-id="ui.subscription.features">
{features.length === 0 ? (
{!hasLimits ? (
<div className="text-muted-foreground text-sm italic">{t("settings.subscription.noSubscription")}</div>
) : (
<>
<dl
className={clsx(
"grid gap-2",
withCurrentPlan && "mt-2 ",
features.length === 1 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 2 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-2",
features.length === 3 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 4 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-2",
features.length === 5 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 6 && "grid-cols-1 md:grid-cols-3 xl:grid-cols-2"
)}
>
{features.map((item, idx) => {
return (
<div key={idx} className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground truncate text-xs uppercase tracking-wide">{getTitle(item)}</dt>
<dd className="mt-1">
<span>{<MyPlanFeatureUsage item={item} />}</span>
</dd>
</div>
);
})}
</dl>
</>
<dl className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
{storageLimitGb !== null ? (
<div className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground text-xs font-medium tracking-wide uppercase">{t("app.subscription.features.storage")}</dt>
<dd className="text-foreground mt-1 text-lg font-semibold tabular-nums">
{formatters.number(storageLimitGb, { maximumFractionDigits: 0 })} {t("shared.storage.gb")}
</dd>
</div>
) : null}
{visibleFeatures.map((item) => (
<div key={item.name} className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground text-xs font-medium tracking-wide uppercase">{getTitle(item)}</dt>
<dd className="mt-1 text-lg font-semibold tabular-nums">
<MyPlanFeatureUsage item={item} />
</dd>
</div>
))}
</dl>
)}
</div>
);
@@ -17,6 +17,7 @@ import InputNumber from "~/components/ui/input/InputNumber";
import PlanChangePreviewModal from "./PlanChangePreviewModal";
import { useLocaleFormatters } from "~/locale/format";
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
import { annualSepaExtraPriceEur, type SeatPackageDefinition } from "@hivegrid/entitlements";
export interface CurrentPlanInfo {
title: string;
@@ -45,6 +46,8 @@ interface Props {
billingProviderCoupon: BillingProviderCouponDto | null;
isPreview?: boolean;
onClickFeature?: (name: string) => void;
showFeatures?: boolean;
seatPackage?: SeatPackageDefinition;
/** When set, the user has an existing active subscription on a *different* plan. Click opens a proration preview before submitting. */
currentPlanInfo?: CurrentPlanInfo | null;
}
@@ -68,6 +71,8 @@ export default function Plan({
billingProviderCoupon,
isPreview,
onClickFeature,
showFeatures = false,
seatPackage,
currentPlanInfo,
}: Props) {
const { t } = useTranslation();
@@ -101,7 +106,7 @@ export default function Plan({
return "?";
}
let total = applyDiscount(Number(price.price || 0));
return formatters.currency(total, price.currency.toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(total, price.currency.toUpperCase());
}
function getBeforePrice() {
@@ -109,7 +114,7 @@ export default function Plan({
if (!price) {
return "?";
}
return formatters.currency(Number(price.price || 0), price.currency.toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(Number(price.price || 0), price.currency.toUpperCase());
}
function getPricePeriodSuffix(price?: SubscriptionPriceDto) {
@@ -252,14 +257,20 @@ export default function Plan({
>
{badge && (
<div className="bg-primary text-primary-foreground absolute top-0 -translate-y-1/2 transform rounded-full px-4 py-1.5 text-xs font-semibold tracking-wide uppercase">
{t(badge)}
{badge.startsWith("settings.subscription.checkout.plans.packages.") ? t(badge) : badge}
</div>
)}
<div className="flex-1 space-y-4">
{/* Title and Description */}
<div className="shrink-0 space-y-2">
<h2 className="text-xl font-medium">{t(title)}</h2>
{description && <p className="text-muted-foreground text-sm">{t(description)}</p>}
<h2 className="text-xl font-medium">
{title.startsWith("settings.subscription.checkout.plans.packages.") ? t(title) : title}
</h2>
{description && (
<p className="text-muted-foreground text-sm">
{description.startsWith("settings.subscription.checkout.plans.packages.") ? t(description) : description}
</p>
)}
</div>
{/* Price */}
@@ -350,19 +361,47 @@ export default function Plan({
);
})}
{/* <div className="w-full border-t"></div> */}
{/* Features */}
<ul className="flex-1 space-y-1.5">
{features
.sort((a, b) => (a.order > b.order ? 1 : -1))
.map((feature, idxFeature) => {
return (
{showFeatures ? (
<ul className="flex-1 space-y-1.5">
{[...features]
.sort((a, b) => (a.order > b.order ? 1 : -1))
.map((feature, idxFeature) => (
<li key={idxFeature}>
<PlanFeatureDescription feature={feature} onClickFeature={onClickFeature} />
</li>
);
})}
</ul>
))}
</ul>
) : null}
{seatPackage ? (
<div className="border-border text-muted-foreground space-y-1.5 border-t pt-4 text-sm">
<p className="text-foreground font-medium">{t("billing:selfServiceSubscription.packageTerms.core")}</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.seats", {
office: seatPackage.seats.office.included,
field: seatPackage.seats.field.included,
})}
</p>
<p>{t("billing:selfServiceSubscription.packageTerms.storage", { storage: seatPackage.storage.includedGb })}</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.annualSepa", {
price: formatters.currency(seatPackage.annualSepaEur, "EUR"),
})}
</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.extraSeatsMonthly", {
office: formatters.currency(seatPackage.seats.office.extraPriceEur, "EUR"),
field: formatters.currency(seatPackage.seats.field.extraPriceEur, "EUR"),
})}
</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.extraSeatsAnnualSepa", {
office: formatters.currency(annualSepaExtraPriceEur(seatPackage.seats.office.extraPriceEur), "EUR"),
field: formatters.currency(annualSepaExtraPriceEur(seatPackage.seats.field.extraPriceEur), "EUR"),
})}
</p>
</div>
) : null}
{/* {canSubmit && ( */}
<div className="mt-4 space-y-2">
@@ -432,8 +471,8 @@ export default function Plan({
}
setShowPreview(false);
}}
fromPlanTitle={t(currentPlanInfo.title)}
toPlanTitle={t(title)}
fromPlanTitle={currentPlanInfo.title.startsWith("settings.subscription.checkout.plans.packages.") ? t(currentPlanInfo.title) : currentPlanInfo.title}
toPlanTitle={title.startsWith("settings.subscription.checkout.plans.packages.") ? t(title) : title}
fromPriceAmount={currentPlanInfo.priceAmount}
toPriceAmount={Number(getFlatPrice()?.price ?? 0)}
currency={currency}
@@ -480,7 +519,8 @@ function SubscribeOrBuyButton({
currency,
}: SubscribeOrBuyButtonProps) {
const { t } = useTranslation();
const planLabel = title ? t(title) : (product?.title ? t(product.title) : "");
const rawPlanLabel = title ?? product?.title ?? "";
const planLabel = rawPlanLabel.startsWith("settings.subscription.checkout.plans.packages.") ? t(rawPlanLabel) : rawPlanLabel;
// alreadyOwned takes a distinctive non-clickable badge instead of a button —
// signals "this is your plan" rather than "click to do nothing".
@@ -5,6 +5,7 @@ import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { useLocaleFormatters } from "~/locale/format";
import { CreditTypes } from "~/modules/usage/dtos/CreditType";
import { getSubscriptionFeatureBadge, getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -70,13 +71,14 @@ export default function PlanFeatureDescription({ feature, editing, onClickFeatur
);
}
function FeatureTitle({ feature }: { feature: { title: string; value: number; href?: string | null; badge?: string | null } }) {
function FeatureTitle({ feature }: { feature: { name: string; title: string; value: number; href?: string | null; badge?: string | null } }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const value = typeof feature.value === "number" ? formatters.number(feature.value, { maximumFractionDigits: 0 }) : feature.value;
const badge = getSubscriptionFeatureBadge(t, feature);
return (
<span>
{t(feature.title, { 0: value })} {feature.badge && <span className="bg-primary text-theme-50 ml-1 rounded-md px-1 py-0.5 text-xs">{feature.badge}</span>}
{getSubscriptionFeatureTitle(t, feature, { 0: value })} {badge && <span className="bg-primary text-theme-50 ml-1 rounded-md px-1 py-0.5 text-xs">{badge}</span>}
</span>
);
}
@@ -12,6 +12,7 @@ import type { SubscriptionPriceDto } from "~/application/dtos/subscriptions/Subs
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
import { useSearchParams } from "react-router";
import { useLocaleFormatters } from "~/locale/format";
import { getSeatPackage, resolveSeatPackageId } from "@hivegrid/entitlements";
interface Props {
items: SubscriptionProductDto[];
@@ -138,13 +139,14 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
: null;
return items.map((plan, index) => {
const seatPackageId = resolveSeatPackageId(plan.title, plan.id);
return (
<Plan
key={index}
className={clsx((items.length === 1 || (items.length === 4 && index === 3)) && "lg:col-span-1")}
product={plan}
title={plan.title}
description={plan.description ?? undefined}
title={seatPackageId ? `settings.subscription.checkout.plans.packages.${seatPackageId}.title` : plan.title}
description={seatPackageId ? `settings.subscription.checkout.plans.packages.${seatPackageId}.description` : (plan.description ?? undefined)}
badge={plan.badge ?? undefined}
features={plan.features}
billingPeriod={billingPeriod}
@@ -159,6 +161,8 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
billingProviderCoupon={billingProviderCoupon}
onClickFeature={onClickFeature}
currentPlanInfo={currentPlanInfo}
showFeatures={false}
seatPackage={seatPackageId ? getSeatPackage(seatPackageId) : undefined}
/>
);
});
@@ -0,0 +1,14 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
describe("customer billing plan cards", () => {
it("hide feature matrices while the admin plan preview keeps them available", () => {
const customerPlans = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/settings/subscription/Plans.tsx"), "utf8");
const adminPreview = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/pricing/PricingPlanForm.tsx"), "utf8");
expect(customerPlans).toContain("showFeatures={false}");
expect(adminPreview).toContain("showFeatures");
});
});
@@ -29,6 +29,7 @@ describe("pricing card locale formatting", () => {
expect(source).not.toContain('from "~/utils/helpers/PricingHelper"');
expect(source).not.toContain("NumberUtils.");
expect(source).not.toContain("getFormattedPriceInCurrency");
expect(source).not.toMatch(/formatters\.currency\([^\n]*maximumFractionDigits:\s*0/);
expect(source).not.toContain('"$"');
expect(source).not.toContain('"License"');
expect(source).not.toContain('"Metered"');
@@ -0,0 +1,81 @@
import { useTranslation } from "react-i18next";
import type { SeatUsageCategoryVM, SeatUsageVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Progress } from "~/ui/components/Progress";
/**
* Seat-usage section (Fundament E) — additive, VM-driven, render-only.
*
* Shows how many Büro/Baustelle seats the tenant occupies against the seat
* package limits, and — on overage — the extra seats and their cost in plain
* language. All copy comes through i18n; euro amounts are locale-formatted here.
*/
export default function SeatUsageSection({ vm }: { vm: SeatUsageVM }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
if (vm.status !== "ready") {
return (
<div className="text-text-neutral-tertiary text-sm" data-ui-id="ui.subscription.seats.empty">
{t("settings.subscription.seats.empty")}
</div>
);
}
const { data } = vm;
const formatEur = (value: number) => formatters.currency(value, data.currency);
return (
<div className="space-y-4" data-ui-id="ui.subscription.seats">
{data.hasPackage && data.packageNameKey ? (
<p className="text-text-neutral-secondary text-sm">{t("settings.subscription.seats.currentPackage", { package: t(data.packageNameKey) })}</p>
) : (
<p className="text-text-neutral-tertiary text-sm">{t(data.noPackageHintKey)}</p>
)}
<ul className="space-y-3">
{data.categories.map((category) => (
<SeatCategoryRow key={category.seatType} category={category} hasPackage={data.hasPackage} />
))}
</ul>
{data.hasOverage ? (
<div className="border-border-default rounded-md border border-dashed px-3 py-2 text-sm" data-ui-id="ui.subscription.seats.overage">
<p className="text-text-neutral-primary font-medium">{t(data.overageNoticeKey)}</p>
<ul className="mt-1 space-y-1">
{data.categories
.filter((category) => category.overLimit && category.extraPriceEur !== null)
.map((category) => (
<li key={category.seatType} className="text-text-neutral-secondary">
{t("settings.subscription.seats.extraLine", {
count: category.extra,
seat: t(category.labelKey),
price: formatEur(category.extraPriceEur ?? 0),
})}
</li>
))}
</ul>
<p className="text-text-neutral-primary mt-2 font-medium">{t("settings.subscription.seats.extraTotal", { total: formatEur(data.totalExtraCostEur) })}</p>
</div>
) : null}
</div>
);
}
function SeatCategoryRow({ category, hasPackage }: { category: SeatUsageCategoryVM; hasPackage: boolean }) {
const { t } = useTranslation();
const hasLimit = hasPackage && category.included !== null;
const percent = hasLimit && (category.included ?? 0) > 0 ? Math.min(100, Math.round((category.used / (category.included ?? 1)) * 100)) : 0;
return (
<li className="space-y-1">
<div className="flex items-baseline justify-between">
<span className="text-text-neutral-primary text-sm font-medium">{t(category.labelKey)}</span>
<span className="text-text-neutral-secondary text-sm tabular-nums">
{hasLimit ? t("settings.subscription.seats.occupancy", { used: category.used, included: category.included }) : t("settings.subscription.seats.occupancyNoLimit", { used: category.used })}
</span>
</div>
{hasLimit ? <Progress value={category.overLimit ? 100 : percent} /> : null}
</li>
);
}
@@ -12,7 +12,7 @@ interface Props {
onCancel: () => void;
}
export default function SubscriptionProducts({ products, subscription, canCancel, onCancel }: Props) {
export default function SubscriptionProducts({ products, subscription: _subscription, canCancel: _canCancel, onCancel: _onCancel }: Props) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
@@ -26,8 +26,8 @@ export default function ToggleBillingPeriod({
disabled,
possibleBillingPeriods,
darkMode,
currency,
products,
currency: _currency,
products: _products,
}: Props) {
const { t } = useTranslation();
// const [discounts, setDiscounts] = useState<{ billingPeriod: SubscriptionBillingPeriod; discount?: number }[]>([]);
@@ -13,7 +13,6 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { useRootData } from "~/utils/data/useRootData";
import { createLocaleFormatters } from "~/locale/format";
import { translateLabel } from "~/utils/i18n/translateLabel";
interface Props {
items: TenantWithUsage[];
@@ -99,16 +98,6 @@ export default function TenantsTable({ items, pagination, actions = [] }: Props)
</span>
),
});
headers.push({
name: "types",
title: t("shared.types"),
value: (i) =>
i.types.length === 0 ? (
<span className="text-muted-foreground">{t("shared.default")}</span>
) : (
i.types.map((f) => translateLabel(t, i18n, f.title)).join(", ")
),
});
headers.push({
name: "users",
title: t("models.user.plural"),
@@ -7,32 +7,20 @@ import InputText from "~/components/ui/input/InputText";
import UrlUtils from "~/utils/app/UrlUtils";
import type { TenantWithDetails } from "~/utils/db/tenants.db.server";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import InputCombobox from "~/components/ui/input/InputCombobox";
import { useRootData } from "~/utils/data/useRootData";
import { translateLabel } from "~/utils/i18n/translateLabel";
import { UserIcon } from "~/components/ui/icons/vendor";
type TenantTypeOption = {
id: string;
title: string;
};
interface Props {
tenant: TenantWithDetails;
disabled: boolean;
tenantTypes?: TenantTypeOption[];
options?: {
canChangeType: boolean;
};
}
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes, options }: Props) {
const { i18n, t } = useTranslation();
export default function UpdateTenantDetailsForm({ tenant, disabled }: Props) {
const { t } = useTranslation();
const rootData = useRootData();
const [slug, setSlug] = useState<string | undefined>(tenant?.slug ?? "");
const [icon, setIcon] = useState<string | undefined>(tenant?.icon ?? "");
const [types, setTypes] = useState<string[]>(tenant.types.map((f) => f.id));
function loadedImage(image: string | undefined) {
setIcon(image);
@@ -71,27 +59,6 @@ export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes,
}}
/>
</div>
{tenantTypes !== undefined && tenantTypes.length > 0 && (
<div className="col-span-6 sm:col-span-6">
{types?.map((item, idx) => {
return <input key={idx} type="hidden" name={`typeIds[]`} value={item} hidden readOnly />;
})}
<InputCombobox
withSearch={false}
disabled={!options?.canChangeType}
name="typeIds"
title={t("shared.type")}
value={types}
onChange={(e) => setTypes(e as string[])}
options={tenantTypes.map((f) => {
return {
value: f.id,
name: translateLabel(t, i18n, f.title),
};
})}
/>
</div>
)}
<div className="col-span-6 sm:col-span-6">
<label htmlFor="icon" className="text-foreground/80 block text-xs leading-5 font-medium">
{t("shared.icon")}
@@ -1,65 +0,0 @@
import { useEffect, useState } from "react";
import { useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
import { useRootData } from "~/utils/data/useRootData";
import { defaultAnrede, isAnrede, type Anrede } from "@hivegrid/i18n";
import SettingSection from "~/components/ui/sections/SettingSection";
import InputChoicebox from "~/components/ui/input/InputChoicebox";
type Props = {
tenant: TenantWithProfile;
};
/**
* Schlichter du/Sie-Umschalter (Anrede). Persistiert `Tenant.anrede` und setzt
* den `_anrede`-Cookie (Server-Action `update-anrede`). Default "du" verhaelt
* sich byte-identisch zum Status quo; "sie" schaltet die App auf die
* "<locale>-formal"-Sprachvariante um (Fallback auf Basis-Locale).
*/
export default function UpdateTenantFormAnrede({ tenant }: Props) {
const { t } = useTranslation();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const initial: Anrede = isAnrede(tenant?.anrede ?? undefined) ? (tenant.anrede as Anrede) : defaultAnrede;
const [anrede, setAnrede] = useState<Anrede>(initial);
useEffect(() => {
if (fetcher.data?.success) {
toast.success(fetcher.data.success);
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error);
}
}, [fetcher.data]);
const onChange = (value: string) => {
if (!isAnrede(value) || value === anrede) {
return;
}
setAnrede(value);
const form = new FormData();
form.set("action", "update-anrede");
form.set("anrede", value);
if (csrf) {
form.set("csrf", csrf);
}
fetcher.submit(form, { method: "post", preventScrollReset: true });
};
return (
<SettingSection title={t("settings:tenant.anrede.title")} description={t("settings:tenant.anrede.description")}>
<InputChoicebox
name="anrede"
value={anrede}
onChange={onChange}
disabled={fetcher.state !== "idle"}
options={[
{ value: "du", name: t("settings:tenant.anrede.du") },
{ value: "sie", name: t("settings:tenant.anrede.sie") },
]}
/>
</SettingSection>
);
}
@@ -1,809 +0,0 @@
import { useTranslation } from "react-i18next";
import { useEffect, useState } from "react";
import { Link, useFetcher, useSearchParams } from "react-router";
import { toast } from "sonner";
import { Button } from "~/components/ui/button";
import { cn } from "~/lib/utils";
import { Label } from "~/components/ui/label";
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
import { ColorPicker } from "~/components/ui/colors/ColorPicker";
import InputSelect from "~/components/ui/input/InputSelect";
import SettingSection from "~/components/ui/sections/SettingSection";
import { defaultThemes, getThemeConfig } from "~/utils/theme/defaultThemes";
import { useThemePreviewStore } from "~/stores/themePreviewStore";
import { ThemeConfig, defaultThemeConfig, parseThemeConfig } from "~/utils/theme/ThemeConfig";
import { Input } from "~/components/ui/input";
import { useRootData } from "~/utils/data/useRootData";
import { parseCssConfig } from "~/utils/theme/cssConfigParser";
import { exportConfigToCss } from "~/utils/theme/cssConfigExporter";
import { ExternalLinkIcon, ArrowLeftIcon, ArrowRightIcon, ImportIcon, EraserIcon, SunIcon, MoonIcon } from "~/components/ui/icons/vendor";
import ModalOrSlide from "~/components/ui/modals/ModalOrSlide";
import MonacoEditor from "~/components/editors/MonacoEditor";
import InputChoicebox from "~/components/ui/input/InputChoicebox";
type Props = {
tenant: TenantWithProfile;
};
export default function UpdateTenantFormTheme({ tenant }: Props) {
const { t } = useTranslation();
const { csrf, userSession } = useRootData();
const [searchParams] = useSearchParams();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const { setPreviewTheme, setPreviewConfig, enablePreview, disablePreview, resetPreview } = useThemePreviewStore();
const isDarkMode = userSession?.lightOrDarkMode === "dark";
const [theme, setTheme] = useState(tenant?.theme || "");
const [config, setConfig] = useState<ThemeConfig>(() => parseThemeConfig(tenant?.themeConfig as string | null));
const [cssDialogOpen, setCssDialogOpen] = useState(false);
const [cssEditorValue, setCssEditorValue] = useState("");
const isUserInDarkMode = userSession?.lightOrDarkMode === "dark";
// Enable preview mode when component mounts
useEffect(() => {
enablePreview();
return () => {
disablePreview();
};
}, [enablePreview, disablePreview]);
// Update preview whenever state changes
useEffect(() => {
setPreviewTheme(theme || null);
setPreviewConfig(config);
}, [theme, config, setPreviewTheme, setPreviewConfig]);
useEffect(() => {
if (fetcher.data?.success) {
toast.success(fetcher.data.success);
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error);
}
}, [fetcher.data]);
const updateConfigColor = (key: keyof NonNullable<ThemeConfig["colors"]>, value: string) => {
if (isUserInDarkMode) {
setConfig((prev) => ({
...prev,
darkColors: {
...prev.darkColors,
[key]: value || undefined,
},
}));
} else {
setConfig((prev) => ({
...prev,
colors: {
...prev.colors,
[key]: value || undefined,
},
}));
}
};
const getConfigColor = (key: keyof NonNullable<ThemeConfig["colors"]>) => {
if (isUserInDarkMode) {
return config.darkColors?.[key] || "";
}
return config.colors?.[key] || "";
};
const resetToDefaults = () => {
setTheme("");
setConfig({});
resetPreview();
};
const handleApplyCss = () => {
try {
const parsedConfig = parseCssConfig(cssEditorValue);
// Merge the parsed config with existing config
setConfig((prev) => ({
...prev,
...parsedConfig,
colors: {
...prev.colors,
...parsedConfig.colors,
},
darkColors: {
...prev.darkColors,
...parsedConfig.darkColors,
},
}));
// Clear theme preset since we're using custom config
setTheme("");
toast.success(t("settings:tenant.theme.editor.cssApplied"));
setCssDialogOpen(false);
} catch {
toast.error(t("settings:tenant.theme.editor.cssParseFailed"));
}
};
const openCssDialog = () => {
// Pre-populate with current config when opening
setCssEditorValue(exportConfigToCss(config));
setCssDialogOpen(true);
};
function previousTheme() {
const currentIndex = defaultThemes.findIndex((t) => t.value === theme);
const previousIndex = currentIndex - 1;
setTheme(defaultThemes[previousIndex].value);
setConfig(getThemeConfig(defaultThemes[previousIndex].value) || defaultThemeConfig);
}
function nextTheme() {
const currentIndex = defaultThemes.findIndex((t) => t.value === theme);
const nextIndex = currentIndex + 1;
setTheme(defaultThemes[nextIndex].value);
setConfig(getThemeConfig(defaultThemes[nextIndex].value) || defaultThemeConfig);
}
const onThemeToggle = async () => {
const form = new FormData();
form.set("action", "toggleLightOrDarkMode");
form.set("redirect", location.pathname + "?" + searchParams.toString());
if (csrf) {
form.set("csrf", csrf);
}
fetcher.submit(form, { method: "post", action: "/preferences", preventScrollReset: true });
};
return (
<div className="space-y-6">
<fetcher.Form method="post">
<input type="hidden" name="action" value="update-theme" readOnly hidden />
<input type="hidden" name="theme" value={theme} readOnly hidden />
<input type="hidden" name="themeConfig" value={JSON.stringify(config)} readOnly hidden />
<div className="space-y-6">
{/* Appearance Section */}
<SettingSection
title={t("settings:tenant.theme.appearance.title")}
description={t("settings:tenant.theme.appearance.description")}
>
<div className="grid grid-cols-2 gap-4">
{/* Theme Selection */}
<div className="col-span-1">
<div className="mb-2 flex items-center justify-between">
<Label className="block text-sm font-medium">{t("settings:tenant.theme.appearance.themePreset")}</Label>
</div>
<div className="flex items-center gap-2">
<InputSelect
name="themeSelect"
value={theme}
selectClassName="bg-background"
setValue={(value) => {
const newTheme = value?.toString() || "";
setTheme(newTheme);
// Apply theme preset colors if available
if (newTheme) {
const themePreset = getThemeConfig(newTheme);
if (themePreset) {
setConfig((prev) => ({
...prev,
fontFamily: themePreset.fontFamily || prev.fontFamily,
radius: themePreset.radius || prev.radius,
sidebarVariant: themePreset.sidebarVariant || prev.sidebarVariant,
sidebarDarkMode: themePreset.sidebarDarkMode ?? prev.sidebarDarkMode,
colors: {
...prev.colors,
...themePreset.colors,
},
darkColors: {
...prev.darkColors,
...themePreset.darkColors,
},
}));
}
}
}}
options={[
{ value: "", name: t("settings:tenant.theme.appearance.useDefaultTheme") },
...defaultThemes.map((theme) => {
const label = t(theme.labelKey, { defaultValue: theme.name });
return {
value: theme.value,
name: (
<div className="flex items-center space-x-2">
<div
className={cn(
`theme-${theme.value}`,
"inline-flex shrink-0 items-center rounded-sm text-xs font-medium",
"size-2.5",
"bg-primary text-primary"
)}
/>
<span>{label}</span>
</div>
),
};
}),
]}
className="flex-1"
/>
</div>
</div>
<div>
{/* Import/Export Theme */}
<div className="mb-2 flex items-center justify-between">
<Label className="invisible block text-sm font-medium">{t("settings:tenant.theme.appearance.themeActions")}</Label>
</div>
<div className="flex items-center gap-2">
{/* Previous theme */}
<Button type="button" variant="outline" size="sm" onClick={previousTheme} aria-label={t("shared.previous")}>
<ArrowLeftIcon className="size-3.5" aria-hidden="true" />
</Button>
{/* Next theme */}
<Button type="button" variant="outline" size="sm" onClick={nextTheme} aria-label={t("shared.next")}>
<ArrowRightIcon className="size-3.5" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="sm" onClick={openCssDialog} aria-label={t("shared.import")}>
<ImportIcon className="size-3.5" aria-hidden="true" />
</Button>
{/* Reset theme */}
<Button type="button" variant="outline" size="sm" onClick={resetToDefaults} aria-label={t("shared.reset")}>
<EraserIcon className="size-3.5" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="sm" onClick={onThemeToggle} aria-label={t(isDarkMode ? "shared.light" : "shared.dark")}>
{/* <DarkModeSvgs className="size-3.5" withLabel={false} /> */}
{isDarkMode ? <SunIcon className="size-3.5" aria-hidden="true" /> : <MoonIcon className="size-3.5" aria-hidden="true" />}
</Button>
</div>
</div>
{/* Font Family */}
<div>
<Label className="mb-2 block text-sm font-medium">{t("settings:tenant.theme.appearance.fontFamily")}</Label>
<InputSelect
name="fontFamily"
value={config.fontFamily || ""}
selectClassName="bg-background"
setValue={(value) => setConfig({ ...config, fontFamily: value?.toString() || undefined })}
options={[
{ value: "", name: t("settings:tenant.theme.appearance.defaultSystemUi") },
{
value: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
name: t("settings:tenant.theme.appearance.fontFamilies.sansSerif"),
},
{ value: "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif", name: t("settings:tenant.theme.appearance.fontFamilies.serif") },
{
value: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
name: t("settings:tenant.theme.appearance.fontFamilies.monospace"),
},
{ value: "Inter, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.inter") },
{ value: "Geist, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.geist") },
{ value: "Outfit, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.outfit") },
{ value: "'Open Sans', sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.openSans") },
{ value: "Roboto, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.roboto") },
{ value: "Poppins, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.poppins") },
{ value: "Montserrat, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.montserrat") },
{ value: "Lato, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.lato") },
{ value: "'Source Sans Pro', sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.sourceSansPro") },
{ value: "Raleway, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.raleway") },
{ value: "'Playfair Display', serif", name: t("settings:tenant.theme.appearance.fontFamilies.playfairDisplay") },
{ value: "Merriweather, serif", name: t("settings:tenant.theme.appearance.fontFamilies.merriweather") },
{ value: "'JetBrains Mono', monospace", name: t("settings:tenant.theme.appearance.fontFamilies.jetbrainsMono") },
{ value: "'Fira Code', monospace", name: t("settings:tenant.theme.appearance.fontFamilies.firaCode") },
]}
/>
</div>
{/* Border Radius */}
<div>
<Label className="mb-2 block text-sm font-medium">{t("settings:tenant.theme.appearance.borderRadius")}</Label>
<div className="flex items-center gap-2">
<Input
type="number"
step="0.01"
min={0}
max={2}
value={parseFloat(config.radius?.replace("rem", "") || "0.5")}
onChange={(e) => setConfig({ ...config, radius: `${e.target.value}rem` })}
placeholder="0.5"
className="bg-background w-full"
/>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-5">
<div className="border-border border-t"></div>
</div>
</div>
{/* Colors Section */}
<SettingSection title={t("settings:tenant.theme.colors.title")} description={t(isUserInDarkMode ? "settings.tenant.theme.colors.modes.dark" : "settings.tenant.theme.colors.modes.light")}>
<div className="space-y-4">
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.background")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.background")}
value={getConfigColor("background")}
onChange={(color) => updateConfigColor("background", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("background") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.foreground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.foreground")}
value={getConfigColor("foreground")}
onChange={(color) => updateConfigColor("foreground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("foreground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.primary")}
value={getConfigColor("primary")}
onChange={(color) => updateConfigColor("primary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("primary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.primaryForeground")}
value={getConfigColor("primaryForeground")}
onChange={(color) => updateConfigColor("primaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("primaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.secondary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.secondary")}
value={getConfigColor("secondary")}
onChange={(color) => updateConfigColor("secondary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("secondary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.secondaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.secondaryForeground")}
value={getConfigColor("secondaryForeground")}
onChange={(color) => updateConfigColor("secondaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("secondaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accent")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.accent")}
value={getConfigColor("accent")}
onChange={(color) => updateConfigColor("accent", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("accent") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accentForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.accentForeground")}
value={getConfigColor("accentForeground")}
onChange={(color) => updateConfigColor("accentForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("accentForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.destructive")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.destructive")}
value={getConfigColor("destructive")}
onChange={(color) => updateConfigColor("destructive", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("destructive") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.destructiveForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.destructiveForeground")}
value={getConfigColor("destructiveForeground")}
onChange={(color) => updateConfigColor("destructiveForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("destructiveForeground") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.card")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.card")} value={getConfigColor("card")} onChange={(color) => updateConfigColor("card", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("card") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.cardForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.cardForeground")}
value={getConfigColor("cardForeground")}
onChange={(color) => updateConfigColor("cardForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("cardForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.popover")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.popover")}
value={getConfigColor("popover")}
onChange={(color) => updateConfigColor("popover", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("popover") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.popoverForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.popoverForeground")}
value={getConfigColor("popoverForeground")}
onChange={(color) => updateConfigColor("popoverForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("popoverForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.muted")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.muted")} value={getConfigColor("muted")} onChange={(color) => updateConfigColor("muted", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("muted") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.mutedForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.mutedForeground")}
value={getConfigColor("mutedForeground")}
onChange={(color) => updateConfigColor("mutedForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("mutedForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.border")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.border")}
value={getConfigColor("border")}
onChange={(color) => updateConfigColor("border", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("border") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.input")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.input")} value={getConfigColor("input")} onChange={(color) => updateConfigColor("input", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("input") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.ring")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.ring")} value={getConfigColor("ring")} onChange={(color) => updateConfigColor("ring", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("ring") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-5">
<div className="border-border border-t"></div>
</div>
</div>
{/* Sidebar Section */}
<SettingSection
title={t("settings:tenant.theme.sidebar.title")}
description={t("settings:tenant.theme.sidebar.description")}
>
<div className="space-y-6">
{/* Sidebar Settings */}
<div>
<div className="space-y-4">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.sidebar.style")}</Label>
<InputChoicebox
name="sidebarVariant"
value={config.sidebarVariant || "inset"}
// selectClassName="bg-background"
onChange={(value) => setConfig({ ...config, sidebarVariant: value as "inset" | "sidebar" })}
options={[
{ value: "inset", name: t("settings:tenant.theme.sidebar.styleOptions.inset") },
{ value: "sidebar", name: t("settings:tenant.theme.sidebar.styleOptions.sidebar") },
]}
/>
</div>
{/*
<InputCheckboxInline
name="sidebarDarkMode"
title={t("settings:tenant.theme.sidebar.forceDark")}
value={config.sidebarDarkMode || false}
setValue={(value) => setConfig({ ...config, sidebarDarkMode: value as boolean })}
/> */}
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.sidebar.theme")}</Label>
<InputChoicebox
name="sidebarDarkMode"
value={config.sidebarDarkMode ? "true" : "false"}
onChange={(value) => setConfig({ ...config, sidebarDarkMode: value === "true" })}
options={[
{ value: "false", name: t("shared.light") },
{ value: "true", name: t("shared.dark") },
]}
/>
</div>
</div>
</div>
{/* Sidebar Colors */}
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.sidebar")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebar")}
value={getConfigColor("sidebar")}
onChange={(color) => updateConfigColor("sidebar", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebar") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.background")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarBackground")}
value={getConfigColor("sidebarBackground")}
onChange={(color) => updateConfigColor("sidebarBackground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarBackground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.foreground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarForeground")}
value={getConfigColor("sidebarForeground")}
onChange={(color) => updateConfigColor("sidebarForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarPrimary")}
value={getConfigColor("sidebarPrimary")}
onChange={(color) => updateConfigColor("sidebarPrimary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarPrimary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarPrimaryForeground")}
value={getConfigColor("sidebarPrimaryForeground")}
onChange={(color) => updateConfigColor("sidebarPrimaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarPrimaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accent")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarAccent")}
value={getConfigColor("sidebarAccent")}
onChange={(color) => updateConfigColor("sidebarAccent", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarAccent") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accentForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarAccentForeground")}
value={getConfigColor("sidebarAccentForeground")}
onChange={(color) => updateConfigColor("sidebarAccentForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarAccentForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.border")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarBorder")}
value={getConfigColor("sidebarBorder")}
onChange={(color) => updateConfigColor("sidebarBorder", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarBorder") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.ring")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarRing")}
value={getConfigColor("sidebarRing")}
onChange={(color) => updateConfigColor("sidebarRing", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarRing") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-1">
<div className=""></div>
</div>
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="outline" onClick={resetToDefaults}>
{t("shared.reset")}
</Button>
<Button
type="submit"
variant={"default"}
disabled={fetcher.state === "submitting"}
className={cn(fetcher.state === "submitting" && "base-spinner")}
>
{t("shared.save")}
</Button>
</div>
</div>
</fetcher.Form>
{/* CSS Configuration Modal */}
<ModalOrSlide
type="slide"
open={cssDialogOpen}
setOpen={setCssDialogOpen}
title={t("settings:tenant.theme.editor.title")}
description={t("settings:tenant.theme.editor.description")}
size="3xl"
buttons={
<div className="flex justify-end gap-2">
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm" asChild>
<Link to="https://tweakcn.com/editor/theme" target="_blank">
<ExternalLinkIcon className="mr-2 h-4 w-4" />
{t("settings:tenant.theme.editor.externalEditor")}
</Link>
</Button>
{/* <Button
type="button"
variant="outline"
size="sm"
onClick={() => {
navigator.clipboard.writeText(cssEditorValue);
toast.success(t("settings:tenant.theme.editor.cssCopied"));
}}
>
<CopyIcon className="mr-2 h-4 w-4" />
Copy
</Button> */}
<Button type="button" onClick={handleApplyCss} size="sm">
{t("settings:tenant.theme.editor.applyChanges")}
</Button>
</div>
</div>
}
>
<MonacoEditor
className="h-[calc(100vh-180px)] overflow-hidden"
value={cssEditorValue}
onChange={(value) => setCssEditorValue(value || "")}
language="css"
theme="vs-dark"
/>
</ModalOrSlide>
</div>
);
}
@@ -1,32 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const sourcePath = path.resolve(process.cwd(), "apps/web/app/components/core/tenants/forms/UpdateTenantFormTheme.tsx");
describe("tenant theme form i18n", () => {
it("uses semantic settings keys for appearance, color tokens, sidebar, and CSS editor copy", () => {
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).toContain("settings:tenant.theme.appearance.title");
expect(source).toContain("settings:tenant.theme.appearance.themePreset");
expect(source).toContain("theme.labelKey");
expect(source).toContain("settings:tenant.theme.appearance.defaultSystemUi");
expect(source).toContain("settings:tenant.theme.appearance.fontFamilies.sansSerif");
expect(source).toContain("settings:tenant.theme.appearance.fontFamilies.jetbrainsMono");
expect(source).toContain("settings:tenant.theme.colors.title");
expect(source).toContain("settings:tenant.theme.tokens.primaryForeground");
expect(source).toContain("settings:tenant.theme.sidebar.styleOptions.inset");
expect(source).toContain("settings:tenant.theme.editor.cssApplied");
expect(source).toContain("settings:tenant.theme.editor.applyChanges");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain('"Use default theme"');
expect(source).not.toContain(">Reset<");
expect(source).not.toContain('"Default"');
expect(source).not.toContain('"Colors"');
expect(source).not.toContain('"Inset (Light)"');
expect(source).not.toContain('name: "Sans Serif"');
expect(source).not.toContain('name: "JetBrains Mono"');
expect(source).not.toContain("<span>{theme.name}</span>");
});
});
@@ -1,72 +0,0 @@
import { useState, useEffect, useRef, Fragment } from "react";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useTranslation } from "react-i18next";
import FormGroup from "~/components/ui/forms/FormGroup";
import InputText, { RefInputText } from "~/components/ui/input/InputText";
import { useNavigate } from "react-router";
import { TenantTypeWithDetails } from "~/utils/db/tenants/tenantTypes.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import InputCheckboxCards from "~/components/ui/input/InputCheckboxCards";
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
export function TenantTypeForm({ item, allSubscriptionProducts }: { item?: TenantTypeWithDetails; allSubscriptionProducts: SubscriptionProductDto[] }) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
const navigate = useNavigate();
const [title, setTitle] = useState(item?.title || "");
const [titlePlural, setTitlePlural] = useState(item?.titlePlural || "");
const [description, setDescription] = useState(item?.description || "");
const [isDefault, setIsDefault] = useState(item?.isDefault || false);
const [subscriptionProducts, setSubscriptionProducts] = useState(item?.subscriptionProducts.map((p) => p.id) || []);
const input = useRef<RefInputText>(null);
useEffect(() => {
setTimeout(() => {
input.current?.input.current?.focus();
}, 100);
}, []);
return (
<FormGroup
id={item?.id}
onCancel={() => navigate(adminPath("settings/accounts/types", { mode: "host-aware" }))}
editing={true}
canDelete={getUserHasPermission(appOrAdminData, "admin.accountTypes.delete")}
>
<div className="space-y-2">
<InputText ref={input} autoFocus name="title" title={t("shared.title")} value={title} setValue={setTitle} required />
<InputText name="titlePlural" title={t("shared.titlePlural")} value={titlePlural} setValue={setTitlePlural} required />
<InputText name="description" title={t("shared.description")} value={description} setValue={setDescription} />
<InputCheckboxWithDescription
name="isDefault"
title={t("settings.admin.tenants.types.fields.isDefault.title")}
value={isDefault}
setValue={setIsDefault}
description={t("settings.admin.tenants.types.fields.isDefault.description")}
/>
<Fragment>
{subscriptionProducts?.map((item, idx) => {
return <input key={idx} type="hidden" name={`subscriptionProducts[]`} value={item} />;
})}
<InputCheckboxCards
columns={1}
title={t("models.subscriptionProduct.plural")}
value={subscriptionProducts}
onChange={(e) => setSubscriptionProducts(e as string[])}
display={"name"}
options={allSubscriptionProducts.map((f) => {
return {
value: f.id ?? "",
name: t(f.title),
};
})}
/>
</Fragment>
<input type="hidden" name="action" value="create" hidden readOnly />
</div>
</FormGroup>
);
}
@@ -1,4 +1,4 @@
import { AdminUser, Role, UserRole } from "@hivegrid/db/prisma-browser";
import { Role, UserRole } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
import AtSymbolIcon from "~/components/ui/icons/AtSymbolIcon";
import UserAvatarBadge from "./UserAvatarBadge";
@@ -14,7 +14,7 @@ interface Props {
lastName: string;
avatar?: string | null;
};
admin?: AdminUser | null;
admin?: { userId: string } | null;
withEmail?: boolean;
withAvatar?: boolean;
withSignUpMethod?: boolean;
@@ -1,4 +1,4 @@
import { Log, Role, User } from "@hivegrid/db/prisma-browser";
import { Role, User } from "@hivegrid/db/prisma-browser";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSubmit } from "react-router";
@@ -14,6 +14,10 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { useRootData } from "~/utils/data/useRootData";
import { roleDisplayName } from "../roles/roleDisplay";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { TextArea } from "~/ui/components/TextArea";
import type { AdminUserLastActivity } from "~/utils/db/logs.db.server";
interface Props {
items: UserWithDetails[];
@@ -22,7 +26,7 @@ interface Props {
canSetUserRoles?: boolean;
canDelete: boolean;
pagination?: PaginationDto;
lastLogs?: { userId: string; log: Log }[];
lastLogs?: { userId: string; log: AdminUserLastActivity }[];
}
export default function UsersTable({ items, canImpersonate, canChangePassword, canSetUserRoles, canDelete, pagination, lastLogs }: Props) {
const { i18n, t } = useTranslation();
@@ -34,6 +38,8 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
const [headers, setHeaders] = useState<RowHeaderDisplayDto<UserWithDetails>[]>([]);
const [actions, setActions] = useState<RowHeaderActionDto<UserWithDetails>[]>([]);
const [impersonatingUser, setImpersonatingUser] = useState<UserWithDetails | null>(null);
const [impersonationReason, setImpersonationReason] = useState("");
useEffect(() => {
function getRoleNames(user: UserWithDetails, tenantId: string | null) {
@@ -123,7 +129,10 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
if (canImpersonate) {
actions.push({
title: t("models.user.impersonate"),
onClick: (_, item) => impersonate(item),
onClick: (_, item) => {
setImpersonationReason("");
setImpersonatingUser(item);
},
disabled: (_) => !canImpersonate,
});
}
@@ -155,13 +164,14 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formatters, items, lastLogs, t]);
function impersonate(user: UserWithDetails) {
function impersonate(user: UserWithDetails, reason: string) {
const form = new FormData();
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
form.set("action", "impersonate");
form.set("user-id", user.id);
form.set("reason", reason.trim());
submit(form, {
action: adminPath("accounts/users", { mode: "host-aware" }),
method: "post",
@@ -205,6 +215,41 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
return (
<div>
<TableSimple items={items} headers={headers} actions={actions} pagination={pagination} />
<Dialog open={impersonatingUser !== null} onOpenChange={(open: boolean) => (open ? undefined : setImpersonatingUser(null))}>
<Dialog.Content className="w-[560px] max-w-[90vw] p-4">
{impersonatingUser ? (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.admin.users.impersonate.dialog">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("admin.users.impersonation.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("admin.users.impersonation.body", { email: impersonatingUser.email })}
</span>
</div>
<TextArea showLabel label={t("admin.users.impersonation.reasonLabel")} helpText={t("admin.users.impersonation.reasonHelp")}>
<TextArea.Input
value={impersonationReason}
onChange={(event) => setImpersonationReason(event.currentTarget.value)}
placeholder={t("admin.users.impersonation.reasonPlaceholder")}
data-ui-id="ui.admin.users.impersonate.reason"
/>
</TextArea>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={() => setImpersonatingUser(null)}>{t("shared.cancel")}</Button>
<Button
disabled={impersonationReason.trim().length < 10}
onClick={() => {
impersonate(impersonatingUser, impersonationReason);
setImpersonatingUser(null);
}}
data-ui-id="ui.admin.users.impersonate.confirm"
>
{t("models.user.impersonate")}
</Button>
</div>
</div>
) : null}
</Dialog.Content>
</Dialog>
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteUser} destructive />
</div>
);
@@ -217,7 +262,7 @@ function LastActivity({
formatters,
}: {
item: UserWithDetails;
lastLogs?: { userId: string; log: Log }[];
lastLogs?: { userId: string; log: AdminUserLastActivity }[];
action?: string;
formatters: LocaleFormatters;
}) {
@@ -1,430 +0,0 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation detail.
// Pure component: it receives the server-built KontaktDetailVM data + the
// Activity-Stream VM + option lists and renders the inline-edit forms (DoD 3).
// It NEVER calls useLoaderData/useFetcher (the route injects the data) and holds
// no server imports; every form posts back to the current route's action.
import { useTranslation } from "react-i18next";
import type { ActivityStreamVM, KontaktDetailData } from "@hivegrid/view-models";
export type KontaktDetailViewProps = {
data: KontaktDetailData;
activity: ActivityStreamVM;
allTags: { id: string; name: string; farbe: string }[];
customFieldDefs: { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string }[];
ownerOptions: { id: string; label: string }[];
backHref: string;
listLabelKey: string;
errorKey?: string | null;
};
const crmFieldLabelClass = "block text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
const crmFieldControlClass =
"mt-1 h-9 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
const crmTextareaClass =
"mt-1 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 py-2 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
export default function KontaktDetailView(props: KontaktDetailViewProps) {
const { t, i18n } = useTranslation();
const { data } = props;
const isOrg = data.kontaktTyp === "organisation";
const dateTime = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
return (
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail">
<nav className="text-muted-foreground mb-4 text-sm" aria-label={t("crm.detail.breadcrumb")} data-ui-id="ui.crm.detail.breadcrumb">
<a href={props.backHref} className="hover:text-foreground" data-ui-id="ui.crm.detail.back">
{t(props.listLabelKey)}
</a>
<span className="px-2">{"/"}</span>
<span className="text-foreground">{data.displayName}</span>
</nav>
<header className="flex flex-wrap items-center gap-3">
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.typLabelKey)}</span>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.statusLabelKey)}</span>
{data.isArchived ? <span className="text-destructive text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</header>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.detail.error">
{t(props.errorKey)}
</p>
) : null}
{/* --- Basics (inline edit) --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.basics">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.basics")}</h2>
{data.canWrite ? (
<form method="post" className="mt-2 grid gap-2 sm:grid-cols-2">
<input type="hidden" name="intent" value="updateBasics" />
{isOrg ? (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgName")}</span>
<input name="orgName" defaultValue={data.orgName ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgMerkmal")}</span>
<select name="orgMerkmal" defaultValue={data.orgMerkmal ?? ""} className={crmFieldControlClass}>
<option value="">{t("crm.fields.none")}</option>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((merkmal) => (
<option key={merkmal} value={merkmal}>
{t(`crm.orgMerkmal.${merkmal}`)}
</option>
))}
</select>
</label>
</>
) : (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.vorname")}</span>
<input name="vorname" defaultValue={data.vorname ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.nachname")}</span>
<input name="nachname" defaultValue={data.nachname ?? ""} className={crmFieldControlClass} />
</label>
</>
)}
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.status")}</span>
<select name="kontaktStatus" defaultValue={data.kontaktStatus} className={crmFieldControlClass}>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<div className="sm:col-span-2">
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.basics.save">
{t("crm.actions.save")}
</button>
</div>
</form>
) : (
<dl className="mt-2 grid grid-cols-[8rem_1fr] gap-y-1 text-sm">
<dt className="text-muted-foreground">{t("crm.fields.status")}</dt>
<dd>{t(data.statusLabelKey)}</dd>
{data.orgMerkmalLabelKey ? (
<>
<dt className="text-muted-foreground">{t("crm.fields.orgMerkmal")}</dt>
<dd>{t(data.orgMerkmalLabelKey)}</dd>
</>
) : null}
</dl>
)}
</section>
{/* --- Emails --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.emails">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.emails")}</h2>
<ul className="mt-2 text-sm">
{data.emails.map((email) => (
<li key={email.id} className="flex items-center gap-2 py-0.5" data-row-id={email.id}>
<span>{email.email}</span>
{email.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !email.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addEmail" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.email")}</span>
<input name="email" type="email" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Phones --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.telefone">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.telefone")}</h2>
<ul className="mt-2 text-sm">
{data.telefone.map((tel) => (
<li key={tel.id} className="flex items-center gap-2 py-0.5" data-row-id={tel.id}>
<span>{tel.telefon}</span>
{tel.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !tel.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addTelefon" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.telefon")}</span>
<input name="telefon" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Address (read-only) --- */}
{data.adresse ? (
<section className="mt-6" data-ui-id="ui.crm.detail.adresse">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.adresse")}</h2>
<p className="mt-1 text-sm">
{[data.adresse.strasse, data.adresse.hausnummer].filter(Boolean).join(" ")}
{data.adresse.plz || data.adresse.ort ? `, ${[data.adresse.plz, data.adresse.ort].filter(Boolean).join(" ")}` : ""}
{`, ${data.adresse.land}`}
</p>
</section>
) : null}
{/* --- Relations --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.relations">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.relations")}</h2>
<ul className="mt-2 text-sm">
{data.relationen.map((rel) => (
<li key={rel.id} className="flex items-center gap-2 py-0.5" data-row-id={rel.id}>
<span>{rel.otherKontaktId}</span>
<span className="text-muted-foreground text-xs">{t(rel.rolleLabelKey)}</span>
{rel.kontext ? <span className="text-muted-foreground text-xs">{rel.kontext}</span> : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeRelation" />
<input type="hidden" name="relationId" value={rel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addRelation" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationTarget")}</span>
<input name="zuKontaktId" required className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationRole")}</span>
<select name="rolle" className={crmFieldControlClass}>
{(["hauptkontakt", "sekundaerkontakt", "mitarbeiter", "sonstige"] as const).map((rolle) => (
<option key={rolle} value={rolle}>
{t(`crm.kontaktArt.${rolle}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationContext")}</span>
<input name="kontext" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Tags --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.tags">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.tags")}</h2>
<ul className="mt-2 flex flex-wrap gap-2 text-sm">
{data.tags.map((tag) => (
<li key={tag.id} className="border-border flex items-center gap-1 rounded border px-2 py-0.5" data-row-id={tag.id}>
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
<span>{tag.name}</span>
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTag" />
<input type="hidden" name="tagId" value={tag.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite && props.allTags.length > 0 ? (
<form method="post" className="mt-2 flex items-end gap-2">
<input type="hidden" name="intent" value="addTag" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.tag")}</span>
<select name="tagId" className={crmFieldControlClass}>
{props.allTags.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Custom fields --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.customFields">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.customFields")}</h2>
<dl className="mt-2 grid grid-cols-[10rem_1fr] gap-y-1 text-sm">
{data.customFields.map((cf) => (
<div key={cf.definitionId} className="contents" data-row-id={cf.definitionId}>
<dt className="text-muted-foreground">{cf.label}</dt>
<dd>{cf.wert == null ? "" : String(cf.wert)}</dd>
</div>
))}
</dl>
{data.canWrite && props.customFieldDefs.length > 0 ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="setCustomField" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.customField")}</span>
<select name="definitionId" className={crmFieldControlClass}>
{props.customFieldDefs.map((def) => (
<option key={def.id} value={def.id}>
{def.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.value")}</span>
<input name="wert" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.save")}
</button>
</form>
) : null}
</section>
{/* --- Quick actions --- */}
{data.canWrite || data.canDelete ? (
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.actions">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.actions")}</h2>
<div className="mt-2 flex flex-wrap items-end gap-4">
{data.canWrite ? (
<form method="post" className="flex items-end gap-2">
<input type="hidden" name="intent" value="reassign" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.owner")}</span>
<select name="zustaendigerUserId" defaultValue={data.zustaendigerUserId ?? ""} className={crmFieldControlClass}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.reassign")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post" className="flex-1">
<input type="hidden" name="intent" value="addNote" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.note")}</span>
<textarea name="note" required rows={2} className={crmTextareaClass} />
</label>
<button type="submit" className="text-theme-600 mt-1 text-sm font-medium" data-ui-id="ui.crm.detail.addNote">
{t("crm.actions.addNote")}
</button>
</form>
) : null}
</div>
<div className="mt-3 flex flex-wrap gap-3">
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value={data.isArchived ? "reactivate" : "archive"} />
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.archive">
{t(data.isArchived ? "crm.actions.reactivate" : "crm.actions.archive")}
</button>
</form>
) : null}
{data.canDelete ? (
<form method="post">
<input type="hidden" name="intent" value="delete" />
<button type="submit" className="text-destructive text-sm font-medium" data-ui-id="ui.crm.detail.delete">
{t("crm.actions.delete")}
</button>
</form>
) : null}
</div>
</section>
) : null}
{/* --- Activity stream --- */}
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.activity">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.activity")}</h2>
{props.activity.status === "ready" && props.activity.data ? (
<ul className="mt-2 space-y-2 text-sm">
{props.activity.data.entries.map((entry) => (
<li key={entry.id} className="border-border border-l-2 pl-3" data-row-id={entry.id}>
<p>{entry.summaryText}</p>
<p className="text-muted-foreground text-xs">
{t(entry.activityLabelKey)}
{entry.actorLabel ? ` · ${entry.actorLabel}` : ""} · <time dateTime={entry.createdAtIso}>{dateTime.format(new Date(entry.createdAtIso))}</time>
</p>
</li>
))}
</ul>
) : (
<p className="text-muted-foreground mt-2 text-sm" data-ui-id="ui.crm.detail.activity.empty">
{t("crm.detail.activityEmpty")}
</p>
)}
</section>
</main>
);
}
@@ -1,256 +0,0 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation browser.
// Pure component: it renders the server-built KontaktListVM (filter / sort /
// paginate / bulk / CSV, DoD 2). The filter bar is a GET form (state lives in the
// URL); bulk actions are a POST form whose checkboxes carry the selected ids.
// No useLoaderData/useFetcher, no server imports.
import { useTranslation } from "react-i18next";
import type { KontaktListVM } from "@hivegrid/view-models";
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
export type KontaktListViewProps = {
moduleActive: boolean;
variant: "contacts" | "companies";
vm: KontaktListVM;
tagOptions: { id: string; name: string; farbe: string }[];
ownerOptions: { id: string; label: string }[];
query: KontaktListQuery;
baseHref: string;
newHref: string;
exportHref: string;
errorKey?: string | null;
};
function pageHref(baseHref: string, query: KontaktListQuery, page: number): string {
const params = kontaktListQueryToParams({ ...query, page });
const qs = params.toString();
return qs ? `${baseHref}?${qs}` : baseHref;
}
export default function KontaktListView(props: KontaktListViewProps) {
const { t } = useTranslation();
const titleKey = props.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
const emptyHeadlineKey = props.variant === "companies" ? "crm.empty.companies.headline" : "crm.empty.contacts.headline";
const emptyBodyKey = props.variant === "companies" ? "crm.empty.companies.body" : "crm.empty.contacts.body";
if (!props.moduleActive) {
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.list">
<div className="mt-10 text-center" data-ui-id="ui.crm.list.locked">
<p className="text-foreground font-medium">{t("crm.locked.headline")}</p>
<p className="text-muted-foreground mt-1 text-sm">{t("crm.locked.body")}</p>
</div>
</main>
);
}
const data = props.vm.status === "ready" ? props.vm.data : null;
const { filter, sort } = props.query;
return (
<main className="mx-auto max-w-6xl px-4 py-10" data-ui-id="ui.crm.list">
<header className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-foreground text-xl font-semibold">{t(titleKey)}</h1>
<div className="flex gap-3 text-sm">
<a href={props.exportHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.export">
{t("crm.actions.exportCsv")}
</a>
<a href={props.newHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.new">
{t("crm.actions.newContact")}
</a>
</div>
</header>
{/* --- Filter bar (GET, URL-driven, server-side) --- */}
<form method="get" action={props.baseHref} className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.list.filter">
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.search")}</span>
<input name="q" defaultValue={filter.search ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1" />
</label>
{props.variant === "contacts" ? (
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.type")}</span>
<select name="typ" defaultValue={filter.kontaktTyp ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
<option value="privatperson">{t("crm.kontaktTyp.privatperson")}</option>
<option value="organisation">{t("crm.kontaktTyp.organisation")}</option>
</select>
</label>
) : null}
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.status")}</span>
<select name="status" defaultValue={filter.kontaktStatus ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.owner")}</span>
<select name="owner" defaultValue={filter.zustaendigerUserId ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tags")}</span>
<select name="tags" multiple defaultValue={filter.tagIds ?? []} className="border-muted-foreground/40 rounded border px-2 py-1">
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tagMatch")}</span>
<select name="tagMatch" defaultValue={filter.tagMatch} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="or">{t("crm.filter.tagMatchOr")}</option>
<option value="and">{t("crm.filter.tagMatchAnd")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.sort")}</span>
<select name="sort" defaultValue={sort.field} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="createdAt">{t("crm.filter.sortCreated")}</option>
<option value="name">{t("crm.filter.sortName")}</option>
<option value="kontaktStatus">{t("crm.filter.sortStatus")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.direction")}</span>
<select name="dir" defaultValue={sort.dir} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="desc">{t("crm.filter.dirDesc")}</option>
<option value="asc">{t("crm.filter.dirAsc")}</option>
</select>
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="archived" value="1" defaultChecked={filter.includeArchived} /> {t("crm.filter.includeArchived")}
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="demo" value="show" defaultChecked={filter.includeDemoData} /> {t("onboarding.demoData.showInLists")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.applyFilter")}
</button>
</form>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.list.error">
{t(props.errorKey)}
</p>
) : null}
{!data ? (
<div className="mt-10 text-center" data-ui-id="ui.crm.list.empty">
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
<a href={props.newHref} className="text-theme-600 mt-2 inline-block text-sm font-medium">
{t("crm.actions.newContact")}
</a>
</div>
) : (
<form method="post" className="mt-6" data-ui-id="ui.crm.list.bulkForm">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm" data-ui-id="ui.crm.list.table">
<thead>
<tr className="text-muted-foreground border-b">
<th className="py-2" />
<th className="py-2">{t("crm.column.name")}</th>
<th className="py-2">{t("crm.column.type")}</th>
<th className="py-2">{t("crm.column.status")}</th>
<th className="py-2">{t("crm.column.email")}</th>
<th className="py-2">{t("crm.column.telefon")}</th>
<th className="py-2">{t("crm.column.owner")}</th>
<th className="py-2">{t("crm.column.tags")}</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.id} className="border-b" data-row-id={row.id}>
<td className="py-2">
<input type="checkbox" name="kontaktId" value={row.id} aria-label={t("crm.actions.select")} />
</td>
<td className="py-2">
<a href={row.detailHref} className="text-theme-600">
{row.displayName}
</a>
{row.isArchived ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</td>
<td className="py-2">{t(row.typLabelKey)}</td>
<td className="py-2">{t(row.statusLabelKey)}</td>
<td className="py-2">{row.primaerEmail ?? ""}</td>
<td className="py-2">{row.primaerTelefon ?? ""}</td>
<td className="py-2">{row.zustaendigerLabel ?? ""}</td>
<td className="py-2">
{row.tagChips.map((tag) => (
<span key={tag.id} className="mr-1 inline-flex items-center gap-1">
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
{tag.name}
</span>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* --- Bulk actions (operate on the checked rows) --- */}
<div className="mt-4 flex flex-wrap items-end gap-3" data-ui-id="ui.crm.list.bulk">
<button type="submit" name="intent" value="bulkArchive" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkArchive")}
</button>
<span className="flex items-end gap-1">
<select name="zustaendigerUserId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.owner")}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkReassign" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkReassign")}
</button>
</span>
<span className="flex items-end gap-1">
<select name="tagId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.tag")}>
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkTag" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkTag")}
</button>
</span>
</div>
<nav className="mt-4 flex items-center gap-4 text-sm" data-ui-id="ui.crm.list.pagination">
{data.pagination.hasPrev ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page - 1)} className="text-theme-600">
{t("crm.pagination.prev")}
</a>
) : null}
<span className="text-muted-foreground">
{t("crm.pagination.page", { page: data.pagination.page, pageCount: Math.max(data.pagination.pageCount, 1), total: data.pagination.total })}
</span>
{data.pagination.hasNext ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page + 1)} className="text-theme-600">
{t("crm.pagination.next")}
</a>
) : null}
</nav>
</form>
)}
</main>
);
}
@@ -14,5 +14,14 @@ describe("Lazy Monaco editor boundary", () => {
const clientSource = readRepoFile("apps/web/app/components/editors/MonacoEditor.client.tsx");
expect(clientSource).toContain('from "@monaco-editor/react"');
expect(clientSource).toContain('from "monaco-editor/esm/vs/editor/editor.api.js"');
expect(clientSource).not.toContain('from "monaco-editor"');
expect(clientSource).toContain("loader.config({ monaco })");
expect(clientSource).toContain("globalThis.MonacoEnvironment");
expect(clientSource.match(/monaco-editor\/.+\?worker/g)).toHaveLength(5);
expect(clientSource).toContain("globalThis.location.origin");
expect(clientSource).toContain("new Worker(sameOriginUrl");
expect(clientSource).not.toMatch(/https?:\/\//);
expect(clientSource).not.toContain("cdn.jsdelivr.net");
});
});
@@ -1,8 +1,57 @@
import { Editor, useMonaco } from "@monaco-editor/react";
import { Editor, loader, useMonaco } from "@monaco-editor/react";
import clsx from "clsx";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
import "monaco-editor/esm/vs/editor/editor.all.js";
import "monaco-editor/esm/vs/language/css/monaco.contribution.js";
import "monaco-editor/esm/vs/language/html/monaco.contribution.js";
import "monaco-editor/esm/vs/language/json/monaco.contribution.js";
import "monaco-editor/esm/vs/language/typescript/monaco.contribution.js";
import "monaco-editor/esm/vs/basic-languages/css/css.contribution.js";
import "monaco-editor/esm/vs/basic-languages/html/html.contribution.js";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/markdown/markdown.contribution.js";
import "monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js";
import "monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js";
import CssWorkerUrl from "monaco-editor/esm/vs/language/css/css.worker?worker&url";
import EditorWorkerUrl from "monaco-editor/esm/vs/editor/editor.worker?worker&url";
import HtmlWorkerUrl from "monaco-editor/esm/vs/language/html/html.worker?worker&url";
import JsonWorkerUrl from "monaco-editor/esm/vs/language/json/json.worker?worker&url";
import TypeScriptWorkerUrl from "monaco-editor/esm/vs/language/typescript/ts.worker?worker&url";
import { Fragment, useEffect } from "react";
import { useTranslation } from "react-i18next";
const MONACO_WORKER_URLS: Readonly<Record<string, string>> = {
css: CssWorkerUrl,
handlebars: HtmlWorkerUrl,
html: HtmlWorkerUrl,
javascript: TypeScriptWorkerUrl,
json: JsonWorkerUrl,
less: CssWorkerUrl,
razor: HtmlWorkerUrl,
scss: CssWorkerUrl,
typescript: TypeScriptWorkerUrl,
};
export function createMonacoWorker(label: string): Worker {
const emittedUrl = MONACO_WORKER_URLS[label] ?? EditorWorkerUrl;
const resolvedUrl = new URL(emittedUrl, globalThis.location.href);
// Worker constructors require same-origin URLs. Keep worker entry points on
// the application origin even when the regular Vite asset base points at a
// first-party CDN; the immutable assets remain available at the origin.
const sameOriginUrl = new URL(`${resolvedUrl.pathname}${resolvedUrl.search}${resolvedUrl.hash}`, globalThis.location.origin);
return new Worker(sameOriginUrl, { name: `monaco-${label || "editor"}` });
}
if (typeof window !== "undefined") {
globalThis.MonacoEnvironment = {
getWorker: (_moduleId: string, label: string) => createMonacoWorker(label),
};
// Passing the locally installed ESM runtime prevents @monaco-editor/react's
// default AMD loader from downloading executable code from jsDelivr.
loader.config({ monaco });
}
export type MonacoAutoCompletion = {
label: string;
kind: any;
@@ -1,6 +1,7 @@
import { useState } from "react";
import { useParams } from "react-router";
import { useFetcher, useParams } from "react-router";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import AddFeedbackButton from "./buttons/AddFeedbackButton";
import ChatSupportButton from "./buttons/ChatSupportButton";
import CurrentSubscriptionButton from "./buttons/CurrentSubscriptionButton";
@@ -36,16 +37,40 @@ export default function NavBar({
children?: React.ReactNode;
}) {
const appOrAdminData = useAppOrAdminData();
const rootData = useRootData();
const params = useParams();
const notificationsPath =
layout === "admin" ? adminPath("notifications", { mode: "host-aware" }) : params.tenant ? appPath({ tenantSlug: params.tenant, path: "notifications", mode: "host-aware" }) : "/notifications";
// AK-P3 (AD-28): tenant-app bell opens the notifications drawer with a live
// SSE unseen count; the stream route is tenant-scoped, so the admin layout
// keeps the plain link (documented Dev-Nachzug in the ticket doc).
const canReadPlatformLeads = appOrAdminData.permissions?.some(
(permission) => permission === "admin.leads.read_own" || permission === "admin.leads.read_all"
);
const isPlatformLeadAdmin = layout === "admin" && canReadPlatformLeads;
const notificationsPath = isPlatformLeadAdmin
? adminPath("leads", { mode: "host-aware" })
: layout === "admin"
? adminPath("notifications", { mode: "host-aware" })
: params.tenant
? appPath({ tenantSlug: params.tenant, path: "notifications", mode: "host-aware" })
: "/notifications";
const isTenantApp = layout === "app" && Boolean(params.tenant);
const streamPath = isTenantApp && params.tenant ? appPath({ tenantSlug: params.tenant, path: "notifications/stream", mode: "host-aware" }) : null;
const streamPath = isPlatformLeadAdmin
? adminPath("leads/notifications-stream", { mode: "host-aware" })
: isTenantApp && params.tenant
? appPath({ tenantSlug: params.tenant, path: "notifications/stream", mode: "host-aware" })
: null;
const notificationsStream = useNotificationsStream(streamPath, []);
const notificationReadFetcher = useFetcher();
const [notificationsDrawerOpen, setNotificationsDrawerOpen] = useState(false);
const hasNotificationDrawer = isTenantApp || isPlatformLeadAdmin;
function openNotificationsDrawer() {
setNotificationsDrawerOpen(true);
if (!isPlatformLeadAdmin || !streamPath) return;
const unreadIds = notificationsStream.items.filter((item) => !item.isRead).map((item) => item.id);
if (unreadIds.length === 0) return;
const form = new FormData();
if (rootData.csrf) form.set("csrf", rootData.csrf);
for (const deliveryId of unreadIds) form.append("deliveryId", deliveryId);
void notificationReadFetcher.submit(form, { method: "post", action: streamPath });
}
return (
<div className="flex flex-1 justify-between space-x-2">
<div className="flex flex-1 items-center">{title && <div className="font-extrabold">{title}</div>}</div>
@@ -53,7 +78,7 @@ export default function NavBar({
{/* {layout === "app" && (
<CreditsRemaining
feature={appOrAdminData.featureSyncs}
redirectTo={appOrAdminData.currentTenant ? `/${appOrAdminData.currentTenant.slug}/settings/subscription` : "/settings/subscription"}
redirectTo={appOrAdminData.currentTenant ? `/${appOrAdminData.currentTenant.slug}/settings/billing` : "/settings/billing"}
/>
)} */}
{buttons.onboarding && appOrAdminData?.onboardingSession && (
@@ -64,11 +89,11 @@ export default function NavBar({
{buttons.notifications && appOrAdminData?.user && (
<NotificationsButton
to={notificationsPath}
unseenCount={isTenantApp ? notificationsStream.unreadCount : undefined}
onOpen={isTenantApp ? () => setNotificationsDrawerOpen(true) : undefined}
unseenCount={hasNotificationDrawer ? notificationsStream.unreadCount : undefined}
onOpen={hasNotificationDrawer ? openNotificationsDrawer : undefined}
/>
)}
{isTenantApp && (
{hasNotificationDrawer && (
<NotificationsDrawer
open={notificationsDrawerOpen}
items={notificationsStream.items}
@@ -1,54 +1,76 @@
// AK-P21 (AD-28 interim polish) — global feedback widget. The mini form is a
// real ~/ui Dialog (size XS 420) with a category select (bug/feature/question,
// designer brief P21); the category is prefixed into the message because the
// support-ticket contract intentionally has no category column. Shared by the
// legacy NavBar trigger (mobile visibility restriction removed) and the shadcn
// nav-actions trigger. Submission keeps the established add-feedback intent on
// the tenant root route (rate limit 3/24h lives in Feedback.server).
//
// Instead of the originally sketched screenshot checkbox, the reporter attaches
// an image themselves (decision 2026-07-21): the client never captures the page
// on its own, so no third-party personal data leaves the workspace without the
// reporter consciously picking the file. The upload is fail-closed scanned and
// ClamAV-checked server-side.
import { useFetcher, useLocation, useParams } from "react-router";
import { Fragment, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import StarsIconFilled from "~/components/ui/icons/StarsIconFilled";
import InputText from "~/components/ui/input/InputText";
import Modal from "~/components/ui/modals/Modal";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
const FEEDBACK_CATEGORIES = ["bug", "feature", "question"] as const;
type FeedbackCategory = (typeof FEEDBACK_CATEGORIES)[number];
/** Mirrors the server-side contract in Feedback.server. */
const FEEDBACK_ATTACHMENT_ACCEPT = "image/png,image/jpeg,image/webp,image/gif";
const FEEDBACK_ATTACHMENT_MAX_MB = 5;
export default function AddFeedbackButton() {
const [isOpen, setIsOpen] = useState(false);
const { t } = useTranslation();
return (
<Fragment>
<div className="relative hidden sm:inline-flex">
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<div className="relative z-0 inline-flex rounded-full text-sm shadow-none">
<button
onClick={() => setIsOpen(!isOpen)}
type="button"
className="text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus:z-10 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
aria-haspopup="listbox"
aria-expanded="true"
aria-label={t("feedback.title")}
>
<span className="sr-only">{t("feedback.title")}</span>
<StarsIconFilled className="h-5 w-5 p-0.5" />
</button>
</div>
</div>
</div>
<div className="relative inline-flex">
<button
onClick={() => setIsOpen(!isOpen)}
type="button"
className="text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus:z-10 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
aria-haspopup="dialog"
aria-expanded={isOpen}
aria-label={t("feedback.title")}
>
<span className="sr-only">{t("feedback.title")}</span>
<StarsIconFilled className="h-5 w-5 p-0.5" />
</button>
</div>
<Modal open={isOpen} setOpen={setIsOpen} size="sm">
<FeedbackForm onClose={() => setIsOpen(false)} />
</Modal>
<FeedbackFormDialog open={isOpen} onClose={() => setIsOpen(false)} />
</Fragment>
);
}
function FeedbackForm({ onClose }: { onClose: () => void }) {
export function FeedbackFormDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { t } = useTranslation();
const params = useParams();
const appOrAdminData = useAppOrAdminData();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const location = useLocation();
const [category, setCategory] = useState<FeedbackCategory>("bug");
const [attachmentError, setAttachmentError] = useState<string | null>(null);
useEffect(() => {
if (open) {
setCategory("bug");
setAttachmentError(null);
}
}, [open]);
useEffect(() => {
if (fetcher.data?.success) {
@@ -60,31 +82,109 @@ function FeedbackForm({ onClose }: { onClose: () => void }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetcher.data]);
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
const submitting = fetcher.state !== "idle";
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
fetcher.submit(e.currentTarget, {
if (attachmentError) return;
void fetcher.submit(e.currentTarget, {
method: "post",
action: appPath({ tenantSlug: params.tenant ?? "", mode: "host-aware" }),
encType: "multipart/form-data",
action: params.tenant ? appPath({ tenantSlug: params.tenant, mode: "host-aware" }) : "",
});
// onClose();
};
// Reject oversized or non-image picks before the upload is attempted; the
// server enforces the same limits again.
const onAttachmentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.currentTarget.files?.[0] ?? null;
if (!file) {
setAttachmentError(null);
return;
}
if (file.size > FEEDBACK_ATTACHMENT_MAX_MB * 1024 * 1024) {
setAttachmentError(t("feedback.attachment.tooLarge", { megabytes: FEEDBACK_ATTACHMENT_MAX_MB }));
return;
}
if (!FEEDBACK_ATTACHMENT_ACCEPT.split(",").includes(file.type)) {
setAttachmentError(t("feedback.attachment.unsupportedType"));
return;
}
setAttachmentError(null);
};
return (
<fetcher.Form onSubmit={onSubmit} method="post">
<input type="hidden" name="action" value="add-feedback" readOnly hidden />
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly hidden />
<input type="hidden" name="tenantId" value={appOrAdminData.currentTenant?.id} readOnly hidden />
<input type="hidden" name="fromUrl" value={location.pathname} readOnly hidden />
<div className="space-y-3">
<h3 className="text-lg font-medium leading-6">{t("feedback.title")}</h3>
<p className="text-muted-foreground text-sm">{t("feedback.description")}</p>
<InputText name="message" title="feedback.message" withLabel={false} defaultValue="" required rows={5} placeholder={t("feedback.placeholder")} />
<div className="flex justify-between">
<button type="button" onClick={onClose} className="text-muted-foreground text-sm hover:underline">
{t("shared.cancel")}
</button>
<ButtonPrimary type="submit">{t("feedback.send")}</ButtonPrimary>
</div>
</div>
</fetcher.Form>
<Dialog open={open} onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onClose())}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-4" aria-label={t("feedback.title")} data-ui-id="ui.feedback.dialog">
<fetcher.Form onSubmit={onSubmit} method="post" className="flex w-full flex-col items-start">
<input type="hidden" name="action" value="add-feedback" readOnly hidden />
<input type="hidden" name="csrf" value={csrf ?? ""} readOnly hidden />
<input type="hidden" name="tenantId" value={appOrAdminData.currentTenant?.id} readOnly hidden />
<input type="hidden" name="fromUrl" value={location.pathname} readOnly hidden />
{/* Radix Select is not a native form control — mirror the picked category. */}
<input type="hidden" name="category" value={category} readOnly hidden />
<div className="flex w-full flex-col items-start gap-2">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("feedback.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("feedback.description")}</span>
</div>
<div className="flex w-full flex-col items-start gap-4 pt-4">
<Select
className="w-full max-w-none"
showLabel
label={t("feedback.category.label")}
value={category}
onValueChange={(value: string) => setCategory(FEEDBACK_CATEGORIES.includes(value as FeedbackCategory) ? (value as FeedbackCategory) : "bug")}
data-ui-id="ui.feedback.category"
>
{FEEDBACK_CATEGORIES.map((key) => (
<Select.Item key={key} value={key}>
{t(`feedback.category.${key}`)}
</Select.Item>
))}
</Select>
<TextArea className="w-full max-w-none" label={t("feedback.message")} showLabel>
<TextArea.Input name="message" defaultValue="" rows={5} placeholder={t("feedback.placeholder")} required data-ui-id="ui.feedback.message" />
</TextArea>
<div className="flex w-full flex-col items-start gap-1">
<label
className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
htmlFor="feedback-attachment"
>
{t("feedback.attachment.label")}
</label>
<input
id="feedback-attachment"
type="file"
name="attachment"
accept={FEEDBACK_ATTACHMENT_ACCEPT}
onChange={onAttachmentChange}
data-ui-id="ui.feedback.attachment"
className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full"
/>
{attachmentError ? (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-feedback-negative" role="alert">
{attachmentError}
</span>
) : (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("feedback.attachment.hint", { megabytes: FEEDBACK_ATTACHMENT_MAX_MB })}
</span>
)}
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("feedback.rateLimitHint")}
</span>
</div>
<div className="flex w-full items-center justify-end gap-2 pt-4">
<Button type="button" variant="tertiary" disabled={submitting} onClick={onClose}>
{t("shared.cancel")}
</Button>
<Button type="submit" loading={submitting} disabled={Boolean(attachmentError)} data-ui-id="ui.feedback.send">
{t("feedback.send")}
</Button>
</div>
</fetcher.Form>
</Dialog.Content>
</Dialog>
);
}
@@ -19,7 +19,7 @@ export default function ChatSupportButton() {
$crisp?.push(["do", "chat:hide"]);
setIsOpen(false);
}
} catch (e) {
} catch (_e) {
// ignore
}
}
@@ -22,7 +22,7 @@ export default function CurrentSubscriptionButton() {
<div className="hidden divide-x divide-gray-300 rounded-sm shadow-none lg:inline-flex">
<div className="relative z-0 inline-flex rounded-full text-xs shadow-none sm:text-sm">
<Link
to={!params.tenant ? "" : appPath({ tenantSlug: params.tenant, path: "settings/subscription", mode: "host-aware" })}
to={!params.tenant ? "" : appPath({ tenantSlug: params.tenant, path: "settings/billing", mode: "host-aware" })}
className={clsx(
"text-muted-foreground bg-secondary border-border relative inline-flex items-center space-x-1 rounded-md border p-2 font-medium shadow-inner hover:bg-teal-50 hover:text-teal-800 focus:z-10 focus:bg-teal-100 focus:text-teal-900 focus:outline-hidden",
hasSubscription() &&
@@ -75,7 +75,7 @@ describe("layout button UI IDs", () => {
fireEvent.click(screen.getByLabelText("shell.profile.userMenu"));
expect(screen.getByRole("menuitem", { name: "app.navbar.profile" })).toHaveAttribute("href", "/acme/settings/profile");
expect(screen.getByRole("menuitem", { name: "app.navbar.subscription" })).toHaveAttribute("href", "/acme/settings/subscription");
expect(screen.getByRole("menuitem", { name: "app.navbar.subscription" })).toHaveAttribute("href", "/acme/settings/billing");
});
it("localizes the public admin menu link", () => {
@@ -12,4 +12,11 @@ describe("ProfileButton route fallbacks", () => {
expect(source).toContain('defaultTenantPath("settings/profile") ?? publicHeaderAdminPath("settings/profile")');
expect(source).not.toContain('defaultTenantPath("settings/profile") ?? adminShellPath("settings/profile")');
});
it("gives the tenant menu item additional vertical padding", () => {
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/layouts/buttons/ProfileButton.tsx"), "utf8");
expect(source).toContain('className="hover:bg-secondary block px-4 py-3 text-sm transition duration-150 ease-in-out"');
expect(source).toContain('data-ui-id="ui.profile.menu.tenant"');
});
});
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more