Files

1096 lines
46 KiB
TypeScript

import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { deriveSeatType, featureKeys, SEAT_TYPES, type SeatType } from "@hivegrid/entitlements";
import {
buildDashboardPageData,
runtimeActivitySummaryKey,
type DashboardPageData,
type DashboardRoleKey,
type DashboardRoleLayoutDefinitionVM,
type DashboardChartPointVM,
type DashboardSeriesPointVM,
type DashboardSeriesVM,
type DashboardSourceSnapshotVM,
type DashboardWidgetDefinitionVM,
} from "@hivegrid/view-models";
import type { Params } from "react-router";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { getTranslations } from "~/locale/i18next.server";
import {
filterAggregateReadablePipelineIdsWithTx,
projectReadScopeWhere,
} from "~/utils/integrations/projects/projectService.server";
export const DASHBOARD_MODULE_KEY = featureKeys.dashboard;
export const DASHBOARD_READ_PERMISSION = "dashboard.read";
export const DASHBOARD_CUSTOMIZE_PERMISSION = "dashboard.customize";
export const LEGACY_DASHBOARD_PERMISSION = "app.dashboard.view";
// Pure VM types/builders live in @hivegrid/view-models (R-P11b, AD-28); this
// module keeps the server-only parts: catalog/layout config, permission checks,
// RLS reads, and seeding. Legacy aliases keep existing consumers stable.
export type DashboardWidgetDefinition = DashboardWidgetDefinitionVM;
export type DashboardRoleLayoutDefinition = DashboardRoleLayoutDefinitionVM;
export type DashboardVM = DashboardPageData;
export type { DashboardRoleKey, DashboardPageData };
export type { DashboardWidgetVM, DashboardRoleVM, DashboardWidgetDomain, DashboardWidgetKind } from "@hivegrid/view-models";
export interface DashboardContext {
readonly locale: string;
readonly tenantId: string;
readonly tenantSlug: string;
readonly userId: string;
readonly permissions: readonly string[];
readonly roleIds: readonly string[];
readonly groupIds: readonly string[];
/** Membership row id — telephony binds calls to the TenantUser, not the User. */
readonly tenantUserId: string | null;
/** Effective seat (Fundament C): `field` = on-site work, `office` = back-office desk. */
readonly seatType: SeatType;
readonly canCustomize: boolean;
}
const widgetCatalog = Object.freeze([
{
key: "sales.kpis",
domain: "sales",
kind: "kpi",
titleKey: "app.dashboard.widgets.salesKpis.title",
descriptionKey: "app.dashboard.widgets.salesKpis.description",
requiredAnyPermission: ["projects.read_all", "deals.read_aggregates"],
defaultPeriod: "30d",
},
{
key: "sales.order_intake",
domain: "sales",
kind: "trend",
titleKey: "app.dashboard.widgets.orderIntake.title",
descriptionKey: "app.dashboard.widgets.orderIntake.description",
requiredAnyPermission: ["deals.read_aggregates", "deals.read_volume_all"],
defaultPeriod: "quarter",
},
{
key: "sales.forecast",
domain: "sales",
kind: "trend",
titleKey: "app.dashboard.widgets.salesForecast.title",
descriptionKey: "app.dashboard.widgets.salesForecast.description",
requiredAnyPermission: ["deals.read_aggregates", "deals.read_volume_all"],
defaultPeriod: "quarter",
},
{
key: "sales.win_rate",
domain: "sales",
kind: "chart",
titleKey: "app.dashboard.widgets.winRate.title",
descriptionKey: "app.dashboard.widgets.winRate.description",
requiredAnyPermission: ["projects.read_all", "deals.read_aggregates"],
defaultPeriod: "quarter",
},
{
key: "finance.receivables",
domain: "finance",
kind: "chart",
titleKey: "app.dashboard.widgets.receivables.title",
descriptionKey: "app.dashboard.widgets.receivables.description",
requiredAnyPermission: ["deals.read_aggregates", "deals.read_volume_all"],
defaultPeriod: "30d",
},
{
key: "finance.days_to_payment",
domain: "finance",
kind: "kpi",
titleKey: "app.dashboard.widgets.daysToPayment.title",
descriptionKey: "app.dashboard.widgets.daysToPayment.description",
requiredAnyPermission: ["deals.read_aggregates", "deals.read_volume_all"],
defaultPeriod: "quarter",
},
{
key: "projects.kpis",
domain: "projects",
kind: "kpi",
titleKey: "app.dashboard.widgets.projectKpis.title",
descriptionKey: "app.dashboard.widgets.projectKpis.description",
requiredAnyPermission: ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"],
defaultPeriod: "30d",
},
{
key: "projects.stage_distribution",
domain: "projects",
kind: "chart",
titleKey: "app.dashboard.widgets.stageDistribution.title",
descriptionKey: "app.dashboard.widgets.stageDistribution.description",
requiredAnyPermission: ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"],
defaultPeriod: "30d",
},
{
key: "projects.open_defects",
domain: "projects",
kind: "kpi",
titleKey: "app.dashboard.widgets.openDefects.title",
descriptionKey: "app.dashboard.widgets.openDefects.description",
requiredAnyPermission: ["acceptance.read", "acceptance.admin"],
defaultPeriod: "30d",
},
{
key: "projects.my_active",
domain: "projects",
kind: "list",
titleKey: "app.dashboard.widgets.myProjects.title",
descriptionKey: "app.dashboard.widgets.myProjects.description",
requiredAnyPermission: ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"],
defaultPeriod: "today",
},
{
key: "tasks.my_open",
domain: "tasks",
kind: "list",
titleKey: "app.dashboard.widgets.myTasks.title",
descriptionKey: "app.dashboard.widgets.myTasks.description",
requiredAnyPermission: ["tasks.read_all", "tasks.read_own"],
defaultPeriod: "today",
},
{
key: "hr.requests_pending",
domain: "hr",
kind: "kpi",
titleKey: "app.dashboard.widgets.hrRequests.title",
descriptionKey: "app.dashboard.widgets.hrRequests.description",
requiredAnyPermission: ["hr.read_all", "hr.leave.approve"],
defaultPeriod: "30d",
},
{
key: "activity.recent",
domain: "activity",
kind: "list",
titleKey: "app.dashboard.widgets.activity.title",
descriptionKey: "app.dashboard.widgets.activity.description",
requiredAnyPermission: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
defaultPeriod: "7d",
},
{
key: "comms.calls_today",
domain: "comms",
kind: "kpi",
titleKey: "app.dashboard.widgets.callsToday.title",
descriptionKey: "app.dashboard.widgets.callsToday.description",
requiredAnyPermission: ["telephony.read_own", "telephony.read_all", "telephony.manage"],
defaultPeriod: "today",
},
{
key: "schedule.my_today",
domain: "schedule",
kind: "list",
titleKey: "app.dashboard.widgets.scheduleToday.title",
descriptionKey: "app.dashboard.widgets.scheduleToday.description",
requiredAnyPermission: ["calendar.connect_own", "bookings.read_own", "plantafel.read_own", "plantafel.read_all"],
defaultPeriod: "today",
},
] as const satisfies readonly DashboardWidgetDefinition[]);
const roleLayouts = Object.freeze([
{
role: "gf",
nameKey: "app.dashboard.roles.gf.name",
descriptionKey: "app.dashboard.roles.gf.description",
mobileFirst: false,
widgets: [
// Order intake leads: the trade literature (HWK Dortmund) treats a falling
// order book as the first stage a workshop slides through, so it takes the
// top-left slot the eye reaches first.
{ key: "sales.order_intake", position: { x: 0, y: 0 }, size: { w: 8, h: 3 } },
{ key: "sales.kpis", position: { x: 8, y: 0 }, size: { w: 4, h: 2 } },
{ key: "sales.win_rate", position: { x: 8, y: 2 }, size: { w: 4, h: 3 } },
// Liquidity follows the order book: "Liquidität geht vor Rentabilität"
// (HWK Dortmund), and unpaid invoices are what an owner can act on today.
{ key: "finance.receivables", position: { x: 0, y: 3 }, size: { w: 8, h: 3 } },
{ key: "finance.days_to_payment", position: { x: 8, y: 3 }, size: { w: 4, h: 2 } },
{ key: "sales.forecast", position: { x: 0, y: 6 }, size: { w: 4, h: 2 } },
{ key: "projects.kpis", position: { x: 4, y: 6 }, size: { w: 4, h: 2 } },
{ key: "projects.open_defects", position: { x: 8, y: 6 }, size: { w: 4, h: 2 } },
{ key: "hr.requests_pending", position: { x: 0, y: 8 }, size: { w: 4, h: 2 } },
// The tall chart and the activity feed close the dashboard so the compact
// KPI tiles stay above the fold.
{ key: "projects.stage_distribution", position: { x: 0, y: 10 }, size: { w: 8, h: 3 } },
{ key: "activity.recent", position: { x: 8, y: 10 }, size: { w: 4, h: 3 } },
],
},
{
role: "office",
nameKey: "app.dashboard.roles.office.name",
descriptionKey: "app.dashboard.roles.office.description",
mobileFirst: false,
widgets: [
{ key: "projects.kpis", position: { x: 0, y: 0 }, size: { w: 4, h: 2 } },
{ key: "tasks.my_open", position: { x: 4, y: 0 }, size: { w: 4, h: 2 } },
{ key: "comms.calls_today", position: { x: 8, y: 0 }, size: { w: 4, h: 2 } },
{ key: "hr.requests_pending", position: { x: 0, y: 2 }, size: { w: 12, h: 2 } },
{ key: "projects.stage_distribution", position: { x: 0, y: 4 }, size: { w: 8, h: 3 } },
{ key: "activity.recent", position: { x: 8, y: 4 }, size: { w: 4, h: 3 } },
],
},
{
role: "monteur",
nameKey: "app.dashboard.roles.monteur.name",
descriptionKey: "app.dashboard.roles.monteur.description",
mobileFirst: true,
widgets: [
{ key: "schedule.my_today", position: { x: 0, y: 0 }, size: { w: 12, h: 2 } },
{ key: "projects.my_active", position: { x: 0, y: 2 }, size: { w: 12, h: 2 } },
{ key: "tasks.my_open", position: { x: 0, y: 4 }, size: { w: 12, h: 2 } },
],
},
] as const satisfies readonly DashboardRoleLayoutDefinition[]);
export function getDashboardWidgetCatalog(): readonly DashboardWidgetDefinition[] {
return widgetCatalog;
}
export function getDefaultDashboardRoleLayouts(): readonly DashboardRoleLayoutDefinition[] {
return roleLayouts;
}
function hasAnyPermission(permissions: readonly string[], requiredAnyPermission: readonly string[]): boolean {
return requiredAnyPermission.some((permission) => permissions.includes(permission));
}
function widgetConfig(widget: DashboardRoleLayoutDefinition["widgets"][number]): Record<string, string | number | boolean> {
return "config" in widget && widget.config ? widget.config : {};
}
function assertDashboardRead(permissions: readonly string[]): void {
if (!hasAnyPermission(permissions, [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION])) {
throw new CatalogError(foundationErrors.notFound, { permission: DASHBOARD_READ_PERMISSION });
}
}
export async function loadDashboardContext({ request, params }: { request: Request; params: Params }): Promise<DashboardContext> {
await requireAuth({ request, params });
const [tenantId, userInfo, { locale }] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request), getTranslations(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: DASHBOARD_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (!hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: DASHBOARD_MODULE_KEY });
}
assertDashboardRead(permissions);
const principals = await withTenantRLS(tenantId, async (tx) => {
const [roleAssignments, groupMemberships, membership] = await Promise.all([
tx.userRole.findMany({
where: { tenantId, userId: userInfo.userId },
select: { roleId: true, role: { select: { seatCategory: true } } },
}),
tx.groupUser.findMany({ where: { userId: userInfo.userId, group: { tenantId } }, select: { groupId: true } }),
tx.tenantUser.findUnique({ where: { tenantId_userId: { tenantId, userId: userInfo.userId } }, select: { id: true, seatType: true } }),
]);
return {
roleIds: roleAssignments.map(({ roleId }) => roleId),
groupIds: groupMemberships.map(({ groupId }) => groupId),
tenantUserId: membership?.id ?? null,
// Same derivation as billing (`getUserEffectiveSeatType`), but read inside the
// dashboard's own RLS transaction instead of a second unscoped round-trip.
seatType: deriveSeatType({
roleSeatCategories: roleAssignments.map(({ role }) => role.seatCategory),
override: membership?.seatType ?? null,
}),
};
});
return {
locale,
tenantId,
tenantSlug: params.tenant ?? tenantId,
userId: userInfo.userId,
permissions,
...principals,
canCustomize: permissions.includes(DASHBOARD_CUSTOMIZE_PERMISSION),
};
}
export async function ensureDefaultDashboards(ctx: Pick<DashboardContext, "tenantId">): Promise<void> {
await withTenantRLS(ctx.tenantId, async (tx) => {
for (const layout of roleLayouts) {
const dashboard = await tx.dashboard.upsert({
where: { tenantId_role_name: { tenantId: ctx.tenantId, role: layout.role, name: layout.nameKey } },
update: {
description: layout.descriptionKey,
isDefaultForRole: true,
isShared: true,
archivedAt: null,
},
create: {
tenantId: ctx.tenantId,
role: layout.role,
name: layout.nameKey,
description: layout.descriptionKey,
isDefaultForRole: true,
isShared: true,
},
});
const layoutRow = await tx.dashboardLayout.findFirst({
where: { tenantId: ctx.tenantId, dashboardId: dashboard.id, userId: null, archivedAt: null },
select: { id: true },
});
const layoutData = { role: layout.role, columns: 12, mobileFirst: layout.mobileFirst };
const widgets = layout.widgets.map((widget) => ({ key: widget.key, position: widget.position, size: widget.size, config: widgetConfig(widget) }));
if (layoutRow) {
await tx.dashboardLayout.update({
where: { id: layoutRow.id },
data: { widgets, layoutData, archivedAt: null },
});
} else {
await tx.dashboardLayout.create({
data: { tenantId: ctx.tenantId, dashboardId: dashboard.id, userId: null, widgets, layoutData },
});
}
const existingInstances = await tx.widgetInstance.findMany({
where: { tenantId: ctx.tenantId, dashboardId: dashboard.id, archivedAt: null },
select: { id: true, widgetCatalogKey: true },
});
const instanceByKey = new Map(existingInstances.map((instance) => [instance.widgetCatalogKey, instance.id]));
for (const widget of layout.widgets) {
const existingId = instanceByKey.get(widget.key);
const data = {
config: widgetConfig(widget),
position: widget.position,
size: widget.size,
archivedAt: null,
};
if (existingId) {
await tx.widgetInstance.update({ where: { id: existingId }, data });
} else {
await tx.widgetInstance.create({
data: {
tenantId: ctx.tenantId,
dashboardId: dashboard.id,
widgetCatalogKey: widget.key,
...data,
},
});
}
}
}
});
}
export async function loadDashboardVM({ request, params }: { request: Request; params: Params }): Promise<DashboardVM> {
const ctx = await loadDashboardContext({ request, params });
const snapshot = await loadDashboardSourceSnapshot(ctx);
return buildDashboardVMFromSnapshot({ ctx, snapshot, activeRole: resolveDashboardRole(ctx) });
}
export async function loadDashboardStreamSnapshot({ request, params }: { request: Request; params: Params }): Promise<DashboardVM> {
const ctx = await loadDashboardContext({ request, params });
const snapshot = await loadDashboardSourceSnapshot(ctx);
return buildDashboardVMFromSnapshot({ ctx, snapshot, activeRole: resolveDashboardRole(ctx) });
}
/**
* Authorizes a dashboard SSE connection once and returns a reusable snapshot
* loader bound to that context, so the stream can re-send fresh permission-gated
* snapshots on live change events without re-running auth per event.
*/
export async function openDashboardStreamSession({ request, params }: { request: Request; params: Params }): Promise<{
tenantId: string;
loadSnapshot: () => Promise<DashboardVM>;
}> {
const ctx = await loadDashboardContext({ request, params });
const activeRole = resolveDashboardRole(ctx);
return {
tenantId: ctx.tenantId,
loadSnapshot: async () => {
const snapshot = await loadDashboardSourceSnapshot(ctx);
return buildDashboardVMFromSnapshot({ ctx, snapshot, activeRole });
},
};
}
function buildDashboardVMFromSnapshot({
ctx,
snapshot,
activeRole,
}: {
ctx: DashboardContext;
snapshot: DashboardSourceSnapshotVM;
activeRole: DashboardRoleKey;
}): DashboardVM {
const tenantHref = (path: string) => appPath({ tenantSlug: ctx.tenantSlug, path, mode: "host-aware" });
return buildDashboardPageData({
locale: ctx.locale,
catalog: widgetCatalog,
layouts: roleLayouts,
snapshot,
permissions: ctx.permissions,
activeRole,
streamUrl: tenantHref("dashboard/stream"),
canCustomize: ctx.canCustomize,
// Click-through targets for the single-metric StatsCard tiles; the target
// routes gate themselves. projects.open_defects has no global view yet.
widgetHrefs: {
"sales.forecast": tenantHref("projects/boards"),
"hr.requests_pending": tenantHref("hr/requests"),
"comms.calls_today": tenantHref("calls"),
},
});
}
type DashboardActivityRow = {
id: string;
actorUserId: string | null;
summaryText: string;
subjectType: string;
subjectId: string;
createdAt: Date;
};
export const DASHBOARD_ACTIVITY_MAX_CANDIDATES = 500;
const DASHBOARD_ACTIVITY_BATCH_SIZE = 100;
async function loadRecentVisibleActivityWithTx(
tx: TenantRlsClient,
ctx: DashboardContext,
projectWhere: Record<string, unknown> | null,
): Promise<DashboardActivityRow[]> {
const visible: DashboardActivityRow[] = [];
let cursor: string | undefined;
let scannedCandidates = 0;
while (visible.length < 5 && scannedCandidates < DASHBOARD_ACTIVITY_MAX_CANDIDATES) {
const take = Math.min(DASHBOARD_ACTIVITY_BATCH_SIZE, DASHBOARD_ACTIVITY_MAX_CANDIDATES - scannedCandidates);
const rows = (await tx.activity.findMany({
where: {
tenantId: ctx.tenantId,
OR: [
{ actorUserId: ctx.userId },
...(projectWhere ? [{ subjectType: { in: ["project", "projekt"] } }] : []),
],
},
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
take,
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
select: { id: true, actorUserId: true, summaryText: true, subjectType: true, subjectId: true, createdAt: true },
})) as DashboardActivityRow[];
if (rows.length === 0) break;
scannedCandidates += rows.length;
const candidateProjectIds = [
...new Set(rows.filter((row) => row.subjectType === "project" || row.subjectType === "projekt").map((row) => row.subjectId)),
];
const visibleProjectIds =
projectWhere && candidateProjectIds.length > 0
? new Set(
(
await tx.projekt.findMany({
where: { AND: [projectWhere, { id: { in: candidateProjectIds } }] },
select: { id: true },
})
).map(({ id }) => id),
)
: new Set<string>();
for (const row of rows) {
if (row.actorUserId === ctx.userId || visibleProjectIds.has(row.subjectId)) {
visible.push(row);
if (visible.length === 5) break;
}
}
if (rows.length < take) break;
cursor = rows.at(-1)?.id;
if (!cursor) break;
}
return visible;
}
async function loadDashboardSourceSnapshot(ctx: DashboardContext): Promise<DashboardSourceSnapshotVM> {
const now = new Date();
const todayStart = new Date(now);
todayStart.setHours(0, 0, 0, 0);
const todayEnd = new Date(todayStart);
todayEnd.setDate(todayEnd.getDate() + 1);
const dueSoon = new Date(now);
dueSoon.setDate(dueSoon.getDate() + 14);
// Series window plus one year of comparison months.
const orderIntakeWindowStart = new Date(now.getFullYear(), now.getMonth() - (DASHBOARD_ORDER_INTAKE_MONTHS - 1) - 12, 1);
// Days-to-payment looks back a year so a single slow customer cannot dominate.
const paymentWindowStart = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
// Win rate looks back the same twelve months as the order-intake headline.
const decisionWindowStart = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
const generatedAt = now.toISOString();
return withTenantRLS(ctx.tenantId, async (tx) => {
const canReadProjects = hasAnyPermission(ctx.permissions, ["projects.read_all", "projects.read_own", "projects.read_own_member", "projects.read_own_pl"]);
const canReadTasks = hasAnyPermission(ctx.permissions, ["tasks.read_all", "tasks.read_own"]);
const canReadHr = hasAnyPermission(ctx.permissions, ["hr.read_all", "hr.leave.approve"]);
const canReadCalendar = hasAnyPermission(ctx.permissions, ["calendar.connect_own", "calendar.admin"]);
const canReadBookings = hasAnyPermission(ctx.permissions, ["bookings.read_all", "bookings.read_own", "bookings.write", "bookings.admin"]);
const canReadDefects = hasAnyPermission(ctx.permissions, ["acceptance.read", "acceptance.admin"]);
const callScope = telephonyCallScope(ctx);
const projectWhere = {
tenantId: ctx.tenantId,
archivedAt: null,
...projectReadScopeWhere(ctx.tenantId, ctx),
};
const openProjectWhere = {
...projectWhere,
stage: { is: { tenantId: ctx.tenantId, stageKind: "offen" as const, archivedAt: null } },
};
const forecastPipelineIds =
canReadProjects && hasAnyPermission(ctx.permissions, ["deals.read_aggregates", "deals.read_volume_all"])
? await tx.projekt.findMany({
where: projectWhere,
distinct: ["pipelineId"],
select: { pipelineId: true },
})
: [];
const canReadForecast = hasAnyPermission(ctx.permissions, ["deals.read_aggregates", "deals.read_volume_all"]);
// Invoices carry no Prisma relation to the project, so they cannot be filtered
// through the project visibility scope. The tile is therefore reserved for
// readers whose project visibility is tenant-wide anyway — the same reasoning
// the forecast cache uses below.
const canReadReceivables = canReadForecast && ctx.permissions.includes("projects.read_all");
const aggregateReadablePipelineIds =
canReadForecast
? await filterAggregateReadablePipelineIdsWithTx(tx, {
tenantId: ctx.tenantId,
pipelineIds: forecastPipelineIds.map(({ pipelineId }) => pipelineId),
ctx,
backstopPermissions: ["deals.read_aggregates", "deals.read_volume_all"],
})
: [];
// R-P11b DoD 3: prefer the R-P8b pipeline aggregate cache for the forecast
// widget. The persisted snapshot is tenant-wide, so it may only serve
// readers whose project visibility is tenant-wide too; own-scoped readers
// and pipelines without a snapshot keep the live scoped computation below.
// Cache rows exclude demo data by construction (R-P8b rebuild).
const forecastCacheEligible = canReadForecast && ctx.permissions.includes("projects.read_all");
const pipelineForecastSnapshots =
forecastCacheEligible && aggregateReadablePipelineIds.length > 0
? await tx.pipelineAggregateSnapshot.findMany({
where: { tenantId: ctx.tenantId, pipelineId: { in: aggregateReadablePipelineIds }, scopeKey: "pipeline" },
select: { pipelineId: true, weightedForecast: true },
})
: [];
const cachedForecastByPipeline = new Map(pipelineForecastSnapshots.map((snapshot) => [snapshot.pipelineId, numeric(snapshot.weightedForecast)]));
const liveForecastPipelineIds = aggregateReadablePipelineIds.filter((pipelineId) => !cachedForecastByPipeline.has(pipelineId));
const [potentialForecastTotals, orderFallbackForecastTotals] =
liveForecastPipelineIds.length > 0
? await Promise.all([
tx.projekt.groupBy({
by: ["stageId"],
where: {
...projectWhere,
pipelineId: { in: liveForecastPipelineIds },
},
_sum: { potenziellerAuftragswert: true },
}),
tx.projekt.groupBy({
by: ["stageId"],
where: {
...projectWhere,
pipelineId: { in: liveForecastPipelineIds },
potenziellerAuftragswert: null,
},
_sum: { auftragsvolumen: true },
}),
])
: [[], []];
const forecastStageIds = [
...new Set([...potentialForecastTotals, ...orderFallbackForecastTotals].map(({ stageId }) => stageId)),
];
const forecastStages =
forecastStageIds.length > 0
? await tx.pipelineStage.findMany({
where: { tenantId: ctx.tenantId, id: { in: forecastStageIds } },
select: { id: true, winProbability: true },
})
: [];
const winProbabilityByStage = new Map(forecastStages.map((stage) => [stage.id, stage.winProbability]));
const taskReadScope = ctx.permissions.includes("tasks.read_all")
? {}
: {
OR: [
{ assignedToUserId: ctx.userId },
{ createdByUserId: ctx.userId },
{ watchers: { some: { tenantId: ctx.tenantId, userId: ctx.userId } } },
...(ctx.groupIds.length > 0 ? [{ assignedToGroupId: { in: [...ctx.groupIds] } }] : []),
],
};
const [
openProjects,
wonProjects,
dueSoonProjects,
myProjects,
myOpenTasks,
dueTodayTasks,
taskItems,
pendingHrRequests,
openDefects,
stageDistributionCounts,
recentActivity,
callsToday,
wonProjectValueRows,
earliestWonProject,
recentlyWonCount,
recentlyLostCount,
openInvoices,
recentlyPaidInvoices,
calendarEvents,
appointments,
] = await Promise.all([
canReadProjects ? tx.projekt.count({ where: openProjectWhere }) : Promise.resolve(0),
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, wonAt: { not: null } } }) : Promise.resolve(0),
canReadProjects ? tx.projekt.count({ where: { ...openProjectWhere, deadline: { gte: todayStart, lt: dueSoon } } }) : Promise.resolve(0),
canReadProjects
? tx.projekt.findMany({
where: openProjectWhere,
orderBy: { updatedAt: "desc" },
take: 4,
select: { id: true, projektname: true, projektNummer: true, deadline: true },
})
: Promise.resolve([]),
canReadTasks
? tx.task.count({
where: { tenantId: ctx.tenantId, archivedAt: null, status: { notIn: ["done", "cancelled"] }, ...taskReadScope },
})
: Promise.resolve(0),
canReadTasks
? tx.task.count({
where: {
tenantId: ctx.tenantId,
archivedAt: null,
status: { notIn: ["done", "cancelled"] },
deadline: { gte: todayStart, lt: todayEnd },
...taskReadScope,
},
})
: Promise.resolve(0),
canReadTasks
? tx.task.findMany({
where: { tenantId: ctx.tenantId, archivedAt: null, status: { notIn: ["done", "cancelled"] }, ...taskReadScope },
orderBy: [{ deadline: "asc" }, { updatedAt: "desc" }],
take: 4,
select: { id: true, title: true, deadline: true, status: true },
})
: Promise.resolve([]),
canReadHr
? tx.hrRequest.count({ where: { tenantId: ctx.tenantId, archivedAt: null, status: { in: ["submitted", "clarification"] } } })
: Promise.resolve(0),
canReadDefects && canReadProjects
? tx.projektChecklistItem.count({
where: {
tenantId: ctx.tenantId,
status: "offen",
checklist: {
tenantId: ctx.tenantId,
typ: "maengel",
archivedAt: null,
projekt: { is: projectWhere },
},
},
})
: Promise.resolve(0),
canReadProjects
? tx.projekt.groupBy({
by: ["stageId"],
where: openProjectWhere,
_count: { _all: true },
})
: Promise.resolve([]),
loadRecentVisibleActivityWithTx(tx, ctx, canReadProjects ? projectWhere : null),
// Counted off the telephony sessions themselves: the activity rows the
// telephony worker writes are `call_inbound|call_outbound|call_missed`
// with `actorKind: "system"` and no actor, so an activity-based count
// filtered by actor could only ever return zero.
callScope
? tx.telephonyCallSession.count({
where: { tenantId: ctx.tenantId, archivedAt: null, startedAt: { gte: todayStart, lt: todayEnd }, ...callScope },
})
: Promise.resolve(0),
// Won order value for the series window plus the 12 comparison months
// before it. Money, so it follows the aggregate permissions rather than
// plain project read access.
canReadProjects && canReadForecast
? tx.projekt.findMany({
where: { ...projectWhere, wonAt: { gte: orderIntakeWindowStart } },
select: { wonAt: true, auftragsvolumen: true, potenziellerAuftragswert: true },
})
: Promise.resolve([]),
canReadProjects && canReadForecast
? tx.projekt.aggregate({ where: { ...projectWhere, wonAt: { not: null } }, _min: { wonAt: true } })
: Promise.resolve({ _min: { wonAt: null } }),
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, wonAt: { gte: decisionWindowStart } } }) : Promise.resolve(0),
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, lostAt: { gte: decisionWindowStart } } }) : Promise.resolve(0),
canReadReceivables
? tx.rechnung.findMany({
where: { tenantId: ctx.tenantId, archivedAt: null, status: "gestellt" },
select: { betrag: true, faelligAm: true },
})
: Promise.resolve([]),
canReadReceivables
? tx.rechnung.findMany({
where: { tenantId: ctx.tenantId, archivedAt: null, status: "bezahlt", bezahltAm: { gte: paymentWindowStart } },
select: { datum: true, bezahltAm: true },
})
: Promise.resolve([]),
canReadCalendar
? tx.calendarEvent.findMany({
where: { tenantId: ctx.tenantId, userId: ctx.userId, archivedAt: null, startsAt: { gte: todayStart, lt: todayEnd } },
orderBy: { startsAt: "asc" },
take: 5,
select: { id: true, title: true, startsAt: true, endsAt: true },
})
: Promise.resolve([]),
canReadBookings
? tx.appointment.findMany({
where: { tenantId: ctx.tenantId, providerUserId: ctx.userId, status: "scheduled", startAt: { gte: todayStart, lt: todayEnd } },
orderBy: { startAt: "asc" },
take: 5,
select: { id: true, startAt: true, endAt: true, notesInternal: true },
})
: Promise.resolve([]),
]);
const potentialForecastValue = potentialForecastTotals.reduce(
(sum, total) => sum + numeric(total._sum.potenziellerAuftragswert) * ((winProbabilityByStage.get(total.stageId) ?? 0) / 100),
0
);
const liveForecastValue = orderFallbackForecastTotals.reduce(
(sum, total) => sum + numeric(total._sum.auftragsvolumen) * ((winProbabilityByStage.get(total.stageId) ?? 0) / 100),
potentialForecastValue
);
const cachedForecastValue = [...cachedForecastByPipeline.values()].reduce((sum, value) => sum + value, 0);
const forecastValue = liveForecastValue + cachedForecastValue;
const winRate = buildWinRate({ won: recentlyWonCount, lost: recentlyLostCount });
const receivables = buildReceivablesAging({
invoices: openInvoices.map((invoice) => ({ amount: numeric(invoice.betrag), dueAt: invoice.faelligAm })),
now,
});
const daysToPayment = averageDaysToPayment(
recentlyPaidInvoices.map((invoice) => ({ issuedAt: invoice.datum, paidAt: invoice.bezahltAm })),
);
const orderIntake = buildOrderIntakeSeries({
rows: wonProjectValueRows.map((row) => ({
wonAt: row.wonAt,
// The order volume is the signed value; before it is filled in, the
// potential value is the best available stand-in for the same deal.
value: numeric(row.auftragsvolumen ?? row.potenziellerAuftragswert),
})),
now,
earliestWonAt: earliestWonProject._min.wonAt ?? null,
});
const stageDistributionStageIds = stageDistributionCounts.map(({ stageId }) => stageId);
const stageDistributionStages =
stageDistributionStageIds.length > 0
? await tx.pipelineStage.findMany({
where: { tenantId: ctx.tenantId, id: { in: stageDistributionStageIds }, archivedAt: null },
orderBy: [{ pipeline: { position: "asc" } }, { position: "asc" }],
select: { id: true, name: true, color: true, pipeline: { select: { name: true } } },
})
: [];
const stageCountById = new Map(stageDistributionCounts.map((row) => [row.stageId, row._count._all]));
const stageDistribution = stageDistributionStages.map((stage) => ({
id: stage.id,
label: `${stage.pipeline.name} · ${stage.name}`,
value: stageCountById.get(stage.id) ?? 0,
color: normalizeChartColor(stage.color),
}));
const isProjectSubject = (row: DashboardActivityRow) => row.subjectType === "project" || row.subjectType === "projekt";
const activityProjectIds = [...new Set(recentActivity.filter(isProjectSubject).map((row) => row.subjectId))];
const activityProjectNames =
canReadProjects && activityProjectIds.length > 0
? new Map(
(
await tx.projekt.findMany({
// Name lookup keeps the permission scope but not the archived filter:
// activity rows may reference archived projects and should still name them.
where: { AND: [{ tenantId: ctx.tenantId, ...projectReadScopeWhere(ctx.tenantId, ctx) }, { id: { in: activityProjectIds } }] },
select: { id: true, projektname: true },
})
).map((project) => [project.id, project.projektname])
)
: new Map<string, string>();
return {
generatedAt,
sales: {
openProjects,
wonProjects,
forecastValue,
winRate,
orderIntake: {
currentMonth: orderIntake.currentMonth,
trailingTwelveMonths: orderIntake.trailingTwelveMonths,
series: orderIntake.series,
},
},
projects: {
activeProjects: openProjects,
dueSoon: dueSoonProjects,
openDefects,
stageDistribution,
myProjects: myProjects.map((project) => ({
id: project.id,
label: project.projektname,
href: appPath({ tenantSlug: ctx.tenantSlug, path: `projects/${project.id}`, mode: "host-aware" }),
meta: project.projektNummer || formatDate(project.deadline),
})),
},
tasks: {
myOpen: myOpenTasks,
dueToday: dueTodayTasks,
items: taskItems.map((task) => ({
id: task.id,
label: task.title,
href: appPath({ tenantSlug: ctx.tenantSlug, path: `tasks`, mode: "host-aware" }),
meta: task.deadline ? formatDate(task.deadline) : task.status,
})),
},
hr: { pendingRequests: pendingHrRequests },
activity: {
items: recentActivity.map((activity) => {
const projectName = isProjectSubject(activity) ? activityProjectNames.get(activity.subjectId) : undefined;
const labelKey = runtimeActivitySummaryKey(activity.summaryText);
return {
id: activity.id,
...(labelKey ? { labelKey } : { label: activity.summaryText }),
...(projectName ? { tooltip: labelKey ? projectName : `${activity.summaryText} — ${projectName}` } : {}),
// Project-subject rows survived the visibility filter above, so linking is safe.
...(canReadProjects && isProjectSubject(activity)
? { href: appPath({ tenantSlug: ctx.tenantSlug, path: `projects/${activity.subjectId}`, mode: "host-aware" }) }
: {}),
metaDateIso: activity.createdAt.toISOString(),
};
}),
},
comms: { callsToday },
finance: {
openReceivables: receivables.openReceivables,
overdueReceivables: receivables.overdueReceivables,
agingBuckets: receivables.agingBuckets,
averageDaysToPayment: daysToPayment,
},
schedule: {
today: [
...calendarEvents.map((event) => ({
id: event.id,
...(event.title ? { label: event.title } : { labelKey: "app.dashboard.schedule.untitled" }),
meta: formatTimeRange(event.startsAt, event.endsAt),
})),
...appointments.map((appointment) => ({
id: appointment.id,
...(appointment.notesInternal ? { label: appointment.notesInternal } : { labelKey: "app.dashboard.schedule.appointment" }),
meta: formatTimeRange(appointment.startAt, appointment.endAt),
})),
],
},
};
});
}
/** How many months the order-intake series shows, current month included. */
export const DASHBOARD_ORDER_INTAKE_MONTHS = 13;
/**
* Won share of the projects a workspace decided in the trailing window. Counted
* on decided projects only: open projects are not failures, and folding them in
* would drag the rate down every time the pipeline grows.
*/
export function buildWinRate(input: { readonly won: number; readonly lost: number }): {
won: number;
lost: number;
rate: number | null;
outcomes: DashboardChartPointVM[];
} {
const decided = input.won + input.lost;
return {
won: input.won,
lost: input.lost,
rate: decided === 0 ? null : input.won / decided,
outcomes: [
{ id: "won", labelKey: "app.dashboard.winRate.won", value: input.won, color: "#334155" },
{ id: "lost", labelKey: "app.dashboard.winRate.lost", value: input.lost, color: "#cbd5e1" },
],
};
}
/**
* Aging buckets for issued-but-unpaid invoices, in the order a reader walks them:
* not yet due first, then rising overdue age. Greys carry the harmless buckets so
* the two that need action are the only saturated marks on the chart; the labels
* carry the meaning on their own, so colour is never the sole encoding (WCAG 1.4.1).
*/
const RECEIVABLE_AGING_BUCKETS = [
{ id: "not_due", labelKey: "app.dashboard.receivables.notDue", maxDaysOverdue: 0, color: "#94a3b8" },
{ id: "overdue_1_30", labelKey: "app.dashboard.receivables.overdue1To30", maxDaysOverdue: 30, color: "#64748b" },
{ id: "overdue_31_60", labelKey: "app.dashboard.receivables.overdue31To60", maxDaysOverdue: 60, color: "#475569" },
{ id: "overdue_61_90", labelKey: "app.dashboard.receivables.overdue61To90", maxDaysOverdue: 90, color: "#d97706" },
{ id: "overdue_90_plus", labelKey: "app.dashboard.receivables.overdue90Plus", maxDaysOverdue: Number.POSITIVE_INFINITY, color: "#b91c1c" },
] as const;
const MS_PER_DAY = 24 * 60 * 60 * 1000;
function daysBetween(from: Date, to: Date): number {
return Math.floor((to.getTime() - from.getTime()) / MS_PER_DAY);
}
/**
* Splits open invoice value across the aging buckets. An invoice without a due
* date counts as not yet due rather than as overdue — dunning someone because a
* date was never entered is worse than waiting.
*/
export function buildReceivablesAging(input: {
readonly invoices: readonly { readonly amount: number; readonly dueAt: Date | null }[];
readonly now: Date;
}): { openReceivables: number; overdueReceivables: number; agingBuckets: DashboardChartPointVM[] } {
const totals = new Map<string, number>(RECEIVABLE_AGING_BUCKETS.map((bucket) => [bucket.id, 0]));
let openReceivables = 0;
let overdueReceivables = 0;
for (const invoice of input.invoices) {
openReceivables += invoice.amount;
const daysOverdue = invoice.dueAt ? daysBetween(invoice.dueAt, input.now) : 0;
if (daysOverdue > 0) overdueReceivables += invoice.amount;
const bucket = RECEIVABLE_AGING_BUCKETS.find((candidate) => daysOverdue <= candidate.maxDaysOverdue) ?? RECEIVABLE_AGING_BUCKETS[0];
totals.set(bucket.id, (totals.get(bucket.id) ?? 0) + invoice.amount);
}
return {
openReceivables,
overdueReceivables,
agingBuckets: RECEIVABLE_AGING_BUCKETS.map((bucket) => ({
id: bucket.id,
labelKey: bucket.labelKey,
value: totals.get(bucket.id) ?? 0,
color: bucket.color,
})),
};
}
/**
* Mean days from invoice date to payment. Only invoices that carry a payment date
* count: rows paid before `bezahltAm` existed would otherwise have to be dated by
* `updatedAt`, which any later edit moves. Null means "not measurable yet".
*/
export function averageDaysToPayment(rows: readonly { readonly issuedAt: Date; readonly paidAt: Date | null }[]): number | null {
const durations = rows.filter((row) => row.paidAt !== null).map((row) => Math.max(0, daysBetween(row.issuedAt, row.paidAt as Date)));
if (durations.length === 0) return null;
return Math.round(durations.reduce((sum, days) => sum + days, 0) / durations.length);
}
function monthKey(date: Date): string {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
/**
* Buckets won order value into the trailing {@link DASHBOARD_ORDER_INTAKE_MONTHS}
* months, time running left to right, with the same month a year earlier as the
* comparison value.
*
* A comparison is only attached where the workspace actually has history that far
* back (`earliestWonAt`); otherwise the point carries none, because a rendered 0
* would read as "we won nothing that month" instead of "we were not live yet".
*/
export function buildOrderIntakeSeries(input: {
readonly rows: readonly { readonly wonAt: Date | null; readonly value: number }[];
readonly now: Date;
readonly earliestWonAt: Date | null;
}): { series: DashboardSeriesVM; currentMonth: number; trailingTwelveMonths: number } {
const totals = new Map<string, number>();
for (const row of input.rows) {
if (!row.wonAt) continue;
const key = monthKey(row.wonAt);
totals.set(key, (totals.get(key) ?? 0) + row.value);
}
const points: DashboardSeriesPointVM[] = [];
let trailingTwelveMonths = 0;
for (let offset = DASHBOARD_ORDER_INTAKE_MONTHS - 1; offset >= 0; offset -= 1) {
const month = new Date(input.now.getFullYear(), input.now.getMonth() - offset, 1);
const key = monthKey(month);
const value = totals.get(key) ?? 0;
if (offset < 12) trailingTwelveMonths += value;
const comparisonMonth = new Date(month.getFullYear() - 1, month.getMonth(), 1);
const comparisonMonthEnd = new Date(comparisonMonth.getFullYear(), comparisonMonth.getMonth() + 1, 1);
const hasHistory = input.earliestWonAt !== null && input.earliestWonAt < comparisonMonthEnd;
points.push({
id: key,
value,
...(hasHistory ? { comparisonValue: totals.get(monthKey(comparisonMonth)) ?? 0 } : {}),
});
}
return {
series: { points, valueFormat: "currency", hasComparison: points.some((point) => point.comparisonValue !== undefined) },
currentMonth: totals.get(monthKey(input.now)) ?? 0,
trailingTwelveMonths,
};
}
/**
* Which calls the member may count, mirroring `telephonyAccess.server`:
* `manage`/`read_all` see the whole workspace, `read_own` only the calls bound to
* their own membership, and anyone else counts nothing (`null`).
*/
export function telephonyCallScope(
ctx: Pick<DashboardContext, "permissions" | "tenantUserId">,
): { tenantUserId?: string } | null {
if (hasAnyPermission(ctx.permissions, ["telephony.read_all", "telephony.manage"])) return {};
if (ctx.permissions.includes("telephony.read_own") && ctx.tenantUserId) return { tenantUserId: ctx.tenantUserId };
return null;
}
/**
* Tenant-wide analytics permissions. Only the global `Admin`/`SuperUser` roles carry
* them (`packages/db/src/permissions-seed.server.ts`), so they mark the owner-level
* reader — unlike `projects.read_all`, which the Vertrieb and Innendienst template
* roles hold as well and which therefore cannot separate GF from Büro.
*/
const DASHBOARD_OWNER_PERMISSIONS = ["deals.read_aggregates", "deals.read_volume_all"] as const;
/**
* Which of the three fixed layouts a member sees. Seat first, then permissions:
* a field seat is on-site work and always gets the Monteur layout, office seats
* split into the owner view (tenant-wide analytics) and the back-office view.
*
* Deriving from the seat fixes the previous permission-only heuristic, under which
* the `Monteur` template role — holding neither `plantafel.read_own` nor
* `calendar.connect_own` — silently landed on the office layout.
*/
export function resolveDashboardRole(input: { readonly seatType: SeatType; readonly permissions: readonly string[] }): DashboardRoleKey {
if (input.seatType === SEAT_TYPES.field) return "monteur";
return hasAnyPermission(input.permissions, DASHBOARD_OWNER_PERMISSIONS) ? "gf" : "office";
}
function numeric(value: unknown): number {
if (typeof value === "number") return value;
if (typeof value === "string") return Number(value) || 0;
if (value && typeof value === "object" && "toString" in value) return Number(value.toString()) || 0;
return 0;
}
function normalizeChartColor(value: string): string {
return /^#[0-9a-f]{6}$/i.test(value) ? value : "#6b7280";
}
function formatDate(value: Date | null | undefined): string | undefined {
return value ? value.toISOString().slice(0, 10) : undefined;
}
function formatTimeRange(start: Date, end: Date): string {
return `${start.toISOString().slice(11, 16)}-${end.toISOString().slice(11, 16)}`;
}