@jsb188/mday-web 1.1.10 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +34 -24
  2. package/src/libs/route-metadata.server.ts +67 -0
  3. package/src/modules/AgentDocs.tsx +800 -0
  4. package/src/modules/DocAccessSettings.tsx +963 -0
  5. package/src/modules/Grids.tsx +842 -0
  6. package/src/modules/RouteShell.tsx +76 -0
  7. package/src/utils/account-web.ts +64 -0
  8. package/src/utils/list-web.ts +17 -0
  9. package/src/utils/log-web.ts +162 -52
  10. package/src/utils/org-web.ts +35 -8
  11. package/src/utils/route-helpers.ts +902 -596
  12. package/src/utils/workflow-web.ts +96 -0
  13. package/tsconfig.json +11 -11
  14. package/src/modules/DataTable-ContextMenu.tsx +0 -169
  15. package/src/modules/DataTable-InboundContact.tsx +0 -523
  16. package/src/modules/DataTable.tsx +0 -5060
  17. package/src/modules/Sheet-ContextMenu.tsx +0 -161
  18. package/src/modules/Sheet.tsx +0 -28
  19. package/src/modules/cell-save-beacon.ts +0 -67
  20. package/src/modules/dataTable-interaction-state.ts +0 -276
  21. package/src/modules/dataTable-shortcuts.ts +0 -192
  22. package/src/modules/dataTable-viewport.ts +0 -89
  23. package/src/modules/grid-cell-render.ts +0 -72
  24. package/src/modules/grid-context-menu.ts +0 -112
  25. package/src/modules/grid-keyboard.ts +0 -267
  26. package/src/modules/grid-render-store.ts +0 -103
  27. package/src/modules/grid-runtime.ts +0 -178
  28. package/src/modules/grid-selection.ts +0 -336
  29. package/src/modules/grid-viewport.ts +0 -57
  30. package/src/modules/use-dataTable-states.ts +0 -529
  31. package/src/modules/use-debounced-cell-save-batch.ts +0 -160
  32. package/tests/DataTable.test.tsx +0 -4466
  33. package/tests/dataTable-interaction-state.test.ts +0 -127
@@ -1,11 +1,12 @@
1
1
  import i18n from '@jsb188/app/i18n/index.ts';
2
- import type { OrganizationFeatureEnum, OrganizationOperationEnum, OrganizationSidebarGroupObj, OrganizationSidebarItemObj } from '@jsb188/mday/types/organization.d.ts';
3
- import type { ReportGroupGQL } from '@jsb188/mday/types/report.d.ts';
4
- import type { DataTableGQL } from '@jsb188/mday/types/dataTable.d.ts';
2
+ import type {
3
+ OrganizationOperationEnum,
4
+ OrganizationSidebarItemObj,
5
+ } from '@jsb188/mday/types/organization.d.ts';
5
6
  import type { OperationName } from '@jsb188/mday/utils/organization.ts';
6
7
  import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
7
8
 
8
- // Use this for report periods, etc
9
+ // Use this for fieldDoc periods, etc
9
10
  // const CURRENT_YEAR = String(new Date().getFullYear());
10
11
 
11
12
  /**
@@ -13,291 +14,317 @@ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
13
14
  */
14
15
 
15
16
  const OP = {
16
- FARMING: ['ARABLE', 'LIVESTOCK'],
17
- GROWER_NETWORK: ['GROWER_NETWORK'],
17
+ FARMING: ['ARABLE'],
18
+ GROWER_NETWORK: ['GROWER_NETWORK'],
18
19
  };
19
20
 
20
- const F = {
21
- normal_logging: ['NORMAL_LOGGING'],
22
- food_safety: ['FOOD_SAFETY', 'GLOBAL_GAP'],
23
- };
21
+ const LOGIN_CHANGED_ERROR_CODES = new Set(['20080', '20081']);
22
+ const AUTH_RETURN_TO_BASE_URL = 'https://marketday.invalid';
23
+ const AUTH_RETURN_TO_PUBLIC_FORM_PATH_PATTERN = /^\/form\/[^/]+$/;
24
+
25
+ /**
26
+ * Build the translated title and description metadata for a Marketday route.
27
+ */
28
+ export function getMarketdayRouteMeta(
29
+ titleKey: string,
30
+ descriptionKey: string,
31
+ ) {
32
+ return [
33
+ {
34
+ title: i18n.t('app.route_', { text: i18n.t(titleKey) }),
35
+ },
36
+ {
37
+ name: 'description',
38
+ content: i18n.t(descriptionKey),
39
+ },
40
+ ];
41
+ }
24
42
 
25
43
  /**
26
44
  * Rules
27
45
  */
28
46
 
29
47
  type ValidRoutePath =
30
- '/app'
31
- | '/app/c/'
32
- | '/app/workflows-test'
33
- | '/app/workflows'
34
- | '/app/sheets'
35
- | '/app/s/'
36
- | '/app/emails'
37
- | '/app/logs'
38
- | '/app/greenhouse'
39
- | '/app/seeding'
40
- | '/app/transplanting'
41
- | '/app/field-work'
42
- | '/app/harvested'
43
- | '/app/post-harvest'
44
- | '/app/orders'
45
- | '/app/purchases'
46
- | '/app/hygiene'
47
- | '/app/sanitation'
48
- | '/app/materials'
49
- | '/app/biosecurity'
50
- | '/app/employees'
51
- | '/app/vendors'
52
- | '/app/markets'
53
- | '/app/receipts'
54
- | '/app/growers'
55
- | '/app/foreign-growers'
56
-
57
- // Reports
58
- | '/app/r/'
59
- | '/app/d/'
60
- | '/app/p/';
61
- // | '/app/r/water-source/';
48
+ | '/app'
49
+ | '/app/c/'
50
+ | '/app/calendar'
51
+ | '/app/workflows'
52
+ | '/app/grids'
53
+ | '/app/workspace'
54
+ | '/app/s/'
55
+ | '/app/emails'
56
+ | '/app/outbound/forms'
57
+ | '/app/outbound/emails'
58
+ | '/app/downloads'
59
+ | '/app/logs'
60
+ | '/app/greenhouse'
61
+ | '/app/seeding'
62
+ | '/app/transplanting'
63
+ | '/app/field-work'
64
+ | '/app/harvested'
65
+ | '/app/post-harvest'
66
+ | '/app/orders'
67
+ | '/app/purchases'
68
+ | '/app/vendors'
69
+ | '/app/receipts'
70
+ | '/app/growers'
71
+
72
+ // FieldDocs
73
+ | '/app/fd/'
74
+ | '/app/d/'
75
+ | '/app/p/';
76
+ // | '/app/fd/water-source/';
62
77
 
63
78
  interface RouteDictObj {
64
- to: ValidRoutePath;
65
- text: string;
66
- iconName?: string;
67
- allowedOperations?: OrganizationOperationEnum[];
68
- notAllowedOperations?: OrganizationOperationEnum[];
69
- requiredFeature?: OrganizationFeatureEnum[];
70
- requiredACL?: OperationName;
71
-
72
- hasPhysicalToolbar?: 'ALWAYS' | 'NEVER' | ((parts: string[]) => boolean);
79
+ to: ValidRoutePath;
80
+ text: string;
81
+ iconName?: string;
82
+ allowedOperations?: OrganizationOperationEnum[];
83
+ notAllowedOperations?: OrganizationOperationEnum[];
84
+ requiredACL?: OperationName;
85
+
86
+ hasPhysicalToolbar?: 'ALWAYS' | 'NEVER' | ((parts: string[]) => boolean);
73
87
  }
74
88
 
75
89
  type CheckACLClientFn = (opName: OperationName) => boolean;
76
90
 
