branchUiDecision.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import {
  2. getBranchAccess,
  3. BRANCH_ACCESS,
  4. } from "@/lib/frontend/rbac/branchAccess";
  5. export const BRANCH_UI_DECISION = Object.freeze({
  6. ALLOWED: "allowed",
  7. FORBIDDEN: "forbidden",
  8. NOT_FOUND: "not-found",
  9. });
  10. /**
  11. * Decide which UI outcome should be shown for a branch route.
  12. *
  13. * Notes:
  14. * - This function assumes the user is authenticated (handled by AuthProvider).
  15. * - For admin/dev we can optionally validate branch existence using `allowedBranches`
  16. * from GET /api/branches. If the list is not available, we fail open.
  17. *
  18. * @param {{
  19. * user: { userId: string, role: string, branchId: string|null },
  20. * branch: string,
  21. * allowedBranches?: string[]|null
  22. * }} input
  23. * @returns {"allowed"|"forbidden"|"not-found"}
  24. */
  25. export function decideBranchUi({ user, branch, allowedBranches = null }) {
  26. const access = getBranchAccess(user, branch);
  27. if (access === BRANCH_ACCESS.FORBIDDEN) {
  28. return BRANCH_UI_DECISION.FORBIDDEN;
  29. }
  30. // Only admin/dev may validate existence across branches.
  31. if (user.role === "admin" || user.role === "dev") {
  32. if (Array.isArray(allowedBranches) && !allowedBranches.includes(branch)) {
  33. return BRANCH_UI_DECISION.NOT_FOUND;
  34. }
  35. }
  36. return BRANCH_UI_DECISION.ALLOWED;
  37. }