Spaces:
Running

File size: 2,247 Bytes
f287aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { User } from "../types";

export const MODULE_BACKED_PAGE_ORDER = [
  "dashboard",
  "tanks",
  "procurement",
  "harvest",
  "inventory",
  "sales",
  "accounting",
  "analytics",
  "fish-types",
  "food-types",
  "medicine-types",
  "users",
  "iot-management",
  "farms",
  "ai-assistant",
  "health",
  "notifications",
  "tasks",
] as const;

export type ModuleBackedPageId = (typeof MODULE_BACKED_PAGE_ORDER)[number];

export interface NavigationModule {
  id: string;
  label?: {
    en?: string;
    ar?: string;
  };
}

const normalizeModuleId = (value: string): string =>
  value
    .trim()
    .toLowerCase()
    .replace(/[_\s]+/g, "-");

const MODULE_ID_ALIASES: Record<string, ModuleBackedPageId> = {
  task: "tasks",
  "user-management": "users",
};

const canonicalizeModuleId = (value: string): ModuleBackedPageId | "" => {
  const normalized = normalizeModuleId(value);
  if (!normalized) {
    return "";
  }

  const aliased = MODULE_ID_ALIASES[normalized] ?? normalized;
  return MODULE_BACKED_PAGE_ORDER.includes(aliased as ModuleBackedPageId)
    ? (aliased as ModuleBackedPageId)
    : "";
};

export const resolveAllowedPages = (user: User): string[] => {
  const fallbackPages = [...MODULE_BACKED_PAGE_ORDER];

  const userModules = user.modules?.map(canonicalizeModuleId).filter(Boolean);
  const effectiveModules = userModules ? [...userModules] : [];

  const allowedModulePages =
    effectiveModules.length > 0
      ? MODULE_BACKED_PAGE_ORDER.filter((pageId) =>
          effectiveModules.includes(pageId),
        )
      : fallbackPages;

  if (allowedModulePages.length === 0) {
    return ["dashboard"];
  }

  return allowedModulePages;
};

export const buildModuleLabelMap = (
  modules: NavigationModule[],
): Record<string, string> => {
  const mapping: Record<string, string> = {};

  modules.forEach((moduleEntry) => {
    const id = canonicalizeModuleId(moduleEntry.id);
    if (!id) {
      return;
    }

    const label = moduleEntry.label?.en || moduleEntry.label?.ar;
    if (label && label.trim()) {
      mapping[id] = label.trim();
    }
  });

  return mapping;
};

export const isPageAllowed = (
  pageId: string,
  allowedPages: string[],
): boolean => allowedPages.includes(pageId);