Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -1,13 +1,219 @@
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");
@@ -22,20 +228,24 @@ describe("dashboard role layout contract", () => {
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([
"general.welcome",
"sales.order_intake",
"sales.kpis",
"sales.win_rate",
"finance.receivables",
"finance.days_to_payment",
"sales.forecast",
"projects.kpis",
"hr.requests_pending",
"projects.open_defects",
"hr.requests_pending",
"projects.stage_distribution",
"activity.recent",
]);
expect(layouts.find((layout) => layout.role === "office")?.widgets.map((widget) => widget.key)).toEqual([
"general.welcome",
"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([
@@ -50,7 +260,7 @@ describe("dashboard role layout contract", () => {
const domains = new Set(catalog.map((widget) => widget.domain));
const catalogKeys = new Set(catalog.map((widget) => widget.key));
expect(domains).toEqual(new Set(["general", "sales", "projects", "tasks", "hr", "activity", "comms", "schedule"]));
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);
@@ -59,4 +269,49 @@ describe("dashboard role layout contract", () => {
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");
});
});
@@ -0,0 +1,53 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const testEmitter = vi.hoisted(() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter: HoistedEventEmitter } = require("events") as typeof import("events");
return new HoistedEventEmitter();
});
vi.mock("~/utils/stream/emitter.server", () => ({
emitter: testEmitter,
}));
import { dashboardChannel, publishDashboardChange, subscribeToDashboardChanges } from "./dashboardEvents.server";
import { publishProjectBoardChange } from "~/utils/integrations/projects/projectBoardEvents.server";
describe("dashboardEvents.server", () => {
beforeEach(() => {
testEmitter.removeAllListeners();
});
it("delivers published changes to subscribers of the same tenant only", () => {
const received: string[] = [];
const otherTenant: string[] = [];
const unsubscribe = subscribeToDashboardChanges("tenant-a", (payload) => received.push(payload));
subscribeToDashboardChanges("tenant-b", (payload) => otherTenant.push(payload));
publishDashboardChange({ tenantId: "tenant-a", source: "projects" });
expect(received).toHaveLength(1);
expect(otherTenant).toHaveLength(0);
const change = JSON.parse(received[0]!) as { source: string; at: string };
expect(change.source).toBe("projects");
expect(new Date(change.at).getTime()).not.toBeNaN();
unsubscribe();
publishDashboardChange({ tenantId: "tenant-a", source: "projects" });
expect(received).toHaveLength(1);
});
it("uses a tenant-scoped channel name", () => {
expect(dashboardChannel("tenant-a")).toBe("dashboard:tenant-a");
});
it("receives a dashboard change when a project board change is published (R-P11b live wiring)", () => {
const received: string[] = [];
subscribeToDashboardChanges("tenant-a", (payload) => received.push(payload));
publishProjectBoardChange({ tenantId: "tenant-a", pipelineId: "pipeline-1", projectId: "project-1", type: "stage_changed" });
expect(received).toHaveLength(1);
expect((JSON.parse(received[0]!) as { source: string }).source).toBe("projects");
});
});
@@ -0,0 +1,48 @@
// R-P11b — tenant-wide dashboard live pub/sub. Reuses the repo's existing
// in-process EventEmitter (`~/utils/stream/emitter.server`, the same one behind
// the workflow-execution and R-P8b pipeline-board SSE streams) so relevant
// mutations push a change signal to connected dashboard SSE clients, which then
// re-send a fresh permission-gated snapshot instead of staying frozen on the
// connect-time snapshot. No new infrastructure is introduced.
//
// Scope caveat (same as projectBoardEvents.server): the emitter is per web
// process. With a single web instance every dashboard client shares the
// process; horizontal scaling would need a cross-process transport (e.g. Redis
// pub/sub) behind the same publish/subscribe API — tracked follow-up, out of
// this ticket's scope.
import { emitter } from "~/utils/stream/emitter.server";
/** Sources that currently publish dashboard-relevant changes. */
export type DashboardChangeSource = "projects";
export interface DashboardChange {
readonly source: DashboardChangeSource;
readonly at: string;
}
/** In-process channel name for one tenant's dashboard change feed. */
export function dashboardChannel(tenantId: string): string {
return `dashboard:${tenantId}`;
}
let listenerCapRaised = false;
/** Subscribe an SSE stream to a tenant's dashboard changes. Returns an unsubscribe fn. */
export function subscribeToDashboardChanges(tenantId: string, onChange: (payload: string) => void): () => void {
if (!listenerCapRaised) {
emitter.setMaxListeners(0);
listenerCapRaised = true;
}
const channel = dashboardChannel(tenantId);
emitter.on(channel, onChange);
return () => {
emitter.off(channel, onChange);
};
}
/** Publish a dashboard-relevant change so connected clients receive a fresh snapshot. */
export function publishDashboardChange(input: { tenantId: string; source: DashboardChangeSource }): void {
const payload: DashboardChange = { source: input.source, at: new Date().toISOString() };
emitter.emit(dashboardChannel(input.tenantId), JSON.stringify(payload));
}