77
- const ROUTES_DICT: Record<ValidRoutePath, RouteDictObj> = {
91
+ /*
92
+ * Return a same-origin auth destination only when it targets a public form or
93
+ * an authenticated app route.
94
+ */
95
+ export function getSafeAuthReturnToPath(returnTo?: string | null) {
96
+ if (!returnTo?.startsWith('/') || returnTo.startsWith('//')) {
97
+ return null;
98
+ }
99
+
100
+ try {
101
+ const url = new URL(returnTo, AUTH_RETURN_TO_BASE_URL);
102
+ const isPublicFormPath = AUTH_RETURN_TO_PUBLIC_FORM_PATH_PATTERN.test(
103
+ url.pathname,
104
+ );
105
+ const isAppPath =
106
+ url.pathname === '/app' || url.pathname.startsWith('/app/');
107
+
108
+ if (
109
+ url.origin !== AUTH_RETURN_TO_BASE_URL ||
110
+ (!isPublicFormPath && !isAppPath)
111
+ ) {
112
+ return null;
113
+ }
114
+
115
+ return `${url.pathname}${url.search}${url.hash}`;
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Check whether a server error means the viewer must switch login context.
123
+ */
124
+ export function hasLoginChangedError(errorCode?: string | number | null) {
125
+ return LOGIN_CHANGED_ERROR_CODES.has(String(errorCode || ''));
126
+ }
127
+
128
+ /**
129
+ * Route prefixes whose pages stay mounted across pathname changes
130
+ * (the app layout keys its outlet by pathname otherwise)
131
+ */
132
+
133
+ const STABLE_OUTLET_ROUTES = ['/app/runs'];
134
+
135
+ /**
136
+ * Get the outlet key pathname; stable-route pages keep one key across
137
+ * their sub-paths so navigating within them does not remount the page
138
+ */
139
+
140
+ export function getOutletPathnameKey(pathname: string): string {
141
+ const stableRoute = STABLE_OUTLET_ROUTES.find(
142
+ (routePrefix) =>
143
+ pathname === routePrefix || pathname.startsWith(`${routePrefix}/`),
144
+ );
145
+
146
+ return stableRoute || pathname;
147
+ }
78
148
 
79
- // Main /app/ routes
80
- // If route ends with '/', it requires (or optionally accepts) a path segment
81
- // e.g. "/app/c/" means "/app/c/:chatId" etc
82
- // e.g. "/app" means exactly "/app", and it never expects a path segment
83
-
84
- '/app': {
85
- to: '/app',
86
- text: 'app.home',
87
- },
88
- '/app/c/': {
89
- to: '/app/c/',
90
- text: 'app.route_ai_chat',
91
- iconName: COMMON_ICON_NAMES.chat,
92
-
93
- hasPhysicalToolbar: 'ALWAYS',
94
- },
95
- // Advanced
96
-
97
- '/app/workflows-test': {
98
- to: '/app/workflows-test',
99
- text: 'form.ai_workflows',
100
- iconName: COMMON_ICON_NAMES.ai_workflow,
101
- },
102
- '/app/workflows': {
103
- to: '/app/workflows',
104
- text: 'form.ai_workflows',
105
- iconName: COMMON_ICON_NAMES.ai_workflow,
106
- },
107
- '/app/sheets': {
108
- to: '/app/sheets',
109
- text: 'app.sheets',
110
- iconName: COMMON_ICON_NAMES.sheet,
111
- },
112
- '/app/s/': {
113
- to: '/app/s/',
114
- text: 'app.sheets',
115
- iconName: COMMON_ICON_NAMES.sheet,
116
- },
117
- '/app/emails': {
118
- to: '/app/emails',
119
- text: 'app.ai_inboxes',
120
- iconName: COMMON_ICON_NAMES.ai_inbox,
121
- requiredACL: 'ai_inbox_read',
122
- },
123
- '/app/logs': {
124
- to: '/app/logs',
125
- text: 'log.all_logs',
126
- iconName: COMMON_ICON_NAMES.logs,
127
- },
128
-
129
- // Arable
130
-
131
- '/app/greenhouse': {
132
- to: '/app/greenhouse',
133
- text: 'log.greenhouse_seeding',
134
- iconName: COMMON_ICON_NAMES.GREENHOUSE_SEEDING,
135
-
136
- allowedOperations: ['ARABLE'],
137
- requiredFeature: F.normal_logging,
138
- },
139
-
140
- '/app/seeding': {
141
- to: '/app/seeding',
142
- text: 'log.seeding',
143
- iconName: COMMON_ICON_NAMES.seeding,
144
-
145
- allowedOperations: ['ARABLE'],
146
- requiredFeature: F.normal_logging,
147
- },
148
- '/app/transplanting': {
149
- to: '/app/transplanting',
150
- text: 'log.transplanting',
151
- iconName: COMMON_ICON_NAMES.transplanting,
152
-
153
- allowedOperations: ['ARABLE'],
154
- requiredFeature: F.normal_logging,
155
- },
156
- '/app/field-work': {
157
- to: '/app/field-work',
158
- text: 'log.field_work',
159
- iconName: COMMON_ICON_NAMES.field_work,
160
-
161
- allowedOperations: ['ARABLE'],
162
- requiredFeature: F.normal_logging,
163
- },
164
- '/app/harvested': {
165
- to: '/app/harvested',
166
- text: 'log.harvested',
167
- iconName: COMMON_ICON_NAMES.harvest,
168
-
169
- allowedOperations: ['ARABLE'],
170
- requiredFeature: F.normal_logging,
171
- },
172
- '/app/post-harvest': {
173
- to: '/app/post-harvest',
174
- text: 'log.post_harvest',
175
- iconName: COMMON_ICON_NAMES.post_harvest,
176
-
177
- allowedOperations: ['ARABLE'],
178
- requiredFeature: F.normal_logging,
179
- },
180
- '/app/purchases': {
181
- to: '/app/purchases',
182
- text: 'log.purchases',
183
- iconName: COMMON_ICON_NAMES.invoice,
184
-
185
- allowedOperations: OP.FARMING,
186
- requiredFeature: F.normal_logging,
187
- },
188
- '/app/orders': {
189
- to: '/app/orders',
190
- text: 'form.sales_orders',
191
- iconName: COMMON_ICON_NAMES.receipt,
192
-
193
- allowedOperations: OP.FARMING,
194
- requiredFeature: F.normal_logging,
195
- },
196
-
197
- // Arable; Food Safety
198
-
199
- '/app/hygiene': {
200
- to: '/app/hygiene',
201
- text: 'log.hygiene',
202
- iconName: COMMON_ICON_NAMES.HYGIENE,
203
-
204
- allowedOperations: OP.FARMING,
205
- requiredFeature: F.food_safety,
206
- },
207
- '/app/sanitation': {
208
- to: '/app/sanitation',
209
- text: 'log.sanitation',
210
- iconName: COMMON_ICON_NAMES.SANITATION,
211
-
212
- allowedOperations: OP.FARMING,
213
- requiredFeature: F.food_safety,
214
- },
215
- '/app/materials': {
216
- to: '/app/materials',
217
- text: 'log.materials',
218
- iconName: COMMON_ICON_NAMES.MATERIALS,
219
-
220
- allowedOperations: OP.FARMING,
221
- requiredFeature: F.food_safety,
222
- },
223
- '/app/biosecurity': {
224
- to: '/app/biosecurity',
225
- text: 'log.biosecurity',
226
- iconName: COMMON_ICON_NAMES.BIOSECURITY,
227
-
228
- allowedOperations: OP.FARMING,
229
- requiredFeature: F.food_safety,
230
- },
231
- '/app/employees': {
232
- to: '/app/employees',
233
- text: 'log.employees',
234
- iconName: COMMON_ICON_NAMES.EMPLOYEES,
235
-
236
- allowedOperations: OP.FARMING,
237
- requiredFeature: F.food_safety,
238
- },
239
-
240
- // Farmers Market
241
- '/app/vendors': {
242
- to: '/app/vendors',
243
- text: 'form.vendors',
244
- iconName: COMMON_ICON_NAMES.shop_vendor,
245
-
246
- allowedOperations: ['FARMERS_MARKET'],
247
- requiredFeature: F.normal_logging
248
- },
249
- '/app/markets': {
250
- to: '/app/markets',
251
- text: 'form.markets',
252
- iconName: COMMON_ICON_NAMES.shop_market,
253
-
254
- allowedOperations: ['FARMERS_MARKET'],
255
- },
256
- '/app/receipts': {
257
- to: ('/app/receipts') as ValidRoutePath,
258
- text: 'form.market_receipts',
259
- iconName: COMMON_ICON_NAMES.market_receipt,
260
-
261
- allowedOperations: ['FARMERS_MARKET'],
262
- requiredFeature: F.normal_logging
263
- },
264
-
265
- // Grower Network
266
- '/app/growers': {
267
- to: '/app/growers',
268
- text: 'form.domestic_growers',
269
- iconName: COMMON_ICON_NAMES.growers,
270
-
271
- allowedOperations: OP.GROWER_NETWORK,
272
- },
273
- '/app/foreign-growers': {
274
- to: '/app/foreign-growers',
275
- text: 'form.foreign_growers',
276
- iconName: COMMON_ICON_NAMES.foreign_growers,
277
-
278
- allowedOperations: OP.GROWER_NETWORK,
279
- },
280
-
281
- // Reports
282
-
283
- '/app/r/': {
284
- to: '/app/r/',
285
- text: 'form.reports',
286
- iconName: COMMON_ICON_NAMES.generic_report,
287
- hasPhysicalToolbar: 'NEVER',
288
- },
289
- '/app/d/': {
290
- to: '/app/d/',
291
- text: 'form.dataTables',
292
- iconName: COMMON_ICON_NAMES.data_table,
293
- hasPhysicalToolbar: 'NEVER',
294
- },
295
- '/app/p/': {
296
- to: '/app/p/',
297
- text: 'form.reports',
298
- iconName: COMMON_ICON_NAMES.generic_report,
299
- hasPhysicalToolbar: 'NEVER',
300
- },
149
+ const ROUTES_DICT: Record<ValidRoutePath, RouteDictObj> = {
150
+ // Main /app/ routes
151
+ // If route ends with '/', it requires (or optionally accepts) a path segment
152
+ // e.g. "/app/c/" means "/app/c/:chatId" etc
153
+ // e.g. "/app" means exactly "/app", and it never expects a path segment
154
+
155
+ '/app': {
156
+ to: '/app',
157
+ text: 'app.home',
158
+ },
159
+ '/app/grids': {
160
+ to: '/app/grids',
161
+ text: 'app.grids',
162
+ iconName: COMMON_ICON_NAMES.grids,
163
+ },
164
+ '/app/workspace': {
165
+ to: '/app/workspace',
166
+ text: 'app.workspace',
167
+ iconName: COMMON_ICON_NAMES.workspace,
168
+ },
169
+ '/app/calendar': {
170
+ to: '/app/calendar',
171
+ text: 'app.route_calendar',
172
+ iconName: COMMON_ICON_NAMES.calendar,
173
+ // The calendar owns the whole viewport like the Sheet and DataTable
174
+ // surfaces do; it renders its own toolbar row
175
+ hasPhysicalToolbar: 'NEVER',
176
+ },
177
+ '/app/c/': {
178
+ to: '/app/c/',
179
+ text: 'app.route_ai_chat',
180
+ iconName: COMMON_ICON_NAMES.chat,
181
+
182
+ hasPhysicalToolbar: 'ALWAYS',
183
+ },
184
+ // Advanced
185
+
186
+ '/app/workflows': {
187
+ to: '/app/workflows',
188
+ text: 'form.ai_workflows',
189
+ iconName: COMMON_ICON_NAMES.ai_workflow,
190
+ },
191
+ '/app/s/': {
192
+ to: '/app/s/',
193
+ text: 'sheet.sheets',
194
+ iconName: COMMON_ICON_NAMES.sheet,
195
+ },
196
+ '/app/emails': {
197
+ to: '/app/emails',
198
+ text: 'app.ai_inboxes',
199
+ iconName: COMMON_ICON_NAMES.ai_inbox,
200
+ requiredACL: 'ai_inbox_read',
201
+ },
202
+ '/app/outbound/forms': {
203
+ to: '/app/outbound/forms',
204
+ text: 'campaign.published_forms',
205
+ iconName: COMMON_ICON_NAMES.public_form,
206
+ },
207
+ '/app/outbound/emails': {
208
+ to: '/app/outbound/emails',
209
+ text: 'campaign.email_campaigns',
210
+ iconName: COMMON_ICON_NAMES.email_campaign,
211
+ },
212
+ '/app/downloads': {
213
+ to: '/app/downloads',
214
+ text: 'form.downloads',
215
+ iconName: 'download',
216
+ },
217
+ '/app/logs': {
218
+ to: '/app/logs',
219
+ text: 'log.all_logs',
220
+ iconName: COMMON_ICON_NAMES.logs,
221
+ },
222
+
223
+ // Arable
224
+
225
+ '/app/greenhouse': {
226
+ to: '/app/greenhouse',
227
+ text: 'log.greenhouse_seeding',
228
+ iconName: COMMON_ICON_NAMES.GREENHOUSE_SEEDING,
229
+
230
+ allowedOperations: ['ARABLE'],
231
+ },
232
+
233
+ '/app/seeding': {
234
+ to: '/app/seeding',
235
+ text: 'log.seeding',
236
+ iconName: COMMON_ICON_NAMES.seeding,
237
+
238
+ allowedOperations: ['ARABLE'],
239
+ },
240
+ '/app/transplanting': {
241
+ to: '/app/transplanting',
242
+ text: 'log.transplanting',
243
+ iconName: COMMON_ICON_NAMES.transplanting,
244
+
245
+ allowedOperations: ['ARABLE'],
246
+ },
247
+ '/app/field-work': {
248
+ to: '/app/field-work',
249
+ text: 'log.field_work',
250
+ iconName: COMMON_ICON_NAMES.field_work,
251
+
252
+ allowedOperations: ['ARABLE'],
253
+ },
254
+ '/app/harvested': {
255
+ to: '/app/harvested',
256
+ text: 'log.harvested',
257
+ iconName: COMMON_ICON_NAMES.harvest,
258
+
259
+ allowedOperations: ['ARABLE'],
260
+ },
261
+ '/app/post-harvest': {
262
+ to: '/app/post-harvest',
263
+ text: 'log.post_harvest',
264
+ iconName: COMMON_ICON_NAMES.post_harvest,
265
+
266
+ allowedOperations: ['ARABLE'],
267
+ },
268
+ '/app/purchases': {
269
+ to: '/app/purchases',
270
+ text: 'log.purchases',
271
+ iconName: COMMON_ICON_NAMES.invoice,
272
+
273
+ allowedOperations: OP.FARMING,
274
+ },
275
+ '/app/orders': {
276
+ to: '/app/orders',
277
+ text: 'form.sales_orders',
278
+ iconName: COMMON_ICON_NAMES.receipt,
279
+
280
+ allowedOperations: OP.FARMING,
281
+ },
282
+
283
+ // Farmers Market
284
+ '/app/vendors': {
285
+ to: '/app/vendors',
286
+ text: 'form.vendors',
287
+ iconName: COMMON_ICON_NAMES.shop_vendor,
288
+
289
+ allowedOperations: ['FARMERS_MARKET'],
290
+ },
291
+ '/app/receipts': {
292
+ to: '/app/receipts' as ValidRoutePath,
293
+ text: 'form.market_receipts',
294
+ iconName: COMMON_ICON_NAMES.market_receipt,
295
+
296
+ allowedOperations: ['FARMERS_MARKET'],
297
+ },
298
+
299
+ // Grower Network
300
+ '/app/growers': {
301
+ to: '/app/growers',
302
+ text: 'org.growers',
303
+ iconName: COMMON_ICON_NAMES.growers,
304
+
305
+ allowedOperations: OP.GROWER_NETWORK,
306
+ },
307
+
308
+ // FieldDocs
309
+
310
+ '/app/fd/': {
311
+ to: '/app/fd/',
312
+ text: 'form.field_docs',
313
+ iconName: COMMON_ICON_NAMES.generic_field_doc,
314
+ hasPhysicalToolbar: 'NEVER',
315
+ },
316
+ '/app/d/': {
317
+ to: '/app/d/',
318
+ text: 'form.data_tables',
319
+ iconName: COMMON_ICON_NAMES.data_table,
320
+ hasPhysicalToolbar: 'NEVER',
321
+ },
322
+ '/app/p/': {
323
+ to: '/app/p/',
324
+ text: 'form.field_docs',
325
+ iconName: COMMON_ICON_NAMES.generic_field_doc,
326
+ hasPhysicalToolbar: 'NEVER',
327
+ },
301
328
  };
302
329
 
303
330
  /**
@@ -307,12 +334,19 @@ const ROUTES_DICT: Record<ValidRoutePath, RouteDictObj> = {
307
334
  * @returns The full pathname for the route.
308
335
  */
309
336
 
310
- export function makePathname(routePath: ValidRoutePath, pathSegment?: string | null): ValidRoutePath {
311
- const pathExists = !!ROUTES_DICT[routePath];
312
- if (pathExists && routePath.endsWith('/')) {
313
- return (pathSegment ? `${routePath}${pathSegment}` : routePath.substring(0, routePath.length - 1)) as ValidRoutePath;
314
- }
315
- return pathExists ? routePath : '/app';
337
+ export function makePathname(
338
+ routePath: ValidRoutePath,
339
+ pathSegment?: string | null,
340
+ ): ValidRoutePath {
341
+ const pathExists = !!ROUTES_DICT[routePath];
342
+ if (pathExists && routePath.endsWith('/')) {
343
+ return (
344
+ pathSegment
345
+ ? `${routePath}${pathSegment}`
346
+ : routePath.substring(0, routePath.length - 1)
347
+ ) as ValidRoutePath;
348
+ }
349
+ return pathExists ? routePath : '/app';
316
350
  }
317
351
 
318
352
  /**
@@ -322,12 +356,12 @@ export function makePathname(routePath: ValidRoutePath, pathSegment?: string | n
322
356
  * @returns The full pathname for the route.
323
357
  */
324
358
 
325
- export function isRouteValid(routePath: ValidRoutePath, pathSegment?: string | null): boolean {
326
- const routeDict = !!ROUTES_DICT[routePath];
327
- return (
328
- !!routeDict &&
329
- (!routePath.endsWith('/') || !!pathSegment)
330
- );
359
+ export function isRouteValid(
360
+ routePath: ValidRoutePath,
361
+ pathSegment?: string | null,
362
+ ): boolean {
363
+ const routeDict = !!ROUTES_DICT[routePath];
364
+ return !!routeDict && (!routePath.endsWith('/') || !!pathSegment);
331
365
  }
332
366
 
333
367
  /**
@@ -337,373 +371,645 @@ export function isRouteValid(routePath: ValidRoutePath, pathSegment?: string | n
337
371
  * @returns The route name if found.
338
372
  */
339
373
 
340
- const ROUTES_DICT_ORDERED = Object.keys(ROUTES_DICT).sort((a, b) => b.length - a.length);
374
+ const ROUTES_DICT_ORDERED = Object.keys(ROUTES_DICT).sort(
375
+ (a, b) => b.length - a.length,
376
+ );
341
377
 
342
378
  interface RouteConfigObj extends Omit<RouteDictObj, 'hasPhysicalToolbar'> {
343
- routeName: ValidRoutePath;
344
- allowed: boolean;
345
- hasPhysicalToolbar: boolean;
379
+ routeName: ValidRoutePath;
380
+ allowed: boolean;
381
+ hasPhysicalToolbar: boolean;
346
382
  }
347
383
 
348
384
  export function getRouteConfigs(
349
- pathname: ValidRoutePath | string,
350
- operation?: OrganizationOperationEnum | null,
351
- orgFeatures?: OrganizationFeatureEnum[] | null,
352
- checkACLClient?: CheckACLClientFn | null,
385
+ pathname: ValidRoutePath | string,
386
+ operation?: OrganizationOperationEnum | null,
387
+ checkACLClient?: CheckACLClientFn | null,
353
388
  ): RouteConfigObj {
354
-
355
- for (const routeName of ROUTES_DICT_ORDERED) {
356
- if (pathname.startsWith(routeName)) {
357
-
358
- // Scroll position fix + breadcrumb / TOC cleanup on unmount
359
- // This will retain scroll position for deeper links,
360
- // ie. "/app/globalgap/2023/.." will be retained
361
-
362
- const routeDict = ROUTES_DICT[routeName as ValidRoutePath];
363
- const pathParts = pathname.split('/');
364
-
365
- const hasPhysicalToolbar = !!routeDict.hasPhysicalToolbar && routeDict.hasPhysicalToolbar !== 'NEVER' && (
366
- routeDict.hasPhysicalToolbar === 'ALWAYS' ||
367
- (typeof routeDict.hasPhysicalToolbar === 'function' && routeDict.hasPhysicalToolbar(pathParts))
368
- );
369
-
370
- return {
371
- ...routeDict,
372
- text: i18n.has(routeDict.text) ? i18n.t(routeDict.text) : routeDict.text,
373
- routeName: routeName as ValidRoutePath,
374
- allowed: isRouteAllowed(pathname, operation, orgFeatures, checkACLClient),
375
- hasPhysicalToolbar,
376
- };
377
- }
378
- }
379
-
380
- return {
381
- routeName: '/__unknown',
382
- allowed: false,
383
- hasPhysicalToolbar: false,
384
- } as any;
389
+ for (const routeName of ROUTES_DICT_ORDERED) {
390
+ if (pathname.startsWith(routeName)) {
391
+ // Scroll position fix + breadcrumb / TOC cleanup on unmount
392
+ // This will retain scroll position for deeper links,
393
+ // ie. "/app/globalgap/2023/.." will be retained
394
+
395
+ const routeDict = ROUTES_DICT[routeName as ValidRoutePath];
396
+ const pathParts = pathname.split('/');
397
+
398
+ const hasPhysicalToolbar =
399
+ !!routeDict.hasPhysicalToolbar &&
400
+ routeDict.hasPhysicalToolbar !== 'NEVER' &&
401
+ (routeDict.hasPhysicalToolbar === 'ALWAYS' ||
402
+ (typeof routeDict.hasPhysicalToolbar === 'function' &&
403
+ routeDict.hasPhysicalToolbar(pathParts)));
404
+
405
+ return {
406
+ ...routeDict,
407
+ text: i18n.has(routeDict.text)
408
+ ? i18n.t(routeDict.text)
409
+ : routeDict.text,
410
+ routeName: routeName as ValidRoutePath,
411
+ allowed: isRouteAllowed(pathname, operation, checkACLClient),
412
+ hasPhysicalToolbar,
413
+ };
414
+ }
415
+ }
416
+
417
+ return {
418
+ routeName: '/__unknown',
419
+ allowed: false,
420
+ hasPhysicalToolbar: false,
421
+ } as any;
385
422
  }
386
423
 
387
424
  /**
388
425
  * Check if this organization's operation allows access to this route path
389
426
  * @param pathname - pathname to check.
390
427
  * @param operation - Organization operation.
391
- * @param orgFeatures - Enabled features for organization.
392
428
  */
393
429
 
394
430
  export function isRouteAllowed(
395
- pathname: ValidRoutePath | string,
396
- operation?: OrganizationOperationEnum | null,
397
- orgFeatures?: OrganizationFeatureEnum[] | null,
398
- checkACLClient?: CheckACLClientFn | null,
431
+ pathname: ValidRoutePath | string,
432
+ operation?: OrganizationOperationEnum | null,
433
+ checkACLClient?: CheckACLClientFn | null,
399
434
  ): boolean {
400
-
401
- let routeDict = ROUTES_DICT[pathname as ValidRoutePath];
402
- if (!routeDict) {
403
- const parts = pathname.split('/');
404
- for (let i = parts.length; i > 0; i--) {
405
- const subPath = parts.slice(0, i).join('/');
406
-
407
- // @ts-ignore - sub paths may not be valid route paths
408
- routeDict = ROUTES_DICT[subPath] || ROUTES_DICT[subPath + '/'];
409
- if (routeDict || i <= 3) {
410
- break;
411
- }
412
- }
413
- }
414
-
415
- if (!routeDict) {
416
- // Assume true if there are no rules set
417
- return true;
418
- }
419
-
420
- return (
421
- (!routeDict.allowedOperations || routeDict.allowedOperations.includes(operation || '')) &&
422
- (!routeDict.notAllowedOperations || !routeDict.notAllowedOperations.includes(operation || '')) &&
423
- // If {orgFeature} is null, assume data is not finished loading yet, and allow "benefit of doubt" access
424
- (!orgFeatures || !routeDict.requiredFeature || routeDict.requiredFeature.some((feature) => orgFeatures.includes(feature))) &&
425
- (!routeDict.requiredACL || !checkACLClient || checkACLClient(routeDict.requiredACL))
426
- );
435
+ let routeDict = ROUTES_DICT[pathname as ValidRoutePath];
436
+ if (!routeDict) {
437
+ const parts = pathname.split('/');
438
+ for (let i = parts.length; i > 0; i--) {
439
+ const subPath = parts.slice(0, i).join('/');
440
+
441
+ // @ts-ignore - sub paths may not be valid route paths
442
+ routeDict = ROUTES_DICT[subPath] || ROUTES_DICT[subPath + '/'];
443
+ if (routeDict || i <= 3) {
444
+ break;
445
+ }
446
+ }
447
+ }
448
+
449
+ if (!routeDict) {
450
+ // Assume true if there are no rules set
451
+ return true;
452
+ }
453
+
454
+ return (
455
+ (!routeDict.allowedOperations ||
456
+ routeDict.allowedOperations.includes(operation || '')) &&
457
+ (!routeDict.notAllowedOperations ||
458
+ !routeDict.notAllowedOperations.includes(operation || '')) &&
459
+ (!routeDict.requiredACL ||
460
+ !checkACLClient ||
461
+ checkACLClient(routeDict.requiredACL))
462
+ );
427
463
  }
428
464
 
429
465
  /**
430
- * Helper; get static nav list based on organization's operation & features
466
+ * Helper; get static nav list based on the organization's operation.
431
467
  */
432
468
 
433
469
  interface NavListItem {
434
- break?: never;
435
- slug?: string;
436
- to: string;
437
- text: string;
438
- iconName?: string | null;
439
- };
470
+ break?: never;
471
+ slug?: string;
472
+ to: string;
473
+ text: string;
474
+ iconName?: string | null;
475
+ }
440
476
 
441
477
  interface NavBreakItem {
442
- break: boolean;
443
- to?: never;
444
- text?: never;
445
- iconName?: never;
446
- };
478
+ break: boolean;
479
+ to?: never;
480
+ text?: never;
481
+ iconName?: never;
482
+ }
447
483
 
448
484
  interface NavGroupItem {
449
- break?: never;
450
- to?: never;
451
- text: string;
452
- initialExpanded?: boolean;
453
- navList: (NavListItem | NavBreakItem)[];
454
- };
485
+ break?: never;
486
+ to?: never;
487
+ text: string;
488
+ initialExpanded?: boolean;
489
+ navList: (NavListItem | NavBreakItem)[];
490
+ }
455
491
 
456
492
  export type NavigationItem = NavListItem | NavBreakItem | NavGroupItem;
457
493
 
494
+ type RawNavigationItem =
495
+ | RouteDictObj
496
+ | { break: boolean }
497
+ | {
498
+ text: string;
499
+ initialExpanded?: boolean;
500
+ navList: RawNavigationItem[];
501
+ };
502
+
503
+ interface SidebarRouteFromSlugObj {
504
+ routePath: ValidRoutePath;
505
+ slug: string;
506
+ to: string;
507
+ }
508
+
509
+ export interface ClientRouteManifestItem {
510
+ parentId?: string;
511
+ path?: string;
512
+ }
513
+
514
+ /*
515
+ * Return a normalized sidebar slug without the optional app prefix.
516
+ */
517
+ function getNormalizedSidebarSlug(slug: string | null | undefined) {
518
+ return String(slug || '')
519
+ .trim()
520
+ .replace(/^\/?app\/?/, '')
521
+ .replace(/^\/+|\/+$/g, '');
522
+ }
523
+
458
524
  /*
459
- * Return the route dictionary key matching a customized sidebar slug.
525
+ * Return the current sidebar slug while translating legacy route prefixes.
460
526
  */
461
- function getRoutePathFromSidebarSlug(slug: string | null | undefined): ValidRoutePath | null {
462
- const normalizedSlug = String(slug || '').trim().replace(/^\/?app\/?/, '').replace(/^\/+|\/+$/g, '');
463
- const routePath = normalizedSlug === 'home' ? '/app' : `/app/${normalizedSlug}`;
527
+ export function normalizeSidebarRouteSlug(slug: string | null | undefined) {
528
+ const normalizedSlug = getNormalizedSidebarSlug(slug);
464
529
 
465
- return ROUTES_DICT[routePath as ValidRoutePath] ? routePath as ValidRoutePath : null;
530
+ return normalizedSlug.startsWith('r/')
531
+ ? `fd/${normalizedSlug.slice(2)}`
532
+ : normalizedSlug;
533
+ }
534
+
535
+ /*
536
+ * Return route metadata and renderable path for a customized sidebar slug.
537
+ */
538
+ function getSidebarRouteFromSlug(
539
+ slug: string | null | undefined,
540
+ ): SidebarRouteFromSlugObj | null {
541
+ const normalizedSlug = normalizeSidebarRouteSlug(slug);
542
+
543
+ if (!normalizedSlug) {
544
+ return null;
545
+ }
546
+
547
+ if (normalizedSlug === 'home') {
548
+ return {
549
+ routePath: '/app',
550
+ slug: 'home',
551
+ to: '/app',
552
+ };
553
+ }
554
+
555
+ const staticRoutePath = `/app/${normalizedSlug}` as ValidRoutePath;
556
+
557
+ if (ROUTES_DICT[staticRoutePath]) {
558
+ return {
559
+ routePath: staticRoutePath,
560
+ slug: normalizedSlug,
561
+ to: staticRoutePath,
562
+ };
563
+ }
564
+
565
+ const [baseSlug, ...pathSegments] = normalizedSlug.split('/');
566
+ const dynamicRoutePath = `/app/${baseSlug}/` as ValidRoutePath;
567
+
568
+ if (!pathSegments.length || !ROUTES_DICT[dynamicRoutePath]) {
569
+ return null;
570
+ }
571
+
572
+ return {
573
+ routePath: dynamicRoutePath,
574
+ slug: normalizedSlug,
575
+ to: `/app/${normalizedSlug}`,
576
+ };
577
+ }
578
+
579
+ /*
580
+ * Return every route path registered by the route helper.
581
+ */
582
+ export function getRouteHelperRoutePaths(): string[] {
583
+ return Object.keys(ROUTES_DICT);
584
+ }
585
+
586
+ /*
587
+ * Check whether one concrete path fits a client route pattern, including optional segments and splats.
588
+ */
589
+ function doesClientRoutePatternMatchPath(routePattern: string, path: string) {
590
+ const patternSegments = routePattern.split('/').filter(Boolean);
591
+ const pathSegments = path.split('/').filter(Boolean);
592
+
593
+ /*
594
+ * Match one pair of segment offsets, branching only when the pattern segment is optional.
595
+ */
596
+ function matchSegments(patternIndex: number, pathIndex: number): boolean {
597
+ if (patternIndex === patternSegments.length) {
598
+ return pathIndex === pathSegments.length;
599
+ }
600
+
601
+ const patternSegment = patternSegments[patternIndex];
602
+
603
+ if (patternSegment === '*') {
604
+ return true;
605
+ }
606
+
607
+ const optional = patternSegment.endsWith('?');
608
+ const requiredPatternSegment = optional
609
+ ? patternSegment.slice(0, -1)
610
+ : patternSegment;
611
+ const dynamic = requiredPatternSegment.startsWith(':');
612
+ const pathSegmentMatches =
613
+ pathIndex < pathSegments.length &&
614
+ (dynamic || requiredPatternSegment === pathSegments[pathIndex]);
615
+
616
+ if (optional) {
617
+ return (
618
+ matchSegments(patternIndex + 1, pathIndex) ||
619
+ (pathSegmentMatches && matchSegments(patternIndex + 1, pathIndex + 1))
620
+ );
621
+ }
622
+
623
+ return pathSegmentMatches && matchSegments(patternIndex + 1, pathIndex + 1);
624
+ }
625
+
626
+ return matchSegments(0, 0);
627
+ }
628
+
629
+ /*
630
+ * Throw when one route registered by the route helper is missing from the client route manifest.
631
+ */
632
+ export function assertRouteHelperRouteExists(
633
+ routePath: string,
634
+ routeManifest: Record<string, ClientRouteManifestItem> | null | undefined,
635
+ ) {
636
+ if (!routeManifest) {
637
+ throw new Error('The client route manifest is unavailable.');
638
+ }
639
+
640
+ const routePathsById = new Map<string, string>();
641
+ const pendingRoutes = Object.entries(routeManifest);
642
+ let previousPendingRouteCount = -1;
643
+
644
+ while (
645
+ pendingRoutes.length &&
646
+ pendingRoutes.length !== previousPendingRouteCount
647
+ ) {
648
+ previousPendingRouteCount = pendingRoutes.length;
649
+
650
+ for (let index = pendingRoutes.length - 1; index >= 0; index -= 1) {
651
+ const [routeId, route] = pendingRoutes[index];
652
+ const parentPath = route.parentId
653
+ ? routePathsById.get(route.parentId)
654
+ : '';
655
+
656
+ if (route.parentId && parentPath === undefined) {
657
+ continue;
658
+ }
659
+
660
+ const routePath = route.path?.startsWith('/')
661
+ ? route.path
662
+ : [parentPath, route.path].filter(Boolean).join('/');
663
+ routePathsById.set(routeId, `/${routePath}`.replace(/\/+/g, '/'));
664
+ pendingRoutes.splice(index, 1);
665
+ }
666
+ }
667
+
668
+ const clientRoutePatterns = Array.from(new Set(routePathsById.values()));
669
+ const samplePath = routePath.endsWith('/')
670
+ ? `${routePath}__route_helper_validation__`
671
+ : routePath;
672
+ const routeExists = clientRoutePatterns.some((routePattern) =>
673
+ doesClientRoutePatternMatchPath(routePattern, samplePath),
674
+ );
675
+
676
+ if (!routeExists) {
677
+ throw new Error(
678
+ `Route registered in ROUTES_DICT is missing from the client app: ${routePath}`,
679
+ );
680
+ }
466
681
  }
467
682
 
468
683
  /*
469
684
  * Return a stable sidebar slug for a route pathname.
470
685
  */
471
686
  function getSidebarSlugFromRoutePath(routePath: string | null | undefined) {
472
- if (routePath === '/app') {
473
- return 'home';
474
- }
687
+ if (routePath === '/app') {
688
+ return 'home';
689
+ }
475
690
 
476
- return String(routePath || '').replace(/^\/?app\/?/, '').replace(/^\/+|\/+$/g, '');
691
+ return normalizeSidebarRouteSlug(routePath);
477
692
  }
478
693
 
479
694
  /*
480
695
  * Resolve a customized sidebar item into a route-backed navigation item.
481
696
  */
482
697
  function getNavigationItemFromSidebarItem(
483
- item: OrganizationSidebarItemObj,
484
- operation: OrganizationOperationEnum | null,
485
- orgFeatures?: (OrganizationFeatureEnum | string)[],
486
- checkACLClient?: CheckACLClientFn | null,
698
+ item: OrganizationSidebarItemObj,
699
+ operation: OrganizationOperationEnum | null,
700
+ checkACLClient?: CheckACLClientFn | null,
487
701
  ): NavListItem | null {
488
- const routePath = getRoutePathFromSidebarSlug(item.slug);
702
+ if (item.kind && item.kind !== 'LINK') {
703
+ return null;
704
+ }
705
+
706
+ const route = getSidebarRouteFromSlug(item.slug);
707
+
708
+ if (!route || !isRouteAllowed(route.routePath, operation, checkACLClient)) {
709
+ return null;
710
+ }
711
+
712
+ const routeDict = ROUTES_DICT[route.routePath];
713
+ const fallbackText =
714
+ routeDict.text && i18n.has(routeDict.text)
715
+ ? i18n.t(routeDict.text)
716
+ : routeDict.text;
717
+
718
+ return {
719
+ slug: route.slug,
720
+ to: route.to,
721
+ text: item.label || fallbackText,
722
+ iconName: item.iconName || routeDict.iconName,
723
+ };
724
+ }
489
725
 
490
- if (!routePath || !isRouteAllowed(routePath, operation, orgFeatures, checkACLClient)) {
491
- return null;
492
- }
726
+ /*
727
+ * Return whether a navigation item is a visual break.
728
+ */
729
+ function isNavigationBreakItem(
730
+ item: NavigationItem | null,
731
+ ): item is NavBreakItem {
732
+ return !!item && 'break' in item && !!item.break;
733
+ }
493
734
 
494
- const routeDict = ROUTES_DICT[routePath];
495
- const fallbackText = routeDict.text && i18n.has(routeDict.text) ? i18n.t(routeDict.text) : routeDict.text;
735
+ /*
736
+ * Remove leading, trailing, and duplicate breaks from a navigation item list.
737
+ */
738
+ function getCleanNavigationBreaks<T extends NavigationItem>(navList: T[]) {
739
+ return navList
740
+ .reduce((acc, item) => {
741
+ if (!isNavigationBreakItem(item)) {
742
+ acc.push(item);
743
+ return acc;
744
+ }
745
+
746
+ const previousItem = acc[acc.length - 1];
747
+
748
+ if (previousItem && !isNavigationBreakItem(previousItem)) {
749
+ acc.push(item);
750
+ }
751
+
752
+ return acc;
753
+ }, [] as T[])
754
+ .filter((item, index, items) => {
755
+ return !isNavigationBreakItem(item) || index < items.length - 1;
756
+ });
757
+ }
496
758
 
497
- return {
498
- slug: getSidebarSlugFromRoutePath(routePath),
499
- to: routePath,
500
- text: item.label || fallbackText,
501
- iconName: item.iconName,
502
- };
759
+ /*
760
+ * Build a nested sidebar nav item from a customized group item.
761
+ */
762
+ function getNavigationGroupFromSidebarItem(
763
+ item: OrganizationSidebarItemObj,
764
+ operation: OrganizationOperationEnum | null,
765
+ checkACLClient?: CheckACLClientFn | null,
766
+ ): NavGroupItem | null {
767
+ if (item.kind !== 'GROUP') {
768
+ return null;
769
+ }
770
+
771
+ const navList = getCustomizedNestedNavigationList(
772
+ item.items,
773
+ operation,
774
+ checkACLClient,
775
+ );
776
+
777
+ return {
778
+ text: item.label || '',
779
+ navList,
780
+ };
503
781
  }
504
782
 
505
783
  /*
506
- * Build the customized organization sidebar from settings.sidebar groups.
784
+ * Build a renderable sidebar item from a customized organization sidebar item.
785
+ */
786
+ function getNavigationItemFromCustomSidebarItem(
787
+ item: OrganizationSidebarItemObj,
788
+ operation: OrganizationOperationEnum | null,
789
+ checkACLClient?: CheckACLClientFn | null,
790
+ ): NavigationItem | null {
791
+ if (item.kind === 'BREAK') {
792
+ return {
793
+ break: true,
794
+ };
795
+ }
796
+
797
+ if (item.kind === 'GROUP') {
798
+ return getNavigationGroupFromSidebarItem(item, operation, checkACLClient);
799
+ }
800
+
801
+ return getNavigationItemFromSidebarItem(item, operation, checkACLClient);
802
+ }
803
+
804
+ /*
805
+ * Build nested link and break navigation items from a customized group item.
806
+ */
807
+ function getCustomizedNestedNavigationList(
808
+ sidebar: OrganizationSidebarItemObj[] | null | undefined,
809
+ operation: OrganizationOperationEnum | null,
810
+ checkACLClient?: CheckACLClientFn | null,
811
+ ): (NavListItem | NavBreakItem)[] {
812
+ if (!Array.isArray(sidebar)) {
813
+ return [];
814
+ }
815
+
816
+ const navList = sidebar.reduce(
817
+ (acc, item) => {
818
+ const navItem =
819
+ item.kind === 'GROUP'
820
+ ? null
821
+ : getNavigationItemFromCustomSidebarItem(
822
+ item,
823
+ operation,
824
+ checkACLClient,
825
+ );
826
+
827
+ if (navItem && !('navList' in navItem)) {
828
+ acc.push(navItem);
829
+ }
830
+
831
+ return acc;
832
+ },
833
+ [] as (NavListItem | NavBreakItem)[],
834
+ );
835
+
836
+ return getCleanNavigationBreaks(navList);
837
+ }
838
+
839
+ /*
840
+ * Build the customized organization sidebar from settings.sidebar items.
507
841
  */
508
842
  function getCustomizedNavigationList(
509
- sidebar: OrganizationSidebarGroupObj[],
510
- operation: OrganizationOperationEnum | null,
511
- orgFeatures?: (OrganizationFeatureEnum | string)[],
512
- checkACLClient?: CheckACLClientFn | null,
843
+ sidebar: OrganizationSidebarItemObj[],
844
+ operation: OrganizationOperationEnum | null,
845
+ checkACLClient?: CheckACLClientFn | null,
513
846
  ): NavigationItem[] {
514
- return sidebar.reduce((acc, group) => {
515
- const navList = Array.isArray(group?.items)
516
- ? group.items.reduce((items, item) => {
517
- const navItem = getNavigationItemFromSidebarItem(item, operation, orgFeatures, checkACLClient);
518
- if (navItem) {
519
- items.push(navItem);
520
- }
521
- return items;
522
- }, [] as NavListItem[])
523
- : [];
524
-
525
- if (navList.length) {
526
- acc.push({
527
- text: group?.title || '',
528
- navList,
529
- });
530
- }
531
-
532
- return acc;
533
- }, [] as NavigationItem[]);
847
+ const navList = sidebar.reduce((acc, item) => {
848
+ const navItem = getNavigationItemFromCustomSidebarItem(
849
+ item,
850
+ operation,
851
+ checkACLClient,
852
+ );
853
+
854
+ if (navItem) {
855
+ acc.push(navItem);
856
+ }
857
+
858
+ return acc;
859
+ }, [] as NavigationItem[]);
860
+
861
+ return getCleanNavigationBreaks(navList);
534
862
  }
535
863
 
864
+ /*
865
+ * Map raw route dictionary items into sidebar navigation items allowed for this organization.
866
+ */
867
+ function mapNavigationList(
868
+ navListArr: RawNavigationItem[],
869
+ operation: OrganizationOperationEnum | null,
870
+ checkACLClient?: CheckACLClientFn | null,
871
+ ): NavigationItem[] {
872
+ /*
873
+ * Convert one raw sidebar item into a renderable item, filtering inaccessible routes.
874
+ */
875
+ const mapNavItems = (item: any) => {
876
+ if (item?.navList) {
877
+ item.navList = item.navList.reduce((acc: any[], x: any, i: number) => {
878
+ const mappedItem = mapNavItems(x);
879
+ if (
880
+ mappedItem &&
881
+ (mappedItem.to || (acc.length && i !== item.navList.length - 1))
882
+ ) {
883
+ if (mappedItem.text && i18n.has(mappedItem.text)) {
884
+ mappedItem.text = i18n.t(mappedItem.text);
885
+ }
886
+ acc.push(mappedItem);
887
+ }
888
+ return acc;
889
+ }, []);
890
+
891
+ if (!item.navList.length) {
892
+ return null;
893
+ }
894
+ } else if (
895
+ item?.to &&
896
+ !isRouteAllowed(item.to, operation, checkACLClient)
897
+ ) {
898
+ return null;
899
+ }
900
+
901
+ if (item?.to) {
902
+ item.slug = getSidebarSlugFromRoutePath(item.to);
903
+ }
904
+
905
+ if (item?.text && i18n.has(item.text)) {
906
+ item.text = i18n.t(item.text);
907
+ }
908
+
909
+ return item;
910
+ };
911
+
912
+ return navListArr.map(mapNavItems).filter(Boolean);
913
+ }
914
+
915
+ /*
916
+ * Return the default operation-specific sidebar list without pinned Home or Workspace links.
917
+ */
918
+ export function getDefaultNav(
919
+ operation: OrganizationOperationEnum | null,
920
+ checkACLClient?: CheckACLClientFn | null,
921
+ ): NavigationItem[] {
922
+ const breakItem = {
923
+ break: true,
924
+ };
925
+
926
+ let navListArr: RawNavigationItem[] = [];
927
+
928
+ switch (operation) {
929
+ case 'ARABLE':
930
+ navListArr = [
931
+ {
932
+ text: i18n.t(`org.type_active.${operation}`),
933
+ navList: [
934
+ ROUTES_DICT['/app/greenhouse'],
935
+ ROUTES_DICT['/app/seeding'],
936
+ ROUTES_DICT['/app/transplanting'],
937
+ ROUTES_DICT['/app/field-work'],
938
+ ROUTES_DICT['/app/harvested'],
939
+ ROUTES_DICT['/app/post-harvest'],
940
+
941
+ breakItem,
942
+
943
+ ROUTES_DICT['/app/purchases'],
944
+ ROUTES_DICT['/app/orders'],
945
+ ],
946
+ },
947
+ ];
948
+ break;
949
+ case 'FARMERS_MARKET':
950
+ navListArr = [
951
+ {
952
+ text: i18n.t(`org.type_active.${operation}`),
953
+ navList: [ROUTES_DICT['/app/vendors'], ROUTES_DICT['/app/receipts']],
954
+ },
955
+ ];
956
+ break;
957
+ case 'GROWER_NETWORK':
958
+ navListArr = [
959
+ {
960
+ text: i18n.t(`org.type_active.${operation}`),
961
+ navList: [ROUTES_DICT['/app/growers']],
962
+ },
963
+ ];
964
+ break;
965
+ default:
966
+ navListArr = [];
967
+ }
968
+
969
+ navListArr = navListArr.concat([
970
+ {
971
+ text: i18n.t('form.advanced'),
972
+ initialExpanded: true,
973
+ navList: [
974
+ // ROUTES_DICT['/app/calendar'],
975
+ ROUTES_DICT['/app/workflows'],
976
+ // ROUTES_DICT['/app/emails'],
977
+ // ROUTES_DICT['/app/downloads'],
978
+ // ROUTES_DICT['/app/outbound/forms'],
979
+ // ROUTES_DICT['/app/outbound/emails'],
980
+ ROUTES_DICT['/app/logs'],
981
+ ],
982
+ },
983
+ ]);
984
+
985
+ return mapNavigationList(navListArr, operation, checkACLClient);
986
+ }
987
+
988
+ /*
989
+ * Return the sidebar navigation list with Home and Workspace pinned before customized or default items.
990
+ */
536
991
  export function getNavigationList(
537
- operation: OrganizationOperationEnum | null,
538
- orgFeatures?: (OrganizationFeatureEnum | string)[], // This array contains available report groups also
539
- reportGroups?: ReportGroupGQL[] | null,
540
- dataTables?: DataTableGQL[] | null,
541
- checkACLClient?: CheckACLClientFn | null,
542
- sidebar?: OrganizationSidebarGroupObj[] | null,
992
+ operation: OrganizationOperationEnum | null,
993
+ checkACLClient?: CheckACLClientFn | null,
994
+ sidebar?: OrganizationSidebarItemObj[] | null,
543
995
  ): NavigationItem[] {
544
- if (Array.isArray(sidebar)) {
545
- return getCustomizedNavigationList(sidebar, operation, orgFeatures, checkACLClient);
546
- }
547
-
548
- const breakItem = {
549
- break: true,
550
- };
551
-
552
- let navListArr: {
553
- text: string;
554
- initialExpanded?: boolean;
555
- navList: (RouteDictObj | { break: boolean })[];
556
- }[] = [];
557
-
558
- switch (operation) {
559
- case 'ARABLE':
560
- navListArr = [
561
- {
562
- text: i18n.t(`org.type_active.${operation}`),
563
- navList: [
564
- ROUTES_DICT['/app/greenhouse'],
565
- ROUTES_DICT['/app/seeding'],
566
- ROUTES_DICT['/app/transplanting'],
567
- ROUTES_DICT['/app/field-work'],
568
- ROUTES_DICT['/app/harvested'],
569
- ROUTES_DICT['/app/post-harvest'],
570
-
571
- breakItem,
572
-
573
- ROUTES_DICT['/app/purchases'],
574
- ROUTES_DICT['/app/orders'],
575
- ]
576
- },
577
- ];
578
- break;
579
- case 'LIVESTOCK':
580
- navListArr = [
581
- {
582
- text: i18n.t(`org.type_active.${operation}`),
583
- navList: [
584
- { ...ROUTES_DICT['/app/purchases'], text: i18n.t('log.supply_purchases') },
585
- ]
586
- },
587
- ];
588
- break;
589
- case 'FARMERS_MARKET':
590
- navListArr = [
591
- {
592
- text: i18n.t(`org.type_active.${operation}`),
593
- navList: [
594
- ROUTES_DICT['/app/vendors'],
595
- // ROUTES_DICT['/app/markets'],
596
- ROUTES_DICT['/app/receipts'],
597
- ]
598
- },
599
- ];
600
- break;
601
- case 'GROWER_NETWORK':
602
- navListArr = [
603
- {
604
- text: i18n.t(`org.type_active.${operation}`),
605
- navList: [
606
- ROUTES_DICT['/app/growers'],
607
- ROUTES_DICT['/app/foreign-growers'],
608
- ]
609
- }
610
- ];
611
- break;
612
- default:
613
- navListArr = [];
614
- }
615
-
616
- // Report sections
617
-
618
- const reportsSection = {
619
- text: i18n.t('form.reports'),
620
- navList: [
621
- ]
622
- };
623
-
624
- if (reportGroups) {
625
- // @ts-ignore
626
- reportsSection.navList = reportsSection.navList.concat(reportGroups.map((reportGroup) => ({
627
- to: makePathname('/app/r/', reportGroup.id),
628
- text: reportGroup.shortName || reportGroup.name,
629
- iconName: COMMON_ICON_NAMES.generic_report,
630
- })));
631
- }
632
-
633
- if (reportsSection.navList.length) {
634
- navListArr.push(reportsSection);
635
- }
636
-
637
- if (dataTables) {
638
- const dataTablesSection = {
639
- text: i18n.t('form.dataTables'),
640
- navList: dataTables.map((dataTable) => ({
641
- to: makePathname('/app/d/', dataTable.id),
642
- text: dataTable.title || dataTable.name,
643
- iconName: COMMON_ICON_NAMES.data_table,
644
- })),
645
- };
646
-
647
- navListArr.push(dataTablesSection);
648
- }
649
-
650
- // @ts-ignore
651
- navListArr = [{
652
- ...ROUTES_DICT['/app'],
653
- iconName: COMMON_ICON_NAMES[operation!] || 'home',
654
- },
655
- breakItem,
656
- // @ts-ignore
657
- ].concat(navListArr).concat([{
658
- text: i18n.t('form.advanced'),
659
- initialExpanded: true,
660
- navList: [
661
- ROUTES_DICT['/app/workflows'],
662
- // ROUTES_DICT['/app/sheets'],
663
- // ROUTES_DICT['/app/emails'],
664
- ROUTES_DICT['/app/logs']
665
- ]
666
- }] as any);
667
-
668
- const mapNavItems = (item: any) => {
669
- if (Array.isArray(item)) {
670
- const [navItem, ...requiredFeatures] = item;
671
- if (requiredFeatures.some(feature => orgFeatures?.includes?.(feature))) {
672
- return navItem;
673
- }
674
- return null;
675
- } else if (item?.navList) {
676
- item.navList = item.navList.reduce((acc: any[], x: any, i: number) => {
677
- const mappedItem = mapNavItems(x);
678
- if (
679
- mappedItem &&
680
- (mappedItem.to || (acc.length && i !== (item.navList.length - 1)))
681
- ) {
682
- if (mappedItem.text && i18n.has(mappedItem.text)) {
683
- mappedItem.text = i18n.t(mappedItem.text);
684
- }
685
- acc.push(mappedItem);
686
- }
687
- return acc;
688
- }, []);
689
-
690
- if (!item.navList.length) {
691
- return null;
692
- }
693
- } else if (item?.to && !isRouteAllowed(item.to, operation, orgFeatures, checkACLClient)) {
694
- return null;
695
- }
696
-
697
- if (item?.to) {
698
- item.slug = getSidebarSlugFromRoutePath(item.to);
699
- }
700
-
701
- if (item?.text && i18n.has(item.text)) {
702
- item.text = i18n.t(item.text);
703
- }
704
-
705
- return item;
706
- };
707
-
708
- return navListArr.map(mapNavItems).filter(Boolean);
996
+ const breakItem = { break: true };
997
+ const pinnedNavList = mapNavigationList(
998
+ [
999
+ {
1000
+ ...ROUTES_DICT['/app'],
1001
+ iconName: COMMON_ICON_NAMES[operation!] || 'home',
1002
+ },
1003
+ ROUTES_DICT['/app/workspace'],
1004
+ breakItem,
1005
+ ],
1006
+ operation,
1007
+ checkACLClient,
1008
+ );
1009
+
1010
+ const remainingNavList = Array.isArray(sidebar)
1011
+ ? getCustomizedNavigationList(sidebar, operation, checkACLClient)
1012
+ : getDefaultNav(operation, checkACLClient);
1013
+
1014
+ return pinnedNavList.concat(remainingNavList);
709
1015
  }