Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/services/dashboard/dashboard.server.test.ts
T

318 lines
14 KiB
TypeScript

import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { SHK_V2_TENANT_BOOTSTRAP_CONFIG } from "~/domain/tenant-bootstrap/shk-v2.config";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
import {
averageDaysToPayment,
buildWinRate,
buildOrderIntakeSeries,
buildReceivablesAging,
DASHBOARD_CUSTOMIZE_PERMISSION,
DASHBOARD_ORDER_INTAKE_MONTHS,
DASHBOARD_ACTIVITY_MAX_CANDIDATES,
DASHBOARD_MODULE_KEY,
DASHBOARD_READ_PERMISSION,
getDashboardWidgetCatalog,
getDefaultDashboardRoleLayouts,
LEGACY_DASHBOARD_PERMISSION,
resolveDashboardRole,
telephonyCallScope,
} from "./dashboard.server";
describe("dashboard layout selection", () => {
it("sends every field seat to the Monteur layout", () => {
expect(resolveDashboardRole({ seatType: "field", permissions: [] })).toBe("monteur");
// Seat wins over permissions: an on-site member keeps the Monteur layout even
// if someone granted them tenant-wide analytics.
expect(resolveDashboardRole({ seatType: "field", permissions: ["deals.read_aggregates"] })).toBe("monteur");
});
it("splits office seats by tenant-wide analytics permissions", () => {
expect(resolveDashboardRole({ seatType: "office", permissions: ["deals.read_aggregates"] })).toBe("gf");
expect(resolveDashboardRole({ seatType: "office", permissions: ["deals.read_volume_all"] })).toBe("gf");
expect(resolveDashboardRole({ seatType: "office", permissions: [] })).toBe("office");
});
it("keeps project readers without analytics rights on the office layout", () => {
// Vertrieb and Innendienst both hold `projects.read_all`; it must not promote
// them to the owner view the way the previous permission-only heuristic did.
expect(resolveDashboardRole({ seatType: "office", permissions: ["projects.read_all", "projects.write"] })).toBe("office");
});
it("routes the shipped SHK template roles to a layout that matches their seat", () => {
type TemplateRole = (typeof SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles)[number];
const roleByName = new Map<string, TemplateRole>(SHK_V2_TENANT_BOOTSTRAP_CONFIG.tenantRoles.map((role) => [role.name, role]));
const layoutFor = (name: string) => {
const role = roleByName.get(name);
if (!role) throw new Error(`Unknown template role: ${name}`);
return resolveDashboardRole({ seatType: role.seatCategory, permissions: role.permissionKeys });
};
expect(layoutFor("Monteur")).toBe("monteur");
expect(layoutFor("Vertrieb")).toBe("office");
expect(layoutFor("Innendienst")).toBe("office");
expect(layoutFor("Marketing")).toBe("office");
expect(layoutFor("Buchhaltung/Verwaltung")).toBe("office");
});
});
describe("order intake series", () => {
const now = new Date(2026, 6, 15); // 15.07.2026
const won = (year: number, month: number, value: number) => ({ wonAt: new Date(year, month - 1, 12), value });
it("buckets won value into the trailing months, oldest first", () => {
const { series, currentMonth, trailingTwelveMonths } = buildOrderIntakeSeries({
rows: [won(2026, 7, 12_000), won(2026, 7, 3_000), won(2026, 6, 8_000), won(2025, 8, 5_000)],
now,
earliestWonAt: new Date(2024, 0, 1),
});
expect(series.points).toHaveLength(DASHBOARD_ORDER_INTAKE_MONTHS);
expect(series.points.at(0)?.id).toBe("2025-07");
expect(series.points.at(-1)?.id).toBe("2026-07");
expect(series.points.at(-1)?.value).toBe(15_000);
expect(series.points.at(-2)?.value).toBe(8_000);
expect(currentMonth).toBe(15_000);
// The trailing year covers the last 12 months, so 08/2025 counts and 07/2025 does not.
expect(trailingTwelveMonths).toBe(28_000);
});
it("carries the same month a year earlier as the comparison value", () => {
const { series } = buildOrderIntakeSeries({
rows: [won(2026, 7, 10_000), won(2025, 7, 4_000)],
now,
earliestWonAt: new Date(2024, 0, 1),
});
expect(series.hasComparison).toBe(true);
expect(series.points.at(-1)).toEqual({ id: "2026-07", value: 10_000, comparisonValue: 4_000 });
});
it("omits the comparison where the workspace has no history that far back", () => {
const { series } = buildOrderIntakeSeries({
rows: [won(2026, 7, 10_000)],
// Workspace went live in May 2026 — a rendered 0 for 07/2025 would read as
// "we won nothing", not "we did not exist yet".
now,
earliestWonAt: new Date(2026, 4, 2),
});
expect(series.hasComparison).toBe(false);
expect(series.points.every((point) => point.comparisonValue === undefined)).toBe(true);
});
it("returns an all-zero series with no comparison for a workspace without won projects", () => {
const { series, currentMonth, trailingTwelveMonths } = buildOrderIntakeSeries({ rows: [], now, earliestWonAt: null });
expect(series.points).toHaveLength(DASHBOARD_ORDER_INTAKE_MONTHS);
expect(series.points.every((point) => point.value === 0)).toBe(true);
expect(series.hasComparison).toBe(false);
expect(currentMonth).toBe(0);
expect(trailingTwelveMonths).toBe(0);
});
});
describe("win rate", () => {
it("counts the won share of decided projects", () => {
const result = buildWinRate({ won: 18, lost: 7 });
expect(result.rate).toBeCloseTo(0.72);
expect(result.outcomes.map((outcome) => [outcome.id, outcome.value])).toEqual([
["won", 18],
["lost", 7],
]);
});
it("returns null while nothing was decided", () => {
// A printed 0 % would read as "we lose everything" rather than "no decisions yet".
expect(buildWinRate({ won: 0, lost: 0 }).rate).toBeNull();
});
it("ignores open projects entirely", () => {
// Only won/lost feed the fraction, so a growing pipeline cannot drag the rate down.
expect(buildWinRate({ won: 3, lost: 1 }).rate).toBe(0.75);
});
});
describe("receivables aging", () => {
const now = new Date(2026, 6, 15);
const due = (daysAgo: number) => new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000);
it("splits open value across the aging buckets", () => {
const { openReceivables, overdueReceivables, agingBuckets } = buildReceivablesAging({
invoices: [
{ amount: 1000, dueAt: due(-5) },
{ amount: 500, dueAt: due(10) },
{ amount: 250, dueAt: due(45) },
{ amount: 125, dueAt: due(75) },
{ amount: 90, dueAt: due(400) },
],
now,
});
expect(openReceivables).toBe(1965);
expect(overdueReceivables).toBe(965);
expect(agingBuckets.map((bucket) => [bucket.id, bucket.value])).toEqual([
["not_due", 1000],
["overdue_1_30", 500],
["overdue_31_60", 250],
["overdue_61_90", 125],
["overdue_90_plus", 90],
]);
});
it("treats an invoice without a due date as not yet due", () => {
const { overdueReceivables, agingBuckets } = buildReceivablesAging({ invoices: [{ amount: 800, dueAt: null }], now });
// Dunning someone because nobody entered a date is worse than waiting.
expect(overdueReceivables).toBe(0);
expect(agingBuckets.find((bucket) => bucket.id === "not_due")?.value).toBe(800);
});
it("keeps every bucket present for an empty ledger so the chart never collapses", () => {
const { openReceivables, agingBuckets } = buildReceivablesAging({ invoices: [], now });
expect(openReceivables).toBe(0);
expect(agingBuckets).toHaveLength(5);
expect(agingBuckets.every((bucket) => bucket.value === 0)).toBe(true);
});
});
describe("average days to payment", () => {
it("averages only invoices that carry a payment date", () => {
expect(
averageDaysToPayment([
{ issuedAt: new Date(2026, 5, 1), paidAt: new Date(2026, 5, 11) },
{ issuedAt: new Date(2026, 5, 1), paidAt: new Date(2026, 5, 21) },
// Paid before the field existed — averaging it in at 0 days would flatter
// the figure the owner reads a liquidity problem from.
{ issuedAt: new Date(2026, 4, 1), paidAt: null },
]),
).toBe(15);
});
it("returns null while no payment carries a date", () => {
expect(averageDaysToPayment([{ issuedAt: new Date(2026, 5, 1), paidAt: null }])).toBeNull();
expect(averageDaysToPayment([])).toBeNull();
});
});
describe("telephony call scope", () => {
it("counts the whole workspace for read_all and manage", () => {
expect(telephonyCallScope({ permissions: ["telephony.read_all"], tenantUserId: "tu_1" })).toEqual({});
expect(telephonyCallScope({ permissions: ["telephony.manage"], tenantUserId: null })).toEqual({});
});
it("binds read_own to the member's own membership", () => {
expect(telephonyCallScope({ permissions: ["telephony.read_own"], tenantUserId: "tu_1" })).toEqual({ tenantUserId: "tu_1" });
});
it("counts nothing without telephony permissions or membership", () => {
expect(telephonyCallScope({ permissions: ["dashboard.read"], tenantUserId: "tu_1" })).toBeNull();
// read_own without a membership row must not fall back to the whole workspace.
expect(telephonyCallScope({ permissions: ["telephony.read_own"], tenantUserId: null })).toBeNull();
});
});
describe("dashboard role layout contract", () => {
it("defines the R-P11b dashboard module and permissions", () => {
expect(DASHBOARD_MODULE_KEY).toBe("dashboard");
expect(DASHBOARD_READ_PERMISSION).toBe("dashboard.read");
expect(DASHBOARD_CUSTOMIZE_PERMISSION).toBe("dashboard.customize");
expect(LEGACY_DASHBOARD_PERMISSION).toBe("app.dashboard.view");
});
it("ships exactly the fixed v1 GF, office, and Monteur layouts", () => {
const layouts = getDefaultDashboardRoleLayouts();
expect(layouts.map((layout) => layout.role)).toEqual(["gf", "office", "monteur"]);
expect(layouts.find((layout) => layout.role === "monteur")?.mobileFirst).toBe(true);
expect(layouts.find((layout) => layout.role === "gf")?.widgets.map((widget) => widget.key)).toEqual([
"sales.order_intake",
"sales.kpis",
"sales.win_rate",
"finance.receivables",
"finance.days_to_payment",
"sales.forecast",
"projects.kpis",
"projects.open_defects",
"hr.requests_pending",
"projects.stage_distribution",
"activity.recent",
]);
expect(layouts.find((layout) => layout.role === "office")?.widgets.map((widget) => widget.key)).toEqual([
"projects.kpis",
"tasks.my_open",
"comms.calls_today",
"hr.requests_pending",
"projects.stage_distribution",
"activity.recent",
]);
expect(layouts.find((layout) => layout.role === "monteur")?.widgets.map((widget) => widget.key)).toEqual([
"schedule.my_today",
"projects.my_active",
"tasks.my_open",
]);
});
it("covers Sales, Projekte, Tasks, HR, Activity, and Comms in the widget catalog", () => {
const catalog = getDashboardWidgetCatalog();
const domains = new Set(catalog.map((widget) => widget.domain));
const catalogKeys = new Set(catalog.map((widget) => widget.key));
expect(domains).toEqual(new Set(["sales", "finance", "projects", "tasks", "hr", "activity", "comms", "schedule"]));
for (const layout of getDefaultDashboardRoleLayouts()) {
for (const widget of layout.widgets) {
expect(catalogKeys.has(widget.key), `${layout.role}.${widget.key}`).toBe(true);
}
}
expect(catalog.find((widget) => widget.key === "sales.kpis")?.requiredAnyPermission).toContain("projects.read_all");
expect(catalog.find((widget) => widget.key === "tasks.my_open")?.requiredAnyPermission).toContain("tasks.read_own");
});
it("scopes project widgets, defects, forecasts, and activity to visible projects", () => {
const source = readFileSync(resolveRepoPath("apps/web/app/services/dashboard/dashboard.server.ts"), "utf8");
const projectService = readFileSync(
resolveRepoPath("apps/web/app/utils/integrations/projects/projectService.server.ts"),
"utf8",
);
expect(source).toContain("projectReadScopeWhere(ctx.tenantId, ctx)");
expect(source).toContain('stageKind: "offen"');
expect(source).toContain("where: openProjectWhere");
expect(source).toContain("stageDistributionCounts");
expect(source).toContain("projekt: { is: projectWhere }");
expect(source).not.toContain("visibleDefectProjectIds");
expect(source).not.toContain("defectProjectCandidates");
expect(source).toContain('subjectType: { in: ["project", "projekt"] }');
expect(source).toContain("actorUserId: ctx.userId");
expect(source).toContain("filterAggregateReadablePipelineIdsWithTx");
// The call count reads the telephony sessions; the worker's activity rows are
// actor-less system events and could never satisfy an actor-filtered count.
expect(source).toContain("tx.telephonyCallSession.count");
// Invoices have no project relation, so the receivables tile is restricted to
// tenant-wide readers instead of being filtered by project visibility.
expect(source).toContain('const canReadReceivables = canReadForecast && ctx.permissions.includes("projects.read_all")');
expect(source).not.toContain('activityType: { in: ["call", "phone_call", "comms.call"] }');
expect(source).toContain("tx.projekt.groupBy");
expect(source).toContain("winProbabilityByStage");
expect(source).not.toContain("forecastProjects");
expect(source).not.toContain("take: 5_001");
expect(source).toContain("loadRecentVisibleActivityWithTx");
expect(DASHBOARD_ACTIVITY_MAX_CANDIDATES).toBe(500);
expect(source).toContain("scannedCandidates < DASHBOARD_ACTIVITY_MAX_CANDIDATES");
expect(source).toContain("const canReadCalendar =");
expect(source).toContain("const canReadBookings =");
expect(source).not.toContain("const canReadSchedule =");
expect(projectService).toContain('fieldKey: "aggregate:forecast"');
expect(source).not.toContain("await ensureDefaultDashboards(ctx)");
// R-P11b DoD 3: the forecast widget prefers the R-P8b pipeline aggregate
// cache, but only for tenant-wide readers — the persisted snapshot is
// tenant-wide and must never serve own-scoped visibility as if it were
// user-scoped. Pipelines without a snapshot fall back to the live groupBy.
expect(source).toContain('const forecastCacheEligible = canReadForecast && ctx.permissions.includes("projects.read_all")');
expect(source).toContain('scopeKey: "pipeline"');
expect(source).toContain("liveForecastPipelineIds");
expect(source).toContain("cachedForecastByPipeline");
});
});