687 lines
27 KiB
TypeScript
687 lines
27 KiB
TypeScript
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import { featureKeys } from "@hivegrid/entitlements";
|
|
import type { Params } from "react-router";
|
|
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
|
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
|
|
import { withTenantRLS } 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";
|
|
|
|
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";
|
|
|
|
export type DashboardRoleKey = "gf" | "office" | "monteur";
|
|
export type DashboardWidgetDomain = "general" | "sales" | "projects" | "tasks" | "hr" | "activity" | "comms" | "schedule";
|
|
export type DashboardWidgetKind = "hero" | "kpi" | "list" | "trend";
|
|
|
|
export interface DashboardWidgetDefinition {
|
|
readonly key: string;
|
|
readonly domain: DashboardWidgetDomain;
|
|
readonly kind: DashboardWidgetKind;
|
|
readonly titleKey: string;
|
|
readonly descriptionKey: string;
|
|
readonly requiredAnyPermission: readonly string[];
|
|
readonly defaultPeriod: "today" | "7d" | "30d" | "quarter";
|
|
}
|
|
|
|
export interface DashboardRoleLayoutDefinition {
|
|
readonly role: DashboardRoleKey;
|
|
readonly nameKey: string;
|
|
readonly descriptionKey: string;
|
|
readonly mobileFirst: boolean;
|
|
readonly widgets: readonly {
|
|
readonly key: string;
|
|
readonly position: { readonly x: number; readonly y: number };
|
|
readonly size: { readonly w: number; readonly h: number };
|
|
readonly config?: Record<string, string | number | boolean>;
|
|
}[];
|
|
}
|
|
|
|
export interface DashboardContext {
|
|
readonly tenantId: string;
|
|
readonly tenantSlug: string;
|
|
readonly userId: string;
|
|
readonly permissions: readonly string[];
|
|
readonly canCustomize: boolean;
|
|
}
|
|
|
|
export interface DashboardMetric {
|
|
readonly labelKey: string;
|
|
readonly value: string;
|
|
}
|
|
|
|
export interface DashboardWidgetVM {
|
|
readonly key: string;
|
|
readonly titleKey: string;
|
|
readonly descriptionKey: string;
|
|
readonly domain: DashboardWidgetDomain;
|
|
readonly kind: DashboardWidgetKind;
|
|
readonly period: DashboardWidgetDefinition["defaultPeriod"];
|
|
readonly visible: boolean;
|
|
readonly loadingMode: "lazy";
|
|
readonly metrics: readonly DashboardMetric[];
|
|
readonly items: readonly { readonly id: string; readonly label?: string; readonly labelKey?: string; readonly href?: string; readonly meta?: string }[];
|
|
readonly position: { readonly x: number; readonly y: number };
|
|
readonly size: { readonly w: number; readonly h: number };
|
|
}
|
|
|
|
export interface DashboardRoleVM {
|
|
readonly role: DashboardRoleKey;
|
|
readonly nameKey: string;
|
|
readonly descriptionKey: string;
|
|
readonly mobileFirst: boolean;
|
|
readonly isDefault: boolean;
|
|
readonly widgets: readonly DashboardWidgetVM[];
|
|
}
|
|
|
|
export interface DashboardVM {
|
|
readonly activeRole: DashboardRoleKey;
|
|
readonly roles: readonly DashboardRoleVM[];
|
|
readonly generatedAt: string;
|
|
readonly streamUrl: string;
|
|
readonly liveUpdatesEnabled: boolean;
|
|
readonly canCustomize: boolean;
|
|
}
|
|
|
|
type DashboardSourceSnapshot = {
|
|
readonly generatedAt: string;
|
|
readonly sales: {
|
|
readonly openProjects: number;
|
|
readonly wonProjects: number;
|
|
readonly forecastValue: number;
|
|
};
|
|
readonly projects: {
|
|
readonly activeProjects: number;
|
|
readonly dueSoon: number;
|
|
readonly openDefects: number;
|
|
readonly myProjects: readonly { id: string; label?: string; labelKey?: string; href: string; meta?: string }[];
|
|
};
|
|
readonly tasks: {
|
|
readonly myOpen: number;
|
|
readonly dueToday: number;
|
|
readonly items: readonly { id: string; label?: string; labelKey?: string; href: string; meta?: string }[];
|
|
};
|
|
readonly hr: {
|
|
readonly pendingRequests: number;
|
|
};
|
|
readonly activity: {
|
|
readonly items: readonly { id: string; label?: string; labelKey?: string; href?: string; meta?: string }[];
|
|
};
|
|
readonly comms: {
|
|
readonly callsToday: number;
|
|
};
|
|
readonly schedule: {
|
|
readonly today: readonly { id: string; label?: string; labelKey?: string; href?: string; meta?: string }[];
|
|
};
|
|
};
|
|
|
|
const widgetCatalog = Object.freeze([
|
|
{
|
|
key: "general.welcome",
|
|
domain: "general",
|
|
kind: "hero",
|
|
titleKey: "app.dashboard.widgets.welcome.title",
|
|
descriptionKey: "app.dashboard.widgets.welcome.description",
|
|
requiredAnyPermission: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
|
|
defaultPeriod: "today",
|
|
},
|
|
{
|
|
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.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: "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.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.write", "hr.admin", "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: [DASHBOARD_READ_PERMISSION, LEGACY_DASHBOARD_PERMISSION],
|
|
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: [
|
|
{ key: "general.welcome", position: { x: 0, y: 0 }, size: { w: 12, h: 1 } },
|
|
{ key: "sales.kpis", position: { x: 0, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "sales.forecast", position: { x: 4, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "projects.kpis", position: { x: 8, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "hr.requests_pending", position: { x: 0, y: 3 }, size: { w: 4, h: 2 } },
|
|
{ key: "projects.open_defects", position: { x: 4, y: 3 }, size: { w: 4, h: 2 } },
|
|
{ key: "activity.recent", position: { x: 8, y: 3 }, size: { w: 4, h: 2 } },
|
|
],
|
|
},
|
|
{
|
|
role: "office",
|
|
nameKey: "app.dashboard.roles.office.name",
|
|
descriptionKey: "app.dashboard.roles.office.description",
|
|
mobileFirst: false,
|
|
widgets: [
|
|
{ key: "general.welcome", position: { x: 0, y: 0 }, size: { w: 12, h: 1 } },
|
|
{ key: "projects.kpis", position: { x: 0, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "tasks.my_open", position: { x: 4, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "comms.calls_today", position: { x: 8, y: 1 }, size: { w: 4, h: 2 } },
|
|
{ key: "hr.requests_pending", position: { x: 0, y: 3 }, size: { w: 6, h: 2 } },
|
|
{ key: "activity.recent", position: { x: 6, y: 3 }, size: { w: 6, h: 2 } },
|
|
],
|
|
},
|
|
{
|
|
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[]);
|
|
|
|
const widgetByKey = new Map(widgetCatalog.map((widget) => [widget.key, widget]));
|
|
|
|
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] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(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);
|
|
return {
|
|
tenantId,
|
|
tenantSlug: params.tenant ?? tenantId,
|
|
userId: userInfo.userId,
|
|
permissions,
|
|
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 });
|
|
await ensureDefaultDashboards(ctx);
|
|
const snapshot = await loadDashboardSourceSnapshot(ctx);
|
|
const requestedRole = new URL(request.url).searchParams.get("role");
|
|
const activeRole = isDashboardRole(requestedRole) ? requestedRole : defaultRoleForPermissions(ctx.permissions);
|
|
return buildDashboardVM({ ctx, snapshot, activeRole });
|
|
}
|
|
|
|
export async function loadDashboardStreamSnapshot({ request, params }: { request: Request; params: Params }): Promise<DashboardVM> {
|
|
const ctx = await loadDashboardContext({ request, params });
|
|
const requestedRole = new URL(request.url).searchParams.get("role");
|
|
const activeRole = isDashboardRole(requestedRole) ? requestedRole : defaultRoleForPermissions(ctx.permissions);
|
|
const snapshot = await loadDashboardSourceSnapshot(ctx);
|
|
return buildDashboardVM({ ctx, snapshot, activeRole });
|
|
}
|
|
|
|
function buildDashboardVM({ ctx, snapshot, activeRole }: { ctx: DashboardContext; snapshot: DashboardSourceSnapshot; activeRole: DashboardRoleKey }): DashboardVM {
|
|
return {
|
|
activeRole,
|
|
generatedAt: snapshot.generatedAt,
|
|
streamUrl: appPath({ tenantSlug: ctx.tenantSlug, path: `dashboard/stream?role=${activeRole}`, mode: "host-aware" }),
|
|
liveUpdatesEnabled: true,
|
|
canCustomize: ctx.canCustomize,
|
|
roles: roleLayouts.map((layout) => ({
|
|
role: layout.role,
|
|
nameKey: layout.nameKey,
|
|
descriptionKey: layout.descriptionKey,
|
|
mobileFirst: layout.mobileFirst,
|
|
isDefault: layout.role === activeRole,
|
|
widgets: layout.widgets.map((widgetLayout) => {
|
|
const widget = widgetByKey.get(widgetLayout.key);
|
|
if (!widget) {
|
|
throw new Error(`Unknown dashboard widget key: ${widgetLayout.key}`);
|
|
}
|
|
const visible = hasAnyPermission(ctx.permissions, widget.requiredAnyPermission);
|
|
return {
|
|
key: widget.key,
|
|
titleKey: widget.titleKey,
|
|
descriptionKey: widget.descriptionKey,
|
|
domain: widget.domain,
|
|
kind: widget.kind,
|
|
period: widget.defaultPeriod,
|
|
visible,
|
|
loadingMode: "lazy",
|
|
position: widgetLayout.position,
|
|
size: widgetLayout.size,
|
|
...(visible ? widgetData(widget.key, snapshot) : { metrics: [], items: [] }),
|
|
};
|
|
}),
|
|
})),
|
|
};
|
|
}
|
|
|
|
async function loadDashboardSourceSnapshot(ctx: DashboardContext): Promise<DashboardSourceSnapshot> {
|
|
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);
|
|
const generatedAt = now.toISOString();
|
|
|
|
return withTenantRLS(ctx.tenantId, async (tx) => {
|
|
const canReadAllProjects = ctx.permissions.includes("projects.read_all");
|
|
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.write", "hr.admin", "hr.leave.approve"]);
|
|
const canReadSchedule = hasAnyPermission(ctx.permissions, ["calendar.connect_own", "bookings.read_own", "plantafel.read_own", "plantafel.read_all"]);
|
|
const canReadDefects = hasAnyPermission(ctx.permissions, ["acceptance.read", "acceptance.admin"]);
|
|
const projectOwnerWhere = canReadAllProjects
|
|
? {}
|
|
: { OR: [{ zustaendigePersonId: ctx.userId }, { projektleiterId: ctx.userId }, { createdByUserId: ctx.userId }] };
|
|
const projectWhere = { tenantId: ctx.tenantId, archivedAt: null, ...projectOwnerWhere };
|
|
|
|
const [
|
|
openProjects,
|
|
wonProjects,
|
|
forecastSnapshots,
|
|
activeProjects,
|
|
dueSoonProjects,
|
|
myProjects,
|
|
myOpenTasks,
|
|
dueTodayTasks,
|
|
taskItems,
|
|
pendingHrRequests,
|
|
openDefects,
|
|
recentActivity,
|
|
callsToday,
|
|
calendarEvents,
|
|
appointments,
|
|
] = await Promise.all([
|
|
canReadProjects ? tx.projekt.count({ where: projectWhere }) : Promise.resolve(0),
|
|
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, wonAt: { not: null } } }) : Promise.resolve(0),
|
|
hasAnyPermission(ctx.permissions, ["deals.read_aggregates", "deals.read_volume_all"])
|
|
? tx.pipelineAggregateSnapshot.findMany({
|
|
where: { tenantId: ctx.tenantId, scopeKey: "pipeline" },
|
|
orderBy: { calculatedAt: "desc" },
|
|
take: 12,
|
|
select: { weightedForecast: true },
|
|
})
|
|
: Promise.resolve([]),
|
|
canReadProjects ? tx.projekt.count({ where: projectWhere }) : Promise.resolve(0),
|
|
canReadProjects ? tx.projekt.count({ where: { ...projectWhere, deadline: { gte: todayStart, lt: dueSoon } } }) : Promise.resolve(0),
|
|
canReadProjects
|
|
? tx.projekt.findMany({
|
|
where: projectWhere,
|
|
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"] }, OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
|
})
|
|
: Promise.resolve(0),
|
|
canReadTasks
|
|
? tx.task.count({
|
|
where: {
|
|
tenantId: ctx.tenantId,
|
|
archivedAt: null,
|
|
status: { notIn: ["done", "cancelled"] },
|
|
deadline: { gte: todayStart, lt: todayEnd },
|
|
OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }],
|
|
},
|
|
})
|
|
: Promise.resolve(0),
|
|
canReadTasks
|
|
? tx.task.findMany({
|
|
where: { tenantId: ctx.tenantId, archivedAt: null, status: { notIn: ["done", "cancelled"] }, OR: [{ assignedToUserId: ctx.userId }, { createdByUserId: ctx.userId }] },
|
|
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
|
|
? tx.projektChecklistItem.count({
|
|
where: {
|
|
tenantId: ctx.tenantId,
|
|
status: "offen",
|
|
checklist: {
|
|
tenantId: ctx.tenantId,
|
|
typ: "maengel",
|
|
archivedAt: null,
|
|
},
|
|
},
|
|
})
|
|
: Promise.resolve(0),
|
|
tx.activity.findMany({
|
|
where: { tenantId: ctx.tenantId },
|
|
orderBy: { createdAt: "desc" },
|
|
take: 5,
|
|
select: { id: true, summaryText: true, subjectType: true, subjectId: true, createdAt: true },
|
|
}),
|
|
tx.activity.count({
|
|
where: { tenantId: ctx.tenantId, activityType: { in: ["call", "phone_call", "comms.call"] }, createdAt: { gte: todayStart, lt: todayEnd } },
|
|
}),
|
|
canReadSchedule
|
|
? 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([]),
|
|
canReadSchedule
|
|
? 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 forecastValue = forecastSnapshots.reduce((sum, snapshot) => sum + numeric(snapshot.weightedForecast), 0);
|
|
return {
|
|
generatedAt,
|
|
sales: { openProjects, wonProjects, forecastValue },
|
|
projects: {
|
|
activeProjects,
|
|
dueSoon: dueSoonProjects,
|
|
openDefects,
|
|
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) => ({
|
|
id: activity.id,
|
|
label: activity.summaryText,
|
|
meta: `${activity.subjectType}:${activity.subjectId}`,
|
|
})),
|
|
},
|
|
comms: { callsToday },
|
|
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),
|
|
})),
|
|
],
|
|
},
|
|
};
|
|
});
|
|
}
|
|
|
|
function widgetData(key: string, snapshot: DashboardSourceSnapshot): Pick<DashboardWidgetVM, "metrics" | "items"> {
|
|
switch (key) {
|
|
case "general.welcome":
|
|
return { metrics: [{ labelKey: "app.dashboard.metrics.lastUpdated", value: snapshot.generatedAt }], items: [] };
|
|
case "sales.kpis":
|
|
return {
|
|
metrics: [
|
|
{ labelKey: "app.dashboard.metrics.openProjects", value: String(snapshot.sales.openProjects) },
|
|
{ labelKey: "app.dashboard.metrics.wonProjects", value: String(snapshot.sales.wonProjects) },
|
|
],
|
|
items: [],
|
|
};
|
|
case "sales.forecast":
|
|
return { metrics: [{ labelKey: "app.dashboard.metrics.forecast", value: currency(snapshot.sales.forecastValue) }], items: [] };
|
|
case "projects.kpis":
|
|
return {
|
|
metrics: [
|
|
{ labelKey: "app.dashboard.metrics.activeProjects", value: String(snapshot.projects.activeProjects) },
|
|
{ labelKey: "app.dashboard.metrics.dueSoon", value: String(snapshot.projects.dueSoon) },
|
|
],
|
|
items: [],
|
|
};
|
|
case "projects.open_defects":
|
|
return { metrics: [{ labelKey: "app.dashboard.metrics.openDefects", value: String(snapshot.projects.openDefects) }], items: [] };
|
|
case "projects.my_active":
|
|
return { metrics: [], items: snapshot.projects.myProjects };
|
|
case "tasks.my_open":
|
|
return {
|
|
metrics: [
|
|
{ labelKey: "app.dashboard.metrics.myOpenTasks", value: String(snapshot.tasks.myOpen) },
|
|
{ labelKey: "app.dashboard.metrics.dueToday", value: String(snapshot.tasks.dueToday) },
|
|
],
|
|
items: snapshot.tasks.items,
|
|
};
|
|
case "hr.requests_pending":
|
|
return { metrics: [{ labelKey: "app.dashboard.metrics.pendingHrRequests", value: String(snapshot.hr.pendingRequests) }], items: [] };
|
|
case "activity.recent":
|
|
return { metrics: [], items: snapshot.activity.items };
|
|
case "comms.calls_today":
|
|
return { metrics: [{ labelKey: "app.dashboard.metrics.callsToday", value: String(snapshot.comms.callsToday) }], items: [] };
|
|
case "schedule.my_today":
|
|
return { metrics: [], items: snapshot.schedule.today };
|
|
default:
|
|
return { metrics: [], items: [] };
|
|
}
|
|
}
|
|
|
|
function isDashboardRole(value: string | null): value is DashboardRoleKey {
|
|
return value === "gf" || value === "office" || value === "monteur";
|
|
}
|
|
|
|
function defaultRoleForPermissions(permissions: readonly string[]): DashboardRoleKey {
|
|
if (permissions.includes("projects.read_all") || permissions.includes("deals.read_aggregates")) return "gf";
|
|
if (permissions.includes("plantafel.read_own") || permissions.includes("calendar.connect_own")) return "monteur";
|
|
return "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 currency(value: number): string {
|
|
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR", maximumFractionDigits: 0 }).format(value);
|
|
}
|
|
|
|
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)}`;
|
|
}
|