Files
slp-modular-cms/frontend/src/router.tsx
T

358 lines
12 KiB
TypeScript

import { lazy, Suspense, type ComponentType } from 'react';
import {
createRootRouteWithContext,
createRoute,
createRouter,
Outlet,
redirect,
} from '@tanstack/react-router';
import type { AuthContextValue } from '@/features/auth/context/auth-context';
import type { SetupStatus } from '@/features/setup/services/types';
import { api, NetworkError } from '@/lib/api-client';
import { AppLayout } from '@/components/layout/AppLayout';
import { LoginPage } from '@/features/auth/pages/LoginPage';
import { NotFoundPage } from '@/pages/NotFoundPage';
import { RoleGuard } from '@/features/auth/components/RoleGuard';
import { ModuleGuard } from '@/features/system/components/ModuleGuard';
import { ContactAvailabilityGuard } from '@/features/contact/components/ContactAvailabilityGuard';
export interface RouterContext {
auth: AuthContextValue;
}
// ---------------------------------------------------------------------------
// InitGuard: module-level session cache for setup status (BR-U2-08).
// One network request per page load; subsequent beforeLoad calls return cached
// data synchronously via Promise.resolve().
// ---------------------------------------------------------------------------
let _setupStatusCache: SetupStatus | null = null;
let _setupStatusPromise: Promise<SetupStatus> | null = null;
async function fetchSetupStatus(): Promise<SetupStatus> {
if (_setupStatusCache !== null) return _setupStatusCache;
if (_setupStatusPromise === null) {
_setupStatusPromise = api
.get<{ initialized?: boolean; Initialized?: boolean; tokenRequired?: boolean; TokenRequired?: boolean }>(
'/api/v1/Setup/status',
)
.then((raw) => {
// Backend may return PascalCase (Initialized) if no camelCase policy is set.
const s: SetupStatus = {
initialized: raw.initialized ?? raw.Initialized ?? false,
tokenRequired: raw.tokenRequired ?? raw.TokenRequired ?? false,
};
_setupStatusCache = s;
return s;
})
.catch((err: unknown) => {
_setupStatusPromise = null;
throw err;
});
}
return _setupStatusPromise;
}
// Exposed for tests so each test starts with a clean cache.
export function _resetSetupStatusCache(): void {
_setupStatusCache = null;
_setupStatusPromise = null;
}
/** Whether the setup page must ask for the setup token (known once the InitGuard fetched the status). */
export function isSetupTokenRequired(): boolean {
return _setupStatusCache?.tokenRequired === true;
}
export function _markSystemInitialized(): void {
_setupStatusCache = { initialized: true };
_setupStatusPromise = null;
}
function RouteFallback() {
return (
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
<span className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
function BootstrapSplash() {
return (
<div className="flex min-h-svh items-center justify-center text-muted-foreground">
<span className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
);
}
function lazyPage<P extends Record<string, never>>(
factory: () => Promise<{ [key: string]: ComponentType<P> }>,
exportName: string,
) {
const Loaded = lazy(() => factory().then((module) => ({ default: module[exportName] })));
return function LazyRouteComponent() {
return (
<Suspense fallback={<RouteFallback />}>
<Loaded {...({} as P)} />
</Suspense>
);
};
}
// ---------------------------------------------------------------------------
// Routes
// ---------------------------------------------------------------------------
const rootRoute = createRootRouteWithContext<RouterContext>()({
pendingComponent: BootstrapSplash,
pendingMs: 0,
notFoundComponent: NotFoundPage,
beforeLoad: async ({ location }) => {
let status: SetupStatus;
try {
status = await fetchSetupStatus();
} catch (err) {
// The status could not be read (backend unreachable, rate limited, a 5xx, a disabled CMS...). That
// says nothing about whether the system is set up, and guessing "not set up" would send people to
// the setup page of a system that already has its owner. So: no redirect either way. The normal
// pages (login, with its own notice when the CMS is off) deal with the situation.
if (err instanceof NetworkError) {
// Backend unreachable: treat it as set up, so /setup leads to the login page (unchanged behaviour).
status = { initialized: true };
} else {
console.warn('[InitGuard] Setup status could not be read, not redirecting:', err);
return;
}
}
const onSetup = location.pathname === '/setup';
const onInvite = location.pathname.startsWith('/invite/complete');
if (!status.initialized && !onSetup && !onInvite) {
throw redirect({ to: '/setup' });
}
if (status.initialized && onSetup) {
throw redirect({ to: '/login' });
}
},
component: () => <Outlet />,
});
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
beforeLoad: () => {
throw redirect({ to: '/dashboard' });
},
});
const loginRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/login',
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
redirect: typeof search.redirect === 'string' ? search.redirect : undefined,
}),
beforeLoad: ({ context }) => {
if (context.auth.isAuthenticated) {
throw redirect({ to: '/dashboard' });
}
},
component: LoginPage,
});
const forgotPasswordRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/forgot-password',
beforeLoad: ({ context }) => {
if (context.auth.isAuthenticated) {
throw redirect({ to: '/dashboard' });
}
},
component: lazyPage(() => import('@/features/auth/pages/ForgotPasswordPage'), 'ForgotPasswordPage'),
});
const resetPasswordRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/reset-password',
validateSearch: (search: Record<string, unknown>): { uid?: string; token?: string } => ({
uid: typeof search.uid === 'string' ? search.uid : undefined,
token: typeof search.token === 'string' ? search.token : undefined,
}),
component: lazyPage(() => import('@/features/auth/pages/ResetPasswordPage'), 'ResetPasswordPage'),
});
const setupRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/setup',
component: lazyPage(() => import('@/features/setup/pages/SetupPage'), 'SetupPage'),
});
const inviteCompleteRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/invite/complete',
validateSearch: (search: Record<string, unknown>): { token?: string } => ({
token: typeof search.token === 'string' ? search.token : undefined,
}),
component: lazyPage(() => import('@/features/invitation/pages/InviteCompletePage'), 'InviteCompletePage'),
});
const authenticatedRoute = createRoute({
getParentRoute: () => rootRoute,
id: '_authenticated',
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
throw redirect({ to: '/login', search: { redirect: location.href } });
}
},
component: AppLayout,
});
const dashboardRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/dashboard',
component: lazyPage(() => import('@/features/dashboard/pages/DashboardPage'), 'DashboardPage'),
});
const usersRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/users',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
{lazyPage(() => import('@/features/users/pages/UsersPage'), 'UsersPage')()}
</RoleGuard>
),
});
const cmsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/cms',
component: () => (
<RoleGuard allowedRoles={['Owner']}>
<ModuleGuard requiredModule="Master">
{lazyPage(() => import('@/features/cms/pages/CmsPage'), 'CmsPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const heroRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/hero',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Hero">
{lazyPage(() => import('@/features/hero/pages/HeroPage'), 'HeroPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const offeringsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/offerings',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Offerings">
{lazyPage(() => import('@/features/offerings/pages/OfferingsListPage'), 'OfferingsListPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const offeringsNewRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/offerings/new',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Offerings">
{lazyPage(() => import('@/features/offerings/pages/OfferingFormPage'), 'OfferingFormPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const offeringsEditRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/offerings/$id/edit',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Offerings">
{lazyPage(() => import('@/features/offerings/pages/OfferingFormPage'), 'OfferingFormPage')()}
</ModuleGuard>
</RoleGuard>
),
});
const messagesRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/messages',
validateSearch: (search: Record<string, unknown>): { tab?: 'settings' } => ({
tab: search.tab === 'settings' ? 'settings' : undefined,
}),
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
<ModuleGuard requiredModule="Contact">
<ContactAvailabilityGuard>
{lazyPage(() => import('@/features/contact/pages/MessagesPage'), 'MessagesPage')()}
</ContactAvailabilityGuard>
</ModuleGuard>
</RoleGuard>
),
});
const settingsRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/settings',
component: () => (
<RoleGuard allowedRoles={['Owner', 'Administrator']}>
{lazyPage(() => import('@/features/settings/pages/SettingsPage'), 'SettingsPage')()}
</RoleGuard>
),
});
const profileRoute = createRoute({
getParentRoute: () => authenticatedRoute,
path: '/profile',
component: lazyPage(() => import('@/features/profile/pages/ProfilePage'), 'ProfilePage'),
});
const accessDeniedRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/403',
component: lazyPage(() => import('@/pages/AccessDeniedPage'), 'AccessDeniedPage'),
});
export const routeTree = rootRoute.addChildren([
indexRoute,
loginRoute,
forgotPasswordRoute,
resetPasswordRoute,
setupRoute,
inviteCompleteRoute,
accessDeniedRoute,
authenticatedRoute.addChildren([
dashboardRoute,
usersRoute,
cmsRoute,
heroRoute,
offeringsRoute,
offeringsNewRoute,
offeringsEditRoute,
messagesRoute,
settingsRoute,
profileRoute,
]),
]);
export const router = createRouter({
routeTree,
defaultPreload: 'intent',
// Matches vite.config.ts's `base`: '/admin/' in production builds, '/' in dev.
basepath: import.meta.env.BASE_URL,
context: { auth: undefined as unknown as AuthContextValue },
});
declare module '@tanstack/react-router' {
interface Register {
router: typeof router;
}
}