QuickNav.jsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. "use client";
  2. import React from "react";
  3. import Link from "next/link";
  4. import { usePathname, useRouter } from "next/navigation";
  5. import { FolderOpen, Search as SearchIcon } from "lucide-react";
  6. import { useAuth } from "@/components/auth/authContext";
  7. import { getBranches } from "@/lib/frontend/apiClient";
  8. import { branchPath, searchPath } from "@/lib/frontend/routes";
  9. import { isValidBranchParam } from "@/lib/frontend/params";
  10. import {
  11. buildNextUrlForBranchSwitch,
  12. readRouteBranchFromPathname,
  13. safeReadLocalStorageBranch,
  14. safeWriteLocalStorageBranch,
  15. } from "@/lib/frontend/quickNav/branchSwitch";
  16. import {
  17. getPrimaryNavFromPathname,
  18. PRIMARY_NAV,
  19. } from "@/lib/frontend/nav/activeRoute";
  20. import { Button } from "@/components/ui/button";
  21. import {
  22. DropdownMenu,
  23. DropdownMenuContent,
  24. DropdownMenuLabel,
  25. DropdownMenuRadioGroup,
  26. DropdownMenuRadioItem,
  27. DropdownMenuSeparator,
  28. DropdownMenuTrigger,
  29. } from "@/components/ui/dropdown-menu";
  30. const STORAGE_KEY_LAST_BRANCH = "rhl_last_branch";
  31. const BRANCH_LIST_STATE = Object.freeze({
  32. IDLE: "idle",
  33. LOADING: "loading",
  34. READY: "ready",
  35. ERROR: "error",
  36. });
  37. export default function QuickNav() {
  38. const router = useRouter();
  39. const pathname = usePathname() || "/";
  40. const { status, user, retry } = useAuth();
  41. const isAuthenticated = status === "authenticated" && user;
  42. const isAdminDev =
  43. isAuthenticated && (user.role === "admin" || user.role === "dev");
  44. const isBranchUser = isAuthenticated && user.role === "branch";
  45. const canRevalidate = typeof retry === "function";
  46. const [selectedBranch, setSelectedBranch] = React.useState(null);
  47. const [branchList, setBranchList] = React.useState({
  48. status: BRANCH_LIST_STATE.IDLE,
  49. branches: null,
  50. });
  51. const activePrimaryNav = React.useMemo(() => {
  52. return getPrimaryNavFromPathname(pathname);
  53. }, [pathname]);
  54. const isExplorerActive = activePrimaryNav?.active === PRIMARY_NAV.EXPLORER;
  55. const isSearchActive = activePrimaryNav?.active === PRIMARY_NAV.SEARCH;
  56. React.useEffect(() => {
  57. if (!isAuthenticated) return;
  58. if (isBranchUser) {
  59. const own = user.branchId;
  60. setSelectedBranch(own && isValidBranchParam(own) ? own : null);
  61. return;
  62. }
  63. const fromRoute = readRouteBranchFromPathname(pathname);
  64. const fromStorage = safeReadLocalStorageBranch(STORAGE_KEY_LAST_BRANCH);
  65. const initial = fromRoute || fromStorage || null;
  66. if (initial && initial !== selectedBranch) {
  67. setSelectedBranch(initial);
  68. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, initial);
  69. }
  70. }, [isAuthenticated, isBranchUser, user?.branchId, pathname, selectedBranch]);
  71. React.useEffect(() => {
  72. if (!isAdminDev) return;
  73. let cancelled = false;
  74. setBranchList({ status: BRANCH_LIST_STATE.LOADING, branches: null });
  75. (async () => {
  76. try {
  77. const res = await getBranches();
  78. if (cancelled) return;
  79. const branches = Array.isArray(res?.branches) ? res.branches : [];
  80. setBranchList({ status: BRANCH_LIST_STATE.READY, branches });
  81. } catch (err) {
  82. if (cancelled) return;
  83. console.error("[QuickNav] getBranches failed:", err);
  84. setBranchList({ status: BRANCH_LIST_STATE.ERROR, branches: null });
  85. }
  86. })();
  87. return () => {
  88. cancelled = true;
  89. };
  90. }, [isAdminDev, user?.userId]);
  91. React.useEffect(() => {
  92. if (!isAdminDev) return;
  93. if (branchList.status !== BRANCH_LIST_STATE.READY) return;
  94. const branches = Array.isArray(branchList.branches)
  95. ? branchList.branches
  96. : [];
  97. if (branches.length === 0) return;
  98. if (!selectedBranch || !branches.includes(selectedBranch)) {
  99. const next = branches[0];
  100. setSelectedBranch(next);
  101. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, next);
  102. }
  103. }, [isAdminDev, branchList.status, branchList.branches, selectedBranch]);
  104. React.useEffect(() => {
  105. if (!isAdminDev) return;
  106. if (!selectedBranch) return;
  107. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, selectedBranch);
  108. }, [isAdminDev, selectedBranch]);
  109. if (!isAuthenticated) return null;
  110. const effectiveBranch = isBranchUser ? user.branchId : selectedBranch;
  111. const canNavigate = Boolean(
  112. effectiveBranch && isValidBranchParam(effectiveBranch),
  113. );
  114. function navigateToBranchKeepingContext(nextBranch) {
  115. if (!isValidBranchParam(nextBranch)) return;
  116. const currentPathname =
  117. typeof window !== "undefined"
  118. ? window.location.pathname || pathname
  119. : pathname;
  120. const currentSearch =
  121. typeof window !== "undefined" ? window.location.search || "" : "";
  122. const nextUrl = buildNextUrlForBranchSwitch({
  123. pathname: currentPathname,
  124. search: currentSearch,
  125. nextBranch,
  126. });
  127. if (!nextUrl) return;
  128. // Optional but desired (RHL-032):
  129. // Trigger a session revalidation without causing content flicker.
  130. if (canRevalidate) retry();
  131. router.push(nextUrl);
  132. }
  133. const explorerVariant = isExplorerActive ? "secondary" : "ghost";
  134. const searchVariant = isSearchActive ? "secondary" : "ghost";
  135. return (
  136. <div className="hidden items-center gap-2 md:flex">
  137. {isAdminDev ? (
  138. <DropdownMenu>
  139. <DropdownMenuTrigger asChild>
  140. <Button
  141. variant="outline"
  142. size="sm"
  143. type="button"
  144. title="Niederlassung auswählen"
  145. >
  146. {canNavigate ? effectiveBranch : "Niederlassung wählen"}
  147. </Button>
  148. </DropdownMenuTrigger>
  149. <DropdownMenuContent align="end" className="min-w-56">
  150. <DropdownMenuLabel>Niederlassung</DropdownMenuLabel>
  151. <DropdownMenuSeparator />
  152. {branchList.status === BRANCH_LIST_STATE.ERROR ? (
  153. <div className="px-2 py-2 text-xs text-muted-foreground">
  154. Konnte nicht geladen werden.
  155. </div>
  156. ) : (
  157. <DropdownMenuRadioGroup
  158. value={canNavigate ? effectiveBranch : ""}
  159. onValueChange={(value) => {
  160. if (!value) return;
  161. if (!isValidBranchParam(value)) return;
  162. setSelectedBranch(value);
  163. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, value);
  164. navigateToBranchKeepingContext(value);
  165. }}
  166. >
  167. {(Array.isArray(branchList.branches)
  168. ? branchList.branches
  169. : []
  170. ).map((b) => (
  171. <DropdownMenuRadioItem key={b} value={b}>
  172. {b}
  173. </DropdownMenuRadioItem>
  174. ))}
  175. </DropdownMenuRadioGroup>
  176. )}
  177. </DropdownMenuContent>
  178. </DropdownMenu>
  179. ) : null}
  180. <Button
  181. variant={explorerVariant}
  182. size="sm"
  183. asChild
  184. disabled={!canNavigate}
  185. >
  186. <Link
  187. href={canNavigate ? branchPath(effectiveBranch) : "#"}
  188. title="Explorer öffnen"
  189. aria-current={isExplorerActive ? "page" : undefined}
  190. >
  191. <FolderOpen className="h-4 w-4" />
  192. Explorer
  193. </Link>
  194. </Button>
  195. <Button variant={searchVariant} size="sm" asChild disabled={!canNavigate}>
  196. <Link
  197. href={canNavigate ? searchPath(effectiveBranch) : "#"}
  198. title="Suche öffnen"
  199. aria-current={isSearchActive ? "page" : undefined}
  200. >
  201. <SearchIcon className="h-4 w-4" />
  202. Suche
  203. </Link>
  204. </Button>
  205. </div>
  206. );
  207. }