@jsb188/mday-web 1.1.10 → 1.1.12

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