Files
2026-07-08 16:15:37 +02:00

300 lines
14 KiB
TypeScript

import { Link, LoaderFunctionArgs, useLoaderData } from "react-router";
import { useSearchParams } from "react-router";
import { useAppData } from "~/utils/data/useAppData";
import { DashboardLoaderData, loadDashboardData } from "~/utils/data/useDashboardData";
import { getTranslations } from "~/locale/i18next.server";
import { getAppDashboardStats } from "~/utils/services/appDashboardService";
import ProfileBanner from "~/components/app/ProfileBanner";
import { DashboardStats } from "~/components/ui/stats/DashboardStats";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { Stat } from "~/application/dtos/stats/Stat";
import InputSelect from "~/components/ui/input/InputSelect";
import PeriodHelper, { defaultPeriodFilter, PeriodFilters } from "~/utils/helpers/PeriodHelper";
import { useTranslation } from "react-i18next";
import ServerError from "~/components/ui/errors/ServerError";
import { serverTimingHeaders } from "~/modules/metrics/utils/defaultHeaders";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getTenant } from "~/utils/db/tenants.db.server";
import { Fragment } from "react";
import { loadAppData } from "~/utils/data/.server/appData";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { requireAuth } from "~/utils/loaders.middleware";
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
import { appTenantPlanRequiredPath } from "~/utils/app/AppTenantStatusPaths";
import {
evaluateDashboardModuleGates,
getDashboardModuleDiagnostics,
getVisibleDashboardModules,
type DashboardModuleGateDiagnostic,
} from "~/services/dashboard-registry/gating.server";
import type { DashboardModuleDefinition, DashboardModuleId } from "~/services/dashboard-registry/registry.server";
import { loadDashboardVM, type DashboardVM, type DashboardWidgetVM } from "~/services/dashboard/dashboard.server";
import { getFirstStepsChecklist } from "~/utils/services/.server/akP20OnboardingService";
export { serverTimingHeaders as headers };
const DASHBOARD_READ_PERMISSION = "dashboard.read";
const LEGACY_DASHBOARD_PERMISSION = "app.dashboard.view";
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
type LoaderData = DashboardLoaderData & {
title: string;
stats: Stat[];
modules: DashboardModuleDefinition[];
moduleDiagnostics: DashboardModuleGateDiagnostic[];
dashboard: DashboardVM;
firstStepsChecklist: Awaited<ReturnType<typeof getFirstStepsChecklist>>;
};
function isDashboardModuleVisible(modules: readonly DashboardModuleDefinition[], moduleId: DashboardModuleId) {
return modules.some((module) => module.id === moduleId);
}
function getSafeModuleNoticePath(diagnostic: DashboardModuleGateDiagnostic) {
if (diagnostic.source === "plan") {
return diagnostic.redirectPath?.startsWith("/") ? diagnostic.redirectPath : "/plan-required";
}
return diagnostic.redirectPath?.startsWith("/") ? diagnostic.redirectPath : "/feature-disabled";
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const userInfo = await requireAuth({ request, params });
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "app.$tenant.dashboard");
let { t } = await getTranslations(request);
const { tenantId, appData } = await time(
promiseHash({
tenantId: getTenantIdFromUrl(params),
appData: loadAppData({ request, params, t, time }),
}),
"app.$tenant.dashboard.context"
);
const tenant = await time(getTenant(tenantId), "getTenant");
if (!tenant) {
throw Response.json({ error: t("app.dashboard.errors.tenantNotFound") }, { status: 404 });
}
const { stats, dashboardData, dashboard, firstStepsChecklist, moduleDecisions } = await time(
promiseHash({
stats: getAppDashboardStats({ t, tenant, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
dashboardData: loadDashboardData({ request, params }),
dashboard: loadDashboardVM({ request, params }),
firstStepsChecklist: getFirstStepsChecklist({ tenantId, userId: userInfo.userId }),
moduleDecisions: evaluateDashboardModuleGates({
request,
params,
subscription: appData.mySubscription,
redirectPaths: {
"feature-flag": `/feature-disabled?tenant=${encodeURIComponent(tenant.slug)}`,
plan: appTenantPlanRequiredPath({ tenant: tenant.slug }),
},
}),
}),
"app.$tenant.dashboard.details"
);
const data: LoaderData = {
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
...dashboardData,
stats,
modules: getVisibleDashboardModules(moduleDecisions),
moduleDiagnostics: getDashboardModuleDiagnostics(moduleDecisions),
dashboard,
firstStepsChecklist,
};
return Response.json(data, { headers: getServerTimingHeader() });
};
export default function DashboardRoute() {
const { t } = useTranslation();
const appData = useAppData();
const data = useLoaderData<LoaderData>();
const [searchParams, setSearchParams] = useSearchParams();
const canViewSummary = isDashboardModuleVisible(data.modules, "summary-stats");
const canViewDashboard =
getUserHasPermission(appData, DASHBOARD_READ_PERMISSION) || getUserHasPermission(appData, LEGACY_DASHBOARD_PERMISSION);
const activeRole = data.dashboard.roles.find((role) => role.role === data.dashboard.activeRole) ?? data.dashboard.roles[0];
return (
<main className="relative z-0 flex-1 pb-8" data-ui-id="ui.dashboard.page">
{/*Page header */}
<div className="bg-background border-border hidden border-b md:block">
<ProfileBanner user={appData.user} />
</div>
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
{canViewDashboard ? (
<Fragment>
{activeRole ? (
<section className="space-y-4" data-ui-id="ui.dashboard.roleLayouts">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h1 className="text-foreground text-2xl font-semibold">{t("app.dashboard.title")}</h1>
<p className="text-muted-foreground text-sm">{t(activeRole.descriptionKey)}</p>
</div>
<div className="flex flex-wrap gap-2" role="tablist" aria-label={t("app.dashboard.roleSwitcher.label")}>
{data.dashboard.roles.map((role) => (
<Link
key={role.role}
to={`?role=${role.role}`}
role="tab"
aria-selected={role.role === data.dashboard.activeRole}
className={`rounded-md border px-3 py-2 text-sm font-medium ${
role.role === data.dashboard.activeRole
? "border-neutral-900 bg-neutral-900 text-white"
: "border-border bg-background text-foreground hover:bg-secondary"
}`}
data-ui-id={`ui.dashboard.roleSwitcher.${role.role}`}
>
{t(role.nameKey)}
</Link>
))}
</div>
</div>
<div className="text-muted-foreground flex flex-wrap items-center gap-3 text-xs">
<span>{t("app.dashboard.live.enabled")}</span>
<span>{t("app.dashboard.live.lastUpdated", { at: data.dashboard.generatedAt })}</span>
{data.dashboard.canCustomize ? <span>{t("app.dashboard.customize.available")}</span> : null}
</div>
<div className={activeRole.mobileFirst ? "grid gap-3 sm:grid-cols-2 xl:grid-cols-3" : "grid gap-4 md:grid-cols-2 xl:grid-cols-3"}>
{activeRole.widgets.map((widget) => (
<DashboardWidgetCard key={widget.key} widget={widget} />
))}
</div>
</section>
) : null}
{canViewSummary && data.stats.length > 0 && (
<div className="space-y-3 p-1">
<div className="flex items-center justify-between space-x-2">
<h3 className="text-foreground grow leading-4 font-medium">{t("app.dashboard.summary")}</h3>
<div>
<InputSelect
className="w-48 shrink-0"
name="period"
value={searchParams.get("period")?.toString() ?? defaultPeriodFilter}
options={PeriodFilters.map((f) => {
return {
value: f.value,
name: t(f.name),
};
})}
setValue={(value) => {
if (value) {
searchParams.set("period", value?.toString() ?? "");
} else {
searchParams.delete("period");
}
setSearchParams(searchParams);
}}
/>
</div>
</div>
<DashboardStats items={data.stats} />
</div>
)}
{data.moduleDiagnostics.length > 0 && (
<div className="space-y-2">
{data.moduleDiagnostics.map((diagnostic) => (
<div key={diagnostic.moduleId} className="border-border bg-secondary rounded-md border border-dashed px-4 py-3 text-sm">
<div className="text-foreground font-medium">
{diagnostic.reason === "plan-required"
? t("app.dashboard.moduleDiagnostics.planRequiredTitle")
: t("app.dashboard.moduleDiagnostics.unavailableTitle")}
</div>
<div className="text-muted-foreground mt-1">
{diagnostic.reason === "plan-required"
? t("app.dashboard.moduleDiagnostics.planRequiredDescription")
: t("app.dashboard.moduleDiagnostics.unavailableDescription")}
</div>
<Link className="text-theme-600 mt-2 inline-flex underline" to={getSafeModuleNoticePath(diagnostic)}>
{diagnostic.reason === "plan-required"
? t("app.dashboard.moduleDiagnostics.viewPlanOptions")
: t("app.dashboard.moduleDiagnostics.learnMore")}
</Link>
</div>
))}
</div>
)}
{!data.firstStepsChecklist.dismissed && (
<section className="rounded-md border p-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 className="text-foreground font-medium">{t("onboarding.firstSteps.dashboardTitle")}</h3>
<p className="text-muted-foreground mt-1 text-sm">
{data.firstStepsChecklist.percentComplete === 100
? t("onboarding.firstSteps.dashboardComplete")
: t("onboarding.firstSteps.dashboardProgress", {
completed: data.firstStepsChecklist.completedCount,
total: data.firstStepsChecklist.totalCount,
})}
</p>
</div>
<Link className="text-theme-600 text-sm underline" to="../onboarding/checklist">
{t("onboarding.firstSteps.open")}
</Link>
</div>
<div className="bg-muted mt-4 h-2 overflow-hidden rounded">
<div className="bg-primary h-full" style={{ width: `${data.firstStepsChecklist.percentComplete}%` }} />
</div>
</section>
)}
</Fragment>
) : (
<div className="font-medium">{t("app.dashboard.noPermission")}</div>
)}
</div>
</main>
);
}
function DashboardWidgetCard({ widget }: { widget: DashboardWidgetVM }) {
const { t } = useTranslation();
return (
<section
className="border-border bg-background flex min-h-32 flex-col gap-3 rounded-md border px-4 py-4 shadow-sm"
data-ui-id={`ui.dashboard.widget.${widget.key}`}
data-loading={widget.loadingMode}
>
<div>
<h2 className="text-foreground text-sm font-semibold">{t(widget.titleKey)}</h2>
<p className="text-muted-foreground mt-1 text-xs">{t(widget.descriptionKey)}</p>
</div>
{!widget.visible ? (
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-2 text-xs">{t("app.dashboard.widgets.permissionHidden")}</p>
) : widget.metrics.length > 0 ? (
<dl className="grid grid-cols-2 gap-2">
{widget.metrics.map((metric) => (
<div key={metric.labelKey} className="rounded-md bg-secondary px-3 py-2">
<dt className="text-muted-foreground text-xs">{t(metric.labelKey)}</dt>
<dd className="text-foreground mt-1 text-lg font-semibold">{metric.value}</dd>
</div>
))}
</dl>
) : widget.items.length > 0 ? (
<ul className="divide-border divide-y">
{widget.items.map((item) => (
<li key={item.id} className="flex items-center justify-between gap-3 py-2 text-sm">
{item.href ? (
<Link className="text-theme-600 min-w-0 truncate hover:underline" to={item.href}>
{item.labelKey ? t(item.labelKey) : item.label}
</Link>
) : (
<span className="text-foreground min-w-0 truncate">{item.labelKey ? t(item.labelKey) : item.label}</span>
)}
{item.meta ? <span className="text-muted-foreground shrink-0 text-xs">{item.meta}</span> : null}
</li>
))}
</ul>
) : (
<p className="text-muted-foreground rounded-md border border-dashed px-3 py-2 text-xs">{t("app.dashboard.widgets.empty")}</p>
)}
</section>
);
}
export function ErrorBoundary() {
return <ServerError />;
}