@jsb188/mday-web 1.1.8 → 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.
@@ -1,285 +1,330 @@
1
- import i18n from '@jsb188/app/i18n';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type {
3
+ OrganizationOperationEnum,
4
+ OrganizationSidebarItemObj,
5
+ } from '@jsb188/mday/types/organization.d.ts';
6
+ import type { OperationName } from '@jsb188/mday/utils/organization.ts';
2
7
  import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
3
- import type { OrganizationFeatureEnum, OrganizationOperationEnum } from '../types/organization.d';
4
8
 
5
- // Use this for report periods, etc
6
- const CURRENT_YEAR = String(new Date().getFullYear());
9
+ // Use this for fieldDoc periods, etc
10
+ // const CURRENT_YEAR = String(new Date().getFullYear());
7
11
 
8
12
  /**
9
13
  * Constants; Re-usable rules
10
14
  */
11
15
 
12
- const OP_FARMING = ['ARABLE', 'LIVESTOCK'];
13
-
14
- const F = {
15
- normal_logging: ['NORMAL_LOGGING'],
16
- food_safety: ['FOOD_SAFETY', 'GLOBAL_GAP'],
16
+ const OP = {
17
+ FARMING: ['ARABLE'],
18
+ GROWER_NETWORK: ['GROWER_NETWORK'],
17
19
  };
18
20
 
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
+ }
42
+
19
43
  /**
20
44
  * Rules
21
45
  */
22
46
 
23
47
  type ValidRoutePath =
24
- '/app'
25
- | '/app/c/'
26
- | '/app/ai-workflows'
27
- | '/app/logs'
28
- | '/app/seeding'
29
- | '/app/transplanting'
30
- | '/app/field-work'
31
- | '/app/harvested'
32
- | '/app/post-harvest'
33
- | '/app/orders'
34
- | '/app/globalgap/'
35
- | '/app/cleaning'
36
- | '/app/purchases'
37
- | '/app/organic'
38
- | '/app/hygiene'
39
- | '/app/sanitation'
40
- | '/app/materials'
41
- | '/app/biosecurity'
42
- | '/app/employees'
43
- | '/app/vendors'
44
- | '/app/markets'
45
- | '/app/receipts'
46
- | '/app/livestock'
47
- | '/app/growers'
48
- | '/app/foreign-growers';
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/';
49
77
 
50
78
  interface RouteDictObj {
51
- to: ValidRoutePath;
52
- text: string;
53
- iconName?: string;
54
- allowedOperations?: OrganizationOperationEnum[];
55
- notAllowedOperations?: OrganizationOperationEnum[];
56
- requiredFeature?: OrganizationFeatureEnum[];
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);
87
+ }
88
+
89
+ type CheckACLClientFn = (opName: OperationName) => boolean;
57
90
 
58
- // These values prevent rendering flickers when calculating TOC/breadcrumbs between page renders
59
- hasPhysicalToolbar?: 'ALWAYS' | 'NEVER' | ((parts: string[]) => boolean);
60
- hasAsideNav?: 'ALWAYS' | 'NEVER' | ((parts: string[]) => boolean);
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
+ }
61
119
  }
62
120
 
63
- const ROUTES_DICT: Record<ValidRoutePath, RouteDictObj> = {
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
+ );
64
145
 
