@jsb188/mday-web 1.1.2

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.
@@ -0,0 +1,950 @@
1
+ // Schedule and projects are not ready.
2
+ // import { getScheduleDefaultSurface } from '@jsb188/schedule/utils/defaults.ts';
3
+ import i18n from '@jsb188/app/i18n/index.ts';
4
+ import type { OrganizationOperationEnum, OrganizationSidebarItemObj } from '@jsb188/mday/types/organization.d.ts';
5
+ import type { OperationName } from '@jsb188/mday/utils/organization.ts';
6
+ import { definePageFilterSchema, serializePageFilters, stringifyPageSearchParams } from '@jsb188/react/libs/page-filters';
7
+ import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
8
+ import { getOperationPageMetadata, OPERATION_PAGES, type OperationPageSlug } from './operation-pages.ts';
9
+
10
+ // Use this for fieldDoc periods, etc
11
+ // const CURRENT_YEAR = String(new Date().getFullYear());
12
+
13
+ /**
14
+ * Constants; Re-usable rules
15
+ */
16
+
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\/[^/]+$/;
20
+
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
+ }
35
+
36
+ /**
37
+ * Rules
38
+ */
39
+
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;
64
+
65
+ interface RouteDictObj {
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);
74
+ }
75
+
76
+ type CheckACLClientFn = (opName: OperationName) => boolean;
77
+
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
+ }
108
+
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,
259
+ };
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
+
270
+ /**
271
+ * Make pathname to a route in Marketday app.
272
+ * @param routeName - The name of the route.
273
+ * @param pathSegment - Optional additional path segment to append.
274
+ * @returns The full pathname for the route.
275
+ */
276
+
277
+ export function makePathname(routePath: ValidRoutePath, pathSegment?: string | null): ValidRoutePath {
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}`;
295
+ }
296
+
297
+ /**
298
+ * Check if route is valid.
299
+ * @param routeName - The name of the route.
300
+ * @param pathSegment - Optional additional path segment to append.
301
+ * @returns The full pathname for the route.
302
+ */
303
+
304
+ export function isRouteValid(routePath: ValidRoutePath, pathSegment?: string | null): boolean {
305
+ const routeDict = !!ROUTES_DICT[routePath];
306
+ return !!routeDict && (!routePath.endsWith('/') || !!pathSegment);
307
+ }
308
+
309
+ /**
310
+ * Get route config from pathname.
311
+ * NOTE: This is the best way to prevent page flickers due to breadcrumbs/TOC calculations/resets/etc.
312
+ * @param pathname - The pathname to check.
313
+ * @returns The route name if found.
314
+ */
315
+
316
+ const ROUTES_DICT_ORDERED = Object.keys(ROUTES_DICT).sort((a, b) => b.length - a.length);
317
+
318
+ interface RouteConfigObj extends Omit<RouteDictObj, 'hasPhysicalToolbar'> {
319
+ routeName: ValidRoutePath;
320
+ allowed: boolean;
321
+ hasPhysicalToolbar: boolean;
322
+ }
323
+
324
+ export function getRouteConfigs(
325
+ pathname: ValidRoutePath | string,
326
+ operation?: OrganizationOperationEnum | null,
327
+ checkACLClient?: CheckACLClientFn | null,
328
+ ): RouteConfigObj {
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;
365
+ }
366
+
367
+ /**
368
+ * Check if this organization's operation allows access to this route path
369
+ * @param pathname - pathname to check.
370
+ * @param operation - Organization operation.
371
+ */
372
+
373
+ export function isRouteAllowed(
374
+ pathname: ValidRoutePath | string,
375
+ operation?: OrganizationOperationEnum | null,
376
+ checkACLClient?: CheckACLClientFn | null,
377
+ ): boolean {
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
+ );
402
+ }
403
+
404
+ /**
405
+ * Helper; get static nav list based on the organization's operation.
406
+ */
407
+
408
+ interface NavListItem {
409
+ break?: never;
410
+ slug?: string;
411
+ to: string;
412
+ text: string;
413
+ iconName?: string | null;
414
+ }
415
+
416
+ interface NavBreakItem {
417
+ break: boolean;
418
+ to?: never;
419
+ text?: never;
420
+ iconName?: never;
421
+ }
422
+
423
+ interface NavGroupItem {
424
+ break?: never;
425
+ to?: never;
426
+ text: string;
427
+ initialExpanded?: boolean;
428
+ navList: (NavListItem | NavBreakItem)[];
429
+ }
430
+
431
+ export type NavigationItem = NavListItem | NavBreakItem | NavGroupItem;
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
+
512
+ /*
513
+ * Check whether one concrete path fits a client route pattern, including optional segments and splats.
514
+ */
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
+ }
532
+
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
+ }
587
+ }
588
+
589
+ /*
590
+ * Return a stable sidebar slug for a route pathname.
591
+ */
592
+ function getSidebarSlugFromRoutePath(routePath: string | null | undefined) {
593
+ if (routePath === '/app') {
594
+ return 'home';
595
+ }
596
+
597
+ return getNormalizedSidebarSlug(routePath);
598
+ }
599
+
600
+ /*
601
+ * Resolve a customized sidebar item into a route-backed navigation item.
602
+ */
603
+ function getNavigationItemFromSidebarItem(
604
+ item: OrganizationSidebarItemObj,
605
+ operation: OrganizationOperationEnum | null,
606
+ checkACLClient?: CheckACLClientFn | null,
607
+ ): NavListItem | null {
608
+ if (item.kind && item.kind !== 'LINK') {
609
+ return null;
610
+ }
611
+
612
+ const route = getSidebarRouteFromSlug(item.slug);
613
+
614
+ if (!route || !isRouteAllowed(route.routePath, operation, checkACLClient)) {
615
+ return null;
616
+ }
617
+
618
+ const routeDict = ROUTES_DICT[route.routePath];
619
+ const fallbackText = routeDict.text && i18n.has(routeDict.text) ? i18n.t(routeDict.text) : routeDict.text;
620
+
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;
634
+ }
635
+
636
+ /*
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.
731
+ */
732
+ function getCustomizedNavigationList(
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,
801
+ ): NavigationItem[] {
802
+ return mapNavigationList([{ ...ROUTES_DICT['/app/workflows'] }, { ...ROUTES_DICT['/app/qrcodes'] }], operation, checkACLClient);
803
+ }
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
+ */
901
+ export function getNavigationList(
902
+ operation: OrganizationOperationEnum | null,
903
+ checkACLClient?: CheckACLClientFn | null,
904
+ sidebar?: OrganizationSidebarItemObj[] | null,
905
+ defaultSurface?: 'PROJECT' | 'COVERAGE' | null,
906
+ ): NavigationItem[] {
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;
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
+ // }