QuickNav.jsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. const ACTIVE_NAV_BUTTON_CLASS =
  38. "border-blue-600 bg-blue-50 hover:bg-blue-50 dark:border-blue-900 dark:bg-blue-950 dark:hover:bg-blue-950";
  39. export default function QuickNav() {
  40. const router = useRouter();
  41. const pathname = usePathname() || "/";
  42. const { status, user, retry } = useAuth();
  43. const isAuthenticated = status === "authenticated" && user;
  44. const isAdminDev =
  45. isAuthenticated && (user.role === "admin" || user.role === "dev");
  46. const isBranchUser = isAuthenticated && user.role === "branch";
  47. const canRevalidate = typeof retry === "function";
  48. const [selectedBranch, setSelectedBranch] = React.useState(null);
  49. const [branchList, setBranchList] = React.useState({
  50. status: BRANCH_LIST_STATE.IDLE,
  51. branches: null,
  52. });
  53. const activePrimaryNav = React.useMemo(() => {
  54. return getPrimaryNavFromPathname(pathname);
  55. }, [pathname]);
  56. const isExplorerActive = activePrimaryNav?.active === PRIMARY_NAV.EXPLORER;
  57. const isSearchActive = activePrimaryNav?.active === PRIMARY_NAV.SEARCH;
  58. const routeBranch = React.useMemo(() => {
  59. return readRouteBranchFromPathname(pathname);
  60. }, [pathname]);
  61. const knownBranches =
  62. branchList.status === BRANCH_LIST_STATE.READY &&
  63. Array.isArray(branchList.branches)
  64. ? branchList.branches
  65. : null;
  66. const isKnownRouteBranch = React.useMemo(() => {
  67. if (!routeBranch) return false;
  68. if (!knownBranches) return false;
  69. return knownBranches.includes(routeBranch);
  70. }, [routeBranch, knownBranches]);
  71. React.useEffect(() => {
  72. if (!isAuthenticated) return;
  73. if (isBranchUser) {
  74. const own = user.branchId;
  75. setSelectedBranch(own && isValidBranchParam(own) ? own : null);
  76. return;
  77. }
  78. const fromStorage = safeReadLocalStorageBranch(STORAGE_KEY_LAST_BRANCH);
  79. if (fromStorage && fromStorage !== selectedBranch) {
  80. setSelectedBranch(fromStorage);
  81. }
  82. }, [isAuthenticated, isBranchUser, user?.branchId, selectedBranch]);
  83. React.useEffect(() => {
  84. if (!isAdminDev) return;
  85. let cancelled = false;
  86. setBranchList({ status: BRANCH_LIST_STATE.LOADING, branches: null });
  87. (async () => {
  88. try {
  89. const res = await getBranches();
  90. if (cancelled) return;
  91. const branches = Array.isArray(res?.branches) ? res.branches : [];
  92. setBranchList({ status: BRANCH_LIST_STATE.READY, branches });
  93. } catch (err) {
  94. if (cancelled) return;
  95. console.error("[QuickNav] getBranches failed:", err);
  96. setBranchList({ status: BRANCH_LIST_STATE.ERROR, branches: null });
  97. }
  98. })();
  99. return () => {
  100. cancelled = true;
  101. };
  102. }, [isAdminDev, user?.userId]);
  103. React.useEffect(() => {
  104. if (!isAdminDev) return;
  105. if (!knownBranches || knownBranches.length === 0) return;
  106. if (!selectedBranch || !knownBranches.includes(selectedBranch)) {
  107. const next = knownBranches[0];
  108. setSelectedBranch(next);
  109. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, next);
  110. }
  111. }, [isAdminDev, knownBranches, selectedBranch]);
  112. React.useEffect(() => {
  113. if (!isAdminDev) return;
  114. if (!isKnownRouteBranch) return;
  115. if (!routeBranch) return;
  116. if (routeBranch !== selectedBranch) {
  117. setSelectedBranch(routeBranch);
  118. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, routeBranch);
  119. }
  120. }, [isAdminDev, isKnownRouteBranch, routeBranch, selectedBranch]);
  121. React.useEffect(() => {
  122. if (!isAdminDev) return;
  123. if (!selectedBranch) return;
  124. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, selectedBranch);
  125. }, [isAdminDev, selectedBranch]);
  126. if (!isAuthenticated) return null;
  127. const effectiveBranch = isBranchUser ? user.branchId : selectedBranch;
  128. const canNavigate = Boolean(
  129. effectiveBranch && isValidBranchParam(effectiveBranch),
  130. );
  131. function navigateToBranchKeepingContext(nextBranch) {
  132. if (!isValidBranchParam(nextBranch)) return;
  133. const currentPathname =
  134. typeof window !== "undefined"
  135. ? window.location.pathname || pathname
  136. : pathname;
  137. const currentSearch =
  138. typeof window !== "undefined" ? window.location.search || "" : "";
  139. const nextUrl = buildNextUrlForBranchSwitch({
  140. pathname: currentPathname,
  141. search: currentSearch,
  142. nextBranch,
  143. });
  144. if (!nextUrl) return;
  145. if (canRevalidate) retry();
  146. router.push(nextUrl);
  147. }
  148. return (
  149. <div className="hidden items-center gap-2 md:flex">
  150. {isAdminDev ? (
  151. <DropdownMenu>
  152. <DropdownMenuTrigger asChild>
  153. <Button
  154. variant="outline"
  155. size="sm"
  156. type="button"
  157. title="Niederlassung auswählen"
  158. >
  159. {canNavigate ? effectiveBranch : "Niederlassung wählen"}
  160. </Button>
  161. </DropdownMenuTrigger>
  162. <DropdownMenuContent align="end" className="min-w-56">
  163. <DropdownMenuLabel>Niederlassung</DropdownMenuLabel>
  164. <DropdownMenuSeparator />
  165. {branchList.status === BRANCH_LIST_STATE.ERROR ? (
  166. <div className="px-2 py-2 text-xs text-muted-foreground">
  167. Konnte nicht geladen werden.
  168. </div>
  169. ) : (
  170. <DropdownMenuRadioGroup
  171. value={canNavigate ? effectiveBranch : ""}
  172. onValueChange={(value) => {
  173. if (!value) return;
  174. if (!isValidBranchParam(value)) return;
  175. setSelectedBranch(value);
  176. safeWriteLocalStorageBranch(STORAGE_KEY_LAST_BRANCH, value);
  177. navigateToBranchKeepingContext(value);
  178. }}
  179. >
  180. {(Array.isArray(branchList.branches)
  181. ? branchList.branches
  182. : []
  183. ).map((b) => (
  184. <DropdownMenuRadioItem key={b} value={b}>
  185. {b}
  186. </DropdownMenuRadioItem>
  187. ))}
  188. </DropdownMenuRadioGroup>
  189. )}
  190. </DropdownMenuContent>
  191. </DropdownMenu>
  192. ) : null}
  193. <Button
  194. variant="outline"
  195. size="sm"
  196. asChild
  197. disabled={!canNavigate}
  198. className={isExplorerActive ? ACTIVE_NAV_BUTTON_CLASS : ""}
  199. >
  200. <Link
  201. href={canNavigate ? branchPath(effectiveBranch) : "#"}
  202. title="Explorer öffnen"
  203. aria-current={isExplorerActive ? "page" : undefined}
  204. >
  205. <FolderOpen className="h-4 w-4" />
  206. Explorer
  207. </Link>
  208. </Button>
  209. <Button
  210. variant="outline"
  211. size="sm"
  212. asChild
  213. disabled={!canNavigate}
  214. className={isSearchActive ? ACTIVE_NAV_BUTTON_CLASS : ""}
  215. >
  216. <Link
  217. href={canNavigate ? searchPath(effectiveBranch) : "#"}
  218. title="Suche öffnen"
  219. aria-current={isSearchActive ? "page" : undefined}
  220. >
  221. <SearchIcon className="h-4 w-4" />
  222. Suche
  223. </Link>
  224. </Button>
  225. </div>
  226. );
  227. }