65
- // Main /app/ routes
66
-
67
- '/app': {
68
- to: '/app',
69
- text: 'app.home',
70
- },
71
-
72
- '/app/c/': {
73
- to: '/app/c/',
74
- text: 'app.route_ai_chat',
75
- iconName: COMMON_ICON_NAMES.chat,
76
-
77
- hasPhysicalToolbar: 'ALWAYS',
78
- hasAsideNav: 'NEVER',
79
- },
80
-
81
- // Advanced
82
-
83
- '/app/ai-workflows': {
84
- to: '/app/ai-workflows',
85
- text: 'form.ai_workflows',
86
- iconName: COMMON_ICON_NAMES.ai_workflow,
87
- },
88
-
89
- '/app/logs': {
90
- to: '/app/logs',
91
- text: 'log.all_logs',
92
- iconName: COMMON_ICON_NAMES.logs,
93
- notAllowedOperations: ['GROWER_NETWORK'], // Temporary for now
94
- },
95
-
96
- // Arable
97
-
98
- '/app/seeding': {
99
- to: '/app/seeding',
100
- text: 'log.seeding',
101
- iconName: COMMON_ICON_NAMES.seeding,
102
-
103
- allowedOperations: ['ARABLE'],
104
- requiredFeature: F.normal_logging,
105
- },
106
- '/app/transplanting': {
107
- to: '/app/transplanting',
108
- text: 'log.transplanting',
109
- iconName: COMMON_ICON_NAMES.transplanting,
110
-
111
- allowedOperations: ['ARABLE'],
112
- requiredFeature: F.normal_logging,
113
- },
114
- '/app/field-work': {
115
- to: '/app/field-work',
116
- text: 'log.field_work',
117
- iconName: COMMON_ICON_NAMES.field_work,
118
-
119
- allowedOperations: ['ARABLE'],
120
- requiredFeature: F.normal_logging,
121
- },
122
- '/app/harvested': {
123
- to: '/app/harvested',
124
- text: 'log.harvested',
125
- iconName: COMMON_ICON_NAMES.harvest,
126
-
127
- allowedOperations: ['ARABLE'],
128
- requiredFeature: F.normal_logging,
129
- },
130
- '/app/post-harvest': {
131
- to: '/app/post-harvest',
132
- text: 'log.post_harvest',
133
- iconName: COMMON_ICON_NAMES.post_harvest,
134
-
135
- allowedOperations: ['ARABLE'],
136
- requiredFeature: F.normal_logging,
137
- },
138
- '/app/purchases': {
139
- to: '/app/purchases',
140
- text: 'log.purchases',
141
- iconName: COMMON_ICON_NAMES.invoice,
142
-
143
- allowedOperations: OP_FARMING,
144
- requiredFeature: F.normal_logging,
145
- },
146
- '/app/orders': {
147
- to: '/app/orders',
148
- text: 'form.sales_orders',
149
- iconName: COMMON_ICON_NAMES.receipt,
150
-
151
- allowedOperations: OP_FARMING,
152
- requiredFeature: F.normal_logging,
153
- },
154
-
155
- // Arable; Reports
156
-
157
- '/app/globalgap/': {
158
- to: ('/app/globalgap/' + CURRENT_YEAR) as ValidRoutePath,
159
- text: 'product.report.GLOBAL_GAP',
160
- iconName: COMMON_ICON_NAMES.generic_report,
161
-
162
- allowedOperations: OP_FARMING,
163
- requiredFeature: ['GLOBAL_GAP'],
164
-
165
- hasPhysicalToolbar: (parts: string[]) => parts.length > 4,
166
- hasAsideNav: (parts: string[]) => parts.length > 4,
167
- },
168
- '/app/cleaning': {
169
- to: '/app/cleaning',
170
- text: 'product.report.CLEANING',
171
- iconName: COMMON_ICON_NAMES.SANITATION,
172
-
173
- allowedOperations: OP_FARMING,
174
- requiredFeature: F.food_safety,
175
- },
176
- '/app/organic': {
177
- to: '/app/organic',
178
- text: 'product.report.ORGANIC_CERTIFICATION',
179
- iconName: COMMON_ICON_NAMES.generic_report,
180
-
181
- allowedOperations: OP_FARMING,
182
- requiredFeature: ['ORGANIC_CERTIFICATION'],
183
-
184
- // This will need to change later if we're introducing "period" table of contents page selection
185
- hasPhysicalToolbar: 'ALWAYS',
186
- hasAsideNav: 'ALWAYS',
187
- },
188
-
189
- // Arable; Food Safety
190
-
191
- '/app/hygiene': {
192
- to: '/app/hygiene',
193
- text: 'log.hygiene',
194
- iconName: COMMON_ICON_NAMES.HYGIENE,
195
-
196
- allowedOperations: OP_FARMING,
197
- requiredFeature: F.food_safety,
198
- },
199
- '/app/sanitation': {
200
- to: '/app/sanitation',
201
- text: 'log.sanitation',
202
- iconName: COMMON_ICON_NAMES.SANITATION,
203
-
204
- allowedOperations: OP_FARMING,
205
- requiredFeature: F.food_safety,
206
- },
207
- '/app/materials': {
208
- to: '/app/materials',
209
- text: 'log.materials',
210
- iconName: COMMON_ICON_NAMES.MATERIALS,
211
-
212
- allowedOperations: OP_FARMING,
213
- requiredFeature: F.food_safety,
214
- },
215
- '/app/biosecurity': {
216
- to: '/app/biosecurity',
217
- text: 'log.biosecurity',
218
- iconName: COMMON_ICON_NAMES.BIOSECURITY,
219
-
220
- allowedOperations: OP_FARMING,
221
- requiredFeature: F.food_safety,
222
- },
223
- '/app/employees': {
224
- to: '/app/employees',
225
- text: 'log.employees',
226
- iconName: COMMON_ICON_NAMES.EMPLOYEES,
227
-
228
- allowedOperations: OP_FARMING,
229
- requiredFeature: F.food_safety,
230
- },
231
-
232
- // Farmers Market
233
- '/app/vendors': {
234
- to: '/app/vendors',
235
- text: 'form.vendors',
236
- iconName: COMMON_ICON_NAMES.shop_vendor,
237
-
238
- allowedOperations: ['FARMERS_MARKET'],
239
- requiredFeature: F.normal_logging
240
- },
241
- '/app/markets': {
242
- to: '/app/markets',
243
- text: 'form.markets',
244
- iconName: COMMON_ICON_NAMES.shop_market,
245
-
246
- allowedOperations: ['FARMERS_MARKET'],
247
- requiredFeature: ['CAL_EVENTS'],
248
- },
249
- '/app/receipts': {
250
- to: ('/app/receipts?s=1') as ValidRoutePath,
251
- text: 'form.market_receipts',
252
- iconName: COMMON_ICON_NAMES.market_receipt,
253
-
254
- allowedOperations: ['FARMERS_MARKET'],
255
- requiredFeature: F.normal_logging
256
- },
257
-
258
- // Livestock
259
- '/app/livestock': {
260
- to: '/app/livestock',
261
- text: 'form.livestock',
262
- iconName: COMMON_ICON_NAMES.livestock,
263
-
264
- allowedOperations: ['LIVESTOCK'],
265
- requiredFeature: F.normal_logging
266
- },
267
-
268
- // Grower Network
269
- '/app/growers': {
270
- to: '/app/growers',
271
- text: 'form.domestic_growers',
272
- iconName: COMMON_ICON_NAMES.growers,
273
-
274
- allowedOperations: ['GROWER_NETWORK'],
275
- },
276
- '/app/foreign-growers': {
277
- to: '/app/foreign-growers',
278
- text: 'form.foreign_growers',
279
- iconName: COMMON_ICON_NAMES.foreign_growers,
280
-
281
- allowedOperations: ['GROWER_NETWORK'],
282
- },
146
+ return stableRoute || pathname;
147
+ }
148
+
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
+ },
283
328
  };
284
329
 
285
330
  /**
@@ -289,12 +334,19 @@ const ROUTES_DICT: Record<ValidRoutePath, RouteDictObj> = {
289
334
  * @returns The full pathname for the route.
290
335
  */
291
336
 
292
- export function makePathname(routePath: ValidRoutePath, pathSegment?: string | null): ValidRoutePath {
293
- const pathExists = !!ROUTES_DICT[routePath];
294
- if (pathExists && routePath.endsWith('/')) {
295
- return (pathSegment ? `${routePath}${pathSegment}` : routePath.substring(0, routePath.length - 1)) as ValidRoutePath;
296
- }
297
- 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';
298
350
  }
299
351
 
300
352
  /**
@@ -304,12 +356,12 @@ export function makePathname(routePath: ValidRoutePath, pathSegment?: string | n
304
356
  * @returns The full pathname for the route.
305
357
  */
306
358
 
307
- export function isRouteValid(routePath: ValidRoutePath, pathSegment?: string | null): boolean {
308
- const routeDict = !!ROUTES_DICT[routePath];
309
- return (
310
- !!routeDict &&
311
- (!routePath.endsWith('/') || !!pathSegment)
312
- );
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);
313
365
  }
314
366
 
315
367
  /**
@@ -319,284 +371,645 @@ export function isRouteValid(routePath: ValidRoutePath, pathSegment?: string | n
319
371
  * @returns The route name if found.
320
372
  */
321
373
 
322
- 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
+ );
323
377
 
324
- interface RouteConfigObj extends Omit<RouteDictObj, 'hasPhysicalToolbar' | 'hasAsideNav'> {
325
- routeName: ValidRoutePath;
326
- scrollResetKey: string;
327
- allowed: boolean;
328
- hasPhysicalToolbar: boolean;
329
- hasAsideNav: boolean;
378
+ interface RouteConfigObj extends Omit<RouteDictObj, 'hasPhysicalToolbar'> {
379
+ routeName: ValidRoutePath;
380
+ allowed: boolean;
381
+ hasPhysicalToolbar: boolean;
330
382
  }
331
383
 
332
384
  export function getRouteConfigs(
333
- pathname: ValidRoutePath | string,
334
- operation?: OrganizationOperationEnum | null,
335
- orgFeatures?: OrganizationFeatureEnum[] | null,
385
+ pathname: ValidRoutePath | string,
386
+ operation?: OrganizationOperationEnum | null,
387
+ checkACLClient?: CheckACLClientFn | null,
336
388
  ): RouteConfigObj {
337
-
338
- for (const routeName of ROUTES_DICT_ORDERED) {
339
- if (pathname.startsWith(routeName)) {
340
-
341
- // Scroll position fix + breadcrumb / TOC cleanup on unmount
342
- // This will retain scroll position for deeper links,
343
- // ie. "/app/globalgap/2023/.." will be retained
344
-
345
- const routeDict = ROUTES_DICT[routeName as ValidRoutePath];
346
- const pathParts = pathname.split('/');
347
-
348
- let scrollResetKey: string;
349
- if (pathParts.length >= 3) {
350
- // scroll reset key here is full path minus last part
351
- scrollResetKey = pathParts.slice(0, pathParts.length - 1).join('/');
352
- } else {
353
- scrollResetKey = pathParts.slice(0, 3).join('/');
354
- }
355
-
356
- const hasAsideNav = !!routeDict.hasAsideNav && routeDict.hasAsideNav !== 'NEVER' && (
357
- routeDict.hasAsideNav === 'ALWAYS' ||
358
- (typeof routeDict.hasAsideNav === 'function' && routeDict.hasAsideNav(pathParts))
359
- );
360
-
361
- const hasPhysicalToolbar = !!routeDict.hasPhysicalToolbar && routeDict.hasPhysicalToolbar !== 'NEVER' && (
362
- routeDict.hasPhysicalToolbar === 'ALWAYS' ||
363
- (typeof routeDict.hasPhysicalToolbar === 'function' && routeDict.hasPhysicalToolbar(pathParts))
364
- );
365
-
366
- return {
367
- ...routeDict,
368
- text: i18n.has(routeDict.text) ? i18n.t(routeDict.text) : routeDict.text,
369
- routeName: routeName as ValidRoutePath,
370
- scrollResetKey,
371
- allowed: isRouteAllowed(pathname, operation, orgFeatures),
372
- hasPhysicalToolbar,
373
- hasAsideNav,
374
- };
375
- }
376
- }
377
-
378
- return {
379
- routeName: '/__unknown',
380
- scrollResetKey: '',
381
- allowed: false,
382
- hasPhysicalToolbar: false,
383
- hasAsideNav: 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,
431
+ pathname: ValidRoutePath | string,
432
+ operation?: OrganizationOperationEnum | null,
433
+ checkACLClient?: CheckACLClientFn | null,
398
434
  ): boolean {
399
-
400
- let routeDict = ROUTES_DICT[pathname as ValidRoutePath];
401
- if (!routeDict) {
402
- const parts = pathname.split('/');
403
- for (let i = parts.length; i > 0; i--) {
404
- const subPath = parts.slice(0, i).join('/');
405
-
406
- // @ts-ignore - sub paths may not be valid route paths
407
- routeDict = ROUTES_DICT[subPath] || ROUTES_DICT[subPath + '/'];
408
- if (routeDict || i <= 3) {
409
- break;
410
- }
411
- }
412
- }
413
-
414
- if (!routeDict) {
415
- // Assume true if there are no rules set
416
- return true;
417
- }
418
-
419
- return (
420
- (!routeDict.allowedOperations || routeDict.allowedOperations.includes(operation || '')) &&
421
- (!routeDict.notAllowedOperations || !routeDict.notAllowedOperations.includes(operation || '')) &&
422
- // If {orgFeature} is null, assume data is not finished loading yet, and allow "benefit of doubt" access
423
- (!orgFeatures || !routeDict.requiredFeature || routeDict.requiredFeature.some((feature) => orgFeatures.includes(feature)))
424
- );
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
+ );
425
463
  }
426
464
 
427
465
  /**
428
- * Helper; because i18n isn't registered when this file opens, we gotta do this
466
+ * Helper; get static nav list based on the organization's operation.
429
467
  */
430
468
 
431
- function routesDictI18n(routeDictObj: RouteDictObj) {
432
- return {
433
- ...routeDictObj,
434
- text: i18n.t(routeDictObj.text),
435
- };
469
+ interface NavListItem {
470
+ break?: never;
471
+ slug?: string;
472
+ to: string;
473
+ text: string;
474
+ iconName?: string | null;
436
475
  }
437
476
 
438
- /**
439
- * Helper; get static nav list based on organization's operation & features
477
+ interface NavBreakItem {
478
+ break: boolean;
479
+ to?: never;
480
+ text?: never;
481
+ iconName?: never;
482
+ }
483
+
484
+ interface NavGroupItem {
485
+ break?: never;
486
+ to?: never;
487
+ text: string;
488
+ initialExpanded?: boolean;
489
+ navList: (NavListItem | NavBreakItem)[];
490
+ }
491
+
492
+ export type NavigationItem = NavListItem | NavBreakItem | NavGroupItem;
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.
440
516
  */
517
+ function getNormalizedSidebarSlug(slug: string | null | undefined) {
518
+ return String(slug || '')
519
+ .trim()
520
+ .replace(/^\/?app\/?/, '')
521
+ .replace(/^\/+|\/+$/g, '');
522
+ }
441
523
 
442
- interface NavListItem {
443
- break: never;
444
- to: string;
445
- text: string;
446
- iconName: string;
447
- };
524
+ /*
525
+ * Return the current sidebar slug while translating legacy route prefixes.
526
+ */
527
+ export function normalizeSidebarRouteSlug(slug: string | null | undefined) {
528
+ const normalizedSlug = getNormalizedSidebarSlug(slug);
448
529
 
449
- interface NavBreakItem {
450
- break: boolean;
451
- to: never;
452
- text: never;
453
- iconName: never;
454
- };
530
+ return normalizedSlug.startsWith('r/')
531
+ ? `fd/${normalizedSlug.slice(2)}`
532
+ : normalizedSlug;
533
+ }
455
534
 
456
- export type NavigationItem = NavListItem | NavBreakItem;
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
+ }
457
578
 
458
- export function getNavigationList(
459
- operation: OrganizationOperationEnum | null,
460
- orgFeatures?: OrganizationFeatureEnum[],
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
+ }
681
+ }
682
+
683
+ /*
684
+ * Return a stable sidebar slug for a route pathname.
685
+ */
686
+ function getSidebarSlugFromRoutePath(routePath: string | null | undefined) {
687
+ if (routePath === '/app') {
688
+ return 'home';
689
+ }
690
+
691
+ return normalizeSidebarRouteSlug(routePath);
692
+ }
693
+
694
+ /*
695
+ * Resolve a customized sidebar item into a route-backed navigation item.
696
+ */
697
+ function getNavigationItemFromSidebarItem(
698
+ item: OrganizationSidebarItemObj,
699
+ operation: OrganizationOperationEnum | null,
700
+ checkACLClient?: CheckACLClientFn | null,
701
+ ): NavListItem | null {
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
+ }
725
+
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
+ }
734
+
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
+ }
758
+
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
+ };
781
+ }
782
+
783
+ /*
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.
841
+ */
842
+ function getCustomizedNavigationList(
843
+ sidebar: OrganizationSidebarItemObj[],
844
+ operation: OrganizationOperationEnum | null,
845
+ checkACLClient?: CheckACLClientFn | null,
461
846
  ): 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);
862
+ }
462
863
 
463
- const breakItem = {
464
- break: true,
465
- };
466
-
467
- let navListArr: {
468
- text: string;
469
- initialExpanded?: boolean;
470
- navList: (RouteDictObj | { break: boolean })[];
471
- }[] = [];
472
-
473
- switch (operation) {
474
- case 'ARABLE':
475
- navListArr = [
476
- {
477
- text: i18n.t('form.reports'),
478
- navList: [
479
- ROUTES_DICT['/app/organic'],
480
- ROUTES_DICT['/app/globalgap/'],
481
- ]
482
- },
483
- {
484
- text: i18n.t('log.food_safety'),
485
- navList: [
486
- ROUTES_DICT['/app/cleaning'],
487
- // ROUTES_DICT['/app/hygiene'],
488
- // ROUTES_DICT['/app/sanitation'],
489
- // ROUTES_DICT['/app/materials'],
490
- // ROUTES_DICT['/app/biosecurity'],
491
- // ROUTES_DICT['/app/employees'],
492
- ]
493
- },
494
- {
495
- text: i18n.t(`org.type_active.${operation}`),
496
- navList: [
497
- ROUTES_DICT['/app/seeding'],
498
- ROUTES_DICT['/app/transplanting'],
499
- ROUTES_DICT['/app/field-work'],
500
- ROUTES_DICT['/app/harvested'],
501
- ROUTES_DICT['/app/post-harvest'],
502
-
503
- breakItem,
504
-
505
- ROUTES_DICT['/app/purchases'],
506
- ROUTES_DICT['/app/orders'],
507
- ]
508
- },
509
- ];
510
- break;
511
- case 'LIVESTOCK':
512
- navListArr = [
513
- {
514
- text: i18n.t(`org.type_active.${operation}`),
515
- navList: [
516
- ROUTES_DICT['/app/livestock'],
517
- { ...ROUTES_DICT['/app/purchases'], text: i18n.t('log.supply_purchases') },
518
- ]
519
- },
520
- ];
521
- break;
522
- case 'FARMERS_MARKET':
523
- navListArr = [
524
- {
525
- text: i18n.t(`org.type_active.${operation}`),
526
- navList: [
527
- ROUTES_DICT['/app/vendors'],
528
- ROUTES_DICT['/app/markets'],
529
- ROUTES_DICT['/app/receipts'],
530
- ]
531
- },
532
- ];
533
- break;
534
- case 'GROWER_NETWORK':
535
- navListArr = [
536
- {
537
- text: i18n.t(`org.type_active.${operation}`),
538
- navList: [
539
- ROUTES_DICT['/app/growers'],
540
- ROUTES_DICT['/app/foreign-growers'],
541
- ]
542
- }
543
- ];
544
- break;
545
- default:
546
- navListArr = [];
547
- }
548
-
549
- // @ts-ignore
550
- navListArr = [{
551
- ...ROUTES_DICT['/app'],
552
- iconName: COMMON_ICON_NAMES[operation!] || 'home',
553
- },
554
- breakItem,
555
- // @ts-ignore
556
- ].concat(navListArr).concat([{
557
- text: i18n.t('form.advanced'),
558
- initialExpanded: false,
559
- navList: [
560
- ROUTES_DICT['/app/ai-workflows'],
561
- ROUTES_DICT['/app/logs']
562
- ]
563
- }] as any);
564
-
565
- const mapNavItems = (item: any) => {
566
- if (Array.isArray(item)) {
567
- const [navItem, ...requiredFeatures] = item;
568
- if (requiredFeatures.some(feature => orgFeatures?.includes?.(feature))) {
569
- return navItem;
570
- }
571
- return null;
572
- } else if (item?.navList) {
573
- item.navList = item.navList.reduce((acc: any[], x: any, i: number) => {
574
- const mappedItem = mapNavItems(x);
575
- if (
576
- mappedItem &&
577
- (mappedItem.to || (acc.length && i !== (item.navList.length - 1)))
578
- ) {
579
- if (mappedItem.text && i18n.has(mappedItem.text)) {
580
- mappedItem.text = i18n.t(mappedItem.text);
581
- }
582
- acc.push(mappedItem);
583
- }
584
- return acc;
585
- }, []);
586
-
587
- if (!item.navList.length) {
588
- return null;
589
- }
590
- } else if (item?.to && !isRouteAllowed(item.to, operation, orgFeatures)) {
591
- return null;
592
- }
593
-
594
- if (item?.text && i18n.has(item.text)) {
595
- item.text = i18n.t(item.text);
596
- }
597
-
598
- return item;
599
- };
600
-
601
- return navListArr.map(mapNavItems).filter(Boolean);
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
+ */
991
+ export function getNavigationList(
992
+ operation: OrganizationOperationEnum | null,
993
+ checkACLClient?: CheckACLClientFn | null,
994
+ sidebar?: OrganizationSidebarItemObj[] | null,
995
+ ): NavigationItem[] {
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);
602
1015
  }