@jsb188/mday 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.
Files changed (123) hide show
  1. package/package.json +105 -35
  2. package/src/constants/agentDoc.ts +12 -0
  3. package/src/constants/agentMemory.ts +154 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/campaign.ts +127 -0
  6. package/src/constants/dataTable.ts +48 -0
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +44 -0
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/inboundContact.ts +8 -0
  13. package/src/constants/integration.ts +13 -0
  14. package/src/constants/log.ts +7 -366
  15. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  16. package/src/constants/logTaxonomy.generated.ts +1103 -0
  17. package/src/constants/noteDoc.ts +77 -0
  18. package/src/constants/organization.ts +18 -11
  19. package/src/constants/pageRoute.ts +23 -0
  20. package/src/constants/schedule.ts +220 -0
  21. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  22. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  23. package/src/constants/sheet.ts +168 -0
  24. package/src/constants/sheetRegionSources.generated.ts +578 -0
  25. package/src/constants/square.ts +16 -0
  26. package/src/constants/storage.ts +61 -0
  27. package/src/constants/usage.ts +79 -0
  28. package/src/schemas/editLogEntry.ts +1017 -738
  29. package/src/schemas/fieldDocsQuery.ts +12 -0
  30. package/src/schemas/inboundContact.ts +77 -0
  31. package/src/schemas/logsQuery.ts +57 -316
  32. package/src/schemas/organization.ts +53 -213
  33. package/src/types/account.d.ts +81 -0
  34. package/src/types/agentDoc.d.ts +64 -0
  35. package/src/types/agentMemory.d.ts +74 -0
  36. package/src/types/campaign.d.ts +683 -0
  37. package/src/types/dataTable.d.ts +366 -0
  38. package/src/types/docAccess.d.ts +96 -0
  39. package/src/types/email.d.ts +142 -0
  40. package/src/types/fieldDoc.d.ts +273 -0
  41. package/src/types/inboundContact.d.ts +57 -0
  42. package/src/types/integration.d.ts +42 -0
  43. package/src/types/log.d.ts +169 -190
  44. package/src/types/noteDoc.d.ts +86 -0
  45. package/src/types/organization.d.ts +175 -76
  46. package/src/types/pageRoute.d.ts +48 -0
  47. package/src/types/schedule.d.ts +391 -0
  48. package/src/types/sheet.d.ts +1130 -0
  49. package/src/types/storage.d.ts +242 -0
  50. package/src/types/usage.d.ts +106 -0
  51. package/src/types/workflow.d.ts +305 -0
  52. package/src/utils/agentDoc.ts +109 -0
  53. package/src/utils/aiChat.ts +26 -0
  54. package/src/utils/campaign.ts +741 -0
  55. package/src/utils/campaignFormEditor.ts +871 -0
  56. package/src/utils/dataTable.ts +849 -0
  57. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  58. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  59. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  60. package/src/utils/dataTableRowDocument.ts +508 -0
  61. package/src/utils/dataTableSource.ts +230 -0
  62. package/src/utils/docAccess.ts +383 -0
  63. package/src/utils/documentName.ts +53 -0
  64. package/src/utils/email.ts +172 -0
  65. package/src/utils/fieldDoc.ts +113 -0
  66. package/src/utils/log.ts +173 -778
  67. package/src/utils/logRegistryValue.ts +90 -0
  68. package/src/utils/logStoreRead.ts +266 -0
  69. package/src/utils/logTaxonomy.ts +76 -0
  70. package/src/utils/logTaxonomyDisplay.ts +439 -0
  71. package/src/utils/noteDoc.ts +827 -0
  72. package/src/utils/organization.ts +683 -81
  73. package/src/utils/pageRoute.ts +71 -0
  74. package/src/utils/schedule.ts +799 -0
  75. package/src/utils/scheduleEvaluation.ts +1994 -0
  76. package/src/utils/scheduleICS.ts +246 -0
  77. package/src/utils/scheduleRuleTemplates.ts +188 -0
  78. package/src/utils/sheet.ts +4973 -0
  79. package/src/utils/sheetAxisMove.ts +830 -0
  80. package/src/utils/sheetBootstrap.ts +1769 -0
  81. package/src/utils/sheetCommand.ts +423 -0
  82. package/src/utils/sheetExport.ts +238 -0
  83. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  84. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  85. package/src/utils/sheetJournal.ts +78 -0
  86. package/src/utils/sheetNumberFormat.ts +1211 -0
  87. package/src/utils/sheetRegion.ts +374 -0
  88. package/src/utils/sheetRegionFilter.ts +1259 -0
  89. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  90. package/src/utils/sheetSequence.ts +148 -0
  91. package/src/utils/sheetSnapshot.ts +992 -0
  92. package/src/utils/sheetStructureEdit.ts +1284 -0
  93. package/src/utils/square.ts +32 -0
  94. package/src/utils/storage.ts +152 -0
  95. package/src/utils/table-route.ts +262 -0
  96. package/src/utils/workflow.ts +380 -0
  97. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  98. package/tests/docAccess.test.ts +525 -0
  99. package/tests/editLogEntry.test.ts +112 -0
  100. package/tests/noteDoc.test.ts +669 -0
  101. package/tests/schedule.test.ts +693 -0
  102. package/tests/scheduleEvaluation.test.ts +1970 -0
  103. package/tests/scheduleICS.test.ts +208 -0
  104. package/tests/scheduleRuleTemplates.test.ts +176 -0
  105. package/tests/scheduleSweepInvariants.test.ts +428 -0
  106. package/tests/sheetAxisMove.test.ts +343 -0
  107. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  108. package/tests/sheetRegionFilter.test.ts +1135 -0
  109. package/tests/sheetSequence.test.ts +41 -0
  110. package/tests/sheetStructureEdit.test.ts +82 -0
  111. package/tsconfig.json +12 -0
  112. package/vitest.config.ts +8 -0
  113. package/src/constants/log-activityTexts.ts +0 -209
  114. package/src/constants/product.ts +0 -66
  115. package/src/constants/report.ts +0 -25
  116. package/src/schemas/childOrganizationsQuery.ts +0 -44
  117. package/src/schemas/productsQuery.ts +0 -145
  118. package/src/schemas/reportsQuery.ts +0 -107
  119. package/src/types/action.d.ts +0 -42
  120. package/src/types/product.d.ts +0 -173
  121. package/src/types/report.d.ts +0 -203
  122. package/src/utils/product-calEvent.ts +0 -508
  123. package/src/utils/route-helpers.ts +0 -583
@@ -1,23 +1,128 @@
1
- import { COLORS } from '@jsb188/app/constants/app';
2
- import i18n from '@jsb188/app/i18n';
3
- import { intersection } from '@jsb188/app/utils/object';
4
- import { DEFAULT_TIMEZONE } from '@jsb188/app/utils/timeZone';
5
- import { COMMON_ICON_NAMES } from '@jsb188/react-web/svgs/Icon';
6
- import { FEATURES_BY_OPERATION } from '../constants/product';
1
+ import { COLORS } from '@jsb188/app/constants/app.ts';
2
+ import { shortenToSpace } from '@jsb188/app/utils/string.ts';
3
+ import { DEFAULT_TIMEZONE } from '@jsb188/app/utils/timeZone.ts';
4
+ import { ORG_CONTACTS } from '../constants/organization.ts';
7
5
  import type {
8
- OrganizationContact,
9
- OrganizationFeatureEnum,
10
- OrganizationGQL,
11
- OrganizationOperationEnum,
12
- OrganizationRelData,
13
- OrganizationRelGQL,
14
- OrganizationRoleEnum,
15
- OrganizationSettingsObj
16
- } from '../types/organization.d';
6
+ ACLPermissionEnum,
7
+ MergedOrgContact,
8
+ OrgContact,
9
+ OrganizationChildData,
10
+ OrganizationChildGQL,
11
+ OrganizationContactData,
12
+ OrganizationDepartmentEnum,
13
+ OrganizationOperationEnum,
14
+ OrganizationRelData,
15
+ OrganizationRelGQL,
16
+ OrganizationRoleEnum,
17
+ OrganizationSettingsObj,
18
+ } from '../types/organization.d.ts';
19
+ import type { SheetCustomRegionSourceColumnFormulaValueSourceEnum } from '../types/sheet.d.ts';
17
20
 
18
21
  // Placeholder to match Server import
19
22
  type ViewerOrganization = any;
20
23
 
24
+ type OperationPermissionTuple = readonly [
25
+ PermissionCheckFor,
26
+ ACLPermissionEnum,
27
+ string,
28
+ ];
29
+ type OperationPermissionsMap = Record<string, OperationPermissionTuple>;
30
+ type OrganizationChildPreferredContacts =
31
+ | OrgContact[]
32
+ | Record<string, Partial<OrgContact> | null | undefined>
33
+ | null
34
+ | undefined;
35
+ type OrganizationChildContactSource = {
36
+ organization?: {
37
+ id?: string | number | bigint | null;
38
+ readableId?: string | null;
39
+ directory?: OrgContact[] | null;
40
+ name?: string | null;
41
+ operation?: OrganizationOperationEnum | string | null;
42
+ } | null;
43
+ preferredContacts?: OrganizationChildPreferredContacts;
44
+ };
45
+
46
+ export const OPERATION_PERMISSIONS = {
47
+ billing_read: [
48
+ 'billing',
49
+ 'READ',
50
+ "You do not have permission to view this organization's billing usage.",
51
+ ],
52
+ chat: [
53
+ 'viewData',
54
+ 'READ',
55
+ 'You do not have permission to chat with AI in this organization.',
56
+ ],
57
+ general_read: [
58
+ 'viewData',
59
+ 'READ',
60
+ "You do not have permission to view this organization's data.",
61
+ ],
62
+ general_write: [
63
+ 'viewData',
64
+ 'WRITE',
65
+ 'You do not have permission to write data in this organization.',
66
+ ],
67
+ integrations_update: [
68
+ 'integrations',
69
+ 'MANAGE',
70
+ "You do not have permission to manage this organization's app connections.",
71
+ ],
72
+ ai_inbox_management: [
73
+ 'orgManagement',
74
+ 'MANAGE',
75
+ "You do not have permission to manage this organization's AI inbox.",
76
+ ],
77
+ ai_inbox_read: [
78
+ 'orgManagement',
79
+ 'READ',
80
+ "You do not have permission to read this organization's AI inbox.",
81
+ ],
82
+ logs_write: [
83
+ 'logs',
84
+ 'WRITE',
85
+ 'You do not have permission to write logs in this organization.',
86
+ ],
87
+ member_sessions_manage: [
88
+ 'members',
89
+ 'MANAGE',
90
+ 'You do not have permission to manage member sessions in this organization.',
91
+ ],
92
+ org_directory: [
93
+ 'logs',
94
+ 'WRITE',
95
+ "You do not have permission to manage this organization's directory book.",
96
+ ],
97
+ agent_docs_edit: [
98
+ 'viewData',
99
+ 'MANAGE',
100
+ 'You do not have permission to edit agent docs in this organization.',
101
+ ],
102
+ org_management: [
103
+ 'orgManagement',
104
+ 'WRITE',
105
+ "You do not have permission to edit this organization's data.",
106
+ ],
107
+ org_sites_update: [
108
+ 'logs',
109
+ 'WRITE',
110
+ 'You do not have permission to update organization sites.',
111
+ ],
112
+ schedule_edit: [
113
+ 'viewData',
114
+ 'MANAGE',
115
+ 'You do not have permission to edit schedules in this organization.',
116
+ ],
117
+ sheets_edit: [
118
+ 'viewData',
119
+ 'MANAGE',
120
+ 'You do not have permission to edit sheets & data tables in this organization.',
121
+ ],
122
+ } as const satisfies OperationPermissionsMap;
123
+
124
+ export type OperationName = keyof typeof OPERATION_PERMISSIONS;
125
+
21
126
  export const PERMISSION_TO_INT = {
22
127
  NONE: 0,
23
128
  READ: 1,
@@ -25,6 +130,67 @@ export const PERMISSION_TO_INT = {
25
130
  MANAGE: 3,
26
131
  };
27
132
 
133
+ export const ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH = 40;
134
+
135
+ const ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX = /^[a-z0-9_-]+$/;
136
+
137
+ /*
138
+ * Convert free-form input into the closest inbound email handle candidate.
139
+ */
140
+
141
+ export function normalizeOrganizationInboundEmailHandle(
142
+ value?: string | null,
143
+ ): string {
144
+ return String(value || '')
145
+ .trim()
146
+ .toLowerCase()
147
+ .replace(/[^a-z0-9_-]+/g, '')
148
+ .replace(/[-_]{2,}/g, (match) => match[0])
149
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
150
+ }
151
+
152
+ /*
153
+ * Build the default inbound email handle placeholder from an organization name.
154
+ */
155
+
156
+ export function buildOrganizationInboundEmailPlaceholder(
157
+ orgName?: string | null,
158
+ ): string {
159
+ return normalizeOrganizationInboundEmailHandle(
160
+ shortenToSpace(String(orgName || ''), 20),
161
+ );
162
+ }
163
+
164
+ /*
165
+ * Keep typed input limited to the inbound email handle character set.
166
+ */
167
+
168
+ export function sanitizeOrganizationInboundEmailHandleInput(
169
+ value?: string | null,
170
+ ): string {
171
+ return String(value || '')
172
+ .toLowerCase()
173
+ .replace(/[^a-z0-9_-]+/g, '')
174
+ .replace(/[-_]{2,}/g, (match) => match[0])
175
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
176
+ }
177
+
178
+ /*
179
+ * Check whether a normalized inbound email handle is valid to store.
180
+ */
181
+
182
+ export function isValidOrganizationInboundEmailHandle(
183
+ value?: string | null,
184
+ ): boolean {
185
+ const handle = String(value || '');
186
+
187
+ return !!(
188
+ handle &&
189
+ handle.length <= ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH &&
190
+ ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX.test(handle)
191
+ );
192
+ }
193
+
28
194
  const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
29
195
 
30
196
  /**
@@ -33,20 +199,16 @@ const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
33
199
  */
34
200
 
35
201
  export function getRoleValue(role: OrganizationRoleEnum): number {
36
- return [
37
- 'GUEST',
38
- 'MEMBER',
39
- 'MANAGER',
40
- 'ADMIN',
41
- 'OWNER',
42
- ].indexOf(role);
202
+ return ['GUEST', 'MEMBER', 'MANAGER', 'ADMIN', 'OWNER'].indexOf(role);
43
203
  }
44
204
 
45
205
  /**
46
206
  * Get default permissions by role
47
207
  */
48
208
 
49
- export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization) {
209
+ export function getDefaultPermissionsByRole(
210
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization,
211
+ ) {
50
212
  const role = orgRel?.role || 'MEMBER';
51
213
  const acl: Record<string, any> = { ...orgRel?.acl };
52
214
 
@@ -59,10 +221,10 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
59
221
 
60
222
  // Also keep this synced with [resolvers/organizationTypeResolvers.ts]
61
223
 
62
- // 0 = "NONE"
63
- // 1 = "READ"
64
- // 2 = "WRITE"
65
224
  // 3 = "MANAGE"
225
+ // 2 = "WRITE"
226
+ // 1 = "READ"
227
+ // 0 = "NONE"
66
228
 
67
229
  switch (role) {
68
230
  case 'ADMIN':
@@ -76,7 +238,7 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
76
238
  logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
77
239
  members: acl.members || 'MANAGE',
78
240
  orgManagement: acl.orgManagement || 'MANAGE',
79
- products: acl.products || 'MANAGE',
241
+ products: acl.products || 'MANAGE', // products = field docs
80
242
  settings: acl.settings || 'MANAGE',
81
243
  viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
82
244
  };
@@ -104,9 +266,9 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
104
266
  logs: acl.logs || 'NONE',
105
267
  members: acl.members || 'NONE',
106
268
  orgManagement: acl.orgManagement || 'NONE',
107
- products: acl.products || 'READ',
269
+ products: acl.products || 'READ', // products = field docs
108
270
  settings: acl.settings || 'NONE',
109
- viewData: acl.viewData || 'NONE',
271
+ viewData: acl.viewData || 'READ',
110
272
  };
111
273
  case 'MEMBER':
112
274
  default:
@@ -118,12 +280,12 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
118
280
  digests: acl.digests || 'NONE', // 2/3 = receive digests, 1 = only see from web app
119
281
  finances: acl.finances || 'NONE',
120
282
  integrations: acl.integrations || 'NONE',
121
- logs: acl.logs || 'WRITE', // "READ" for logs does nothing
283
+ logs: acl.logs || 'WRITE', // "READ" for logs does nothing, also "WRITE" is required for directory/site management
122
284
  members: acl.members || 'READ',
123
285
  orgManagement: acl.orgManagement || 'READ',
124
- products: acl.products || 'READ',
286
+ products: acl.products || 'READ', // products = field docs
125
287
  settings: acl.settings || 'READ',
126
- viewData: acl.viewData || 'NONE', // This blocks access from users being able to read other people's logs
288
+ viewData: acl.viewData || 'WRITE',
127
289
  };
128
290
  }
129
291
 
@@ -131,11 +293,18 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
131
293
  * Check if this account's ACL has required permissions for an action
132
294
  */
133
295
 
134
- export type PermissionCheckFor = keyof ReturnType<typeof getDefaultPermissionsByRole>;
296
+ export type PermissionCheckFor = keyof ReturnType<
297
+ typeof getDefaultPermissionsByRole
298
+ >;
135
299
  export type ACLPermissionCheck = 'READ' | 'WRITE' | 'MANAGE';
136
300
 
137
301
  export function checkACLPermission(
138
- orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
302
+ orgRel:
303
+ | OrganizationRelGQL
304
+ | OrganizationRelData
305
+ | ViewerOrganization
306
+ | null
307
+ | undefined,
139
308
  check: PermissionCheckFor,
140
309
  requiredPermission: ACLPermissionCheck,
141
310
  ): boolean | null {
@@ -144,7 +313,6 @@ export function checkACLPermission(
144
313
  }
145
314
 
146
315
  const acl = getDefaultPermissionsByRole(orgRel);
147
-
148
316
  const requiredInt = PERMISSION_TO_INT[requiredPermission] || 4; // If invalid, it will always return false
149
317
  const permission = acl[check] as ACLPermissionCheck;
150
318
  const acccountPermissionInt = PERMISSION_TO_INT[permission] || 0; // If invalid, it will always return false
@@ -153,40 +321,63 @@ export function checkACLPermission(
153
321
  }
154
322
 
155
323
  /**
156
- * Get all title icons for organization/vendor
157
- * @param org - Organization GQL data
158
- * @param showIconsRule - Rules for which icons to show/not-show
159
- * @returns Array of icon label objects with icon name and tooltip text
324
+ * Check ACL permission from pre-defined constants
160
325
  */
161
326
 
162
- export function getTitleIconsForOrganization(
163
- org: OrganizationGQL,
164
- showIconsRule: Record<string, boolean> = {},
327
+ export function checkACL(
328
+ orgRel:
329
+ | OrganizationRelGQL
330
+ | OrganizationRelData
331
+ | ViewerOrganization
332
+ | null
333
+ | undefined,
334
+ opName: OperationName,
165
335
  ) {
166
- const { operation, compliance } = org;
167
- const titleIcons = [];
336
+ const [permissionCheckFor, requiredPermission] =
337
+ OPERATION_PERMISSIONS[opName] || [];
338
+ if (!permissionCheckFor || !requiredPermission) {
339
+ console.warn(`Operation ${opName} not found in permissions map.`);
340
+ return null;
341
+ }
342
+ return checkACLPermission(orgRel, permissionCheckFor, requiredPermission);
343
+ }
168
344
 
169
- if (operation && showIconsRule.operation !== false) {
170
- titleIcons.push({
171
- iconName: COMMON_ICON_NAMES[operation] || 'info-circle',
172
- tooltipText: i18n.t(`org.type.${operation}`),
173
- });
345
+ /**
346
+ * Check whether the user's ACL differs from role defaults
347
+ * @returns true if at least one ACL permission differs from default role ACL
348
+ */
349
+
350
+ export function isCustomACLForRole(
351
+ orgRel:
352
+ | OrganizationRelGQL
353
+ | OrganizationRelData
354
+ | ViewerOrganization
355
+ | null
356
+ | undefined,
357
+ ): boolean {
358
+ if (!orgRel) {
359
+ return false;
360
+ }
361
+ if (orgRel.role === 'OWNER') {
362
+ return false;
174
363
  }
175
364
 
176
- if (compliance?.length && showIconsRule.compliance !== false) {
177
- const today = new Date();
178
- const todayCalDate = today.toISOString().split('T')[0];
179
- const notExpired = compliance.filter((item: any) => item.expirationDate && item.expirationDate > todayCalDate);
365
+ const roleDefaultACL = getDefaultPermissionsByRole({
366
+ role: orgRel.role,
367
+ acl: {},
368
+ } as OrganizationRelGQL);
180
369
 
181
- if (notExpired.length > 0) {
182
- titleIcons.push({
183
- iconName: 'document-license',
184
- tooltipText: notExpired.map((item: any) => item.name).join(', '),
185
- });
370
+ const effectiveACL = getDefaultPermissionsByRole(orgRel);
371
+ for (const aclKey in roleDefaultACL) {
372
+ if (
373
+ effectiveACL[aclKey as PermissionCheckFor] !==
374
+ roleDefaultACL[aclKey as PermissionCheckFor]
375
+ ) {
376
+ return true;
186
377
  }
187
378
  }
188
379
 
189
- return titleIcons;
380
+ return false;
190
381
  }
191
382
 
192
383
  /**
@@ -197,37 +388,448 @@ export function getTitleIconsForOrganization(
197
388
 
198
389
  export function getDefaultOrganizationSettings(
199
390
  timeZone: string | null,
200
- contacts?: OrganizationContact[],
201
391
  // do params here for priority service + manage roles
202
392
  ): Partial<OrganizationSettingsObj> {
203
- const orgSettings: Record<string, any> = {
393
+ return {
204
394
  timeZone: timeZone || DEFAULT_TIMEZONE,
205
395
  color: COLORS[Math.floor(Math.random() * COLORS.length)],
206
396
  };
397
+ }
207
398
 
208
- if (contacts?.length) {
209
- orgSettings.directory = contacts.map((contact) => {
210
- return {
211
- ...contact,
212
- department: contact.department || 'OTHER',
213
- };
214
- }).filter((contact) => contact.emailAddress || contact.phoneNumber);
399
+ /*
400
+ * Map organization_contacts rows to plain directory contacts, ordered by department.
401
+ */
402
+ export function mapOrgContactRowsToContacts(
403
+ rows?: Array<Partial<OrganizationContactData>> | null,
404
+ ): OrgContact[] {
405
+ return (rows || [])
406
+ .filter((row) => row.department)
407
+ .map((row) => ({
408
+ department: row.department as OrganizationDepartmentEnum,
409
+ name: row.name || null,
410
+ phoneNumber: row.phoneNumber || null,
411
+ emailAddress: row.emailAddress || null,
412
+ }))
413
+ .sort(
414
+ (a, b) =>
415
+ ORG_CONTACTS.indexOf(a.department) - ORG_CONTACTS.indexOf(b.department),
416
+ );
417
+ }
418
+
419
+ /*
420
+ * Map parent-override organization_contacts rows to the department-keyed preferred contacts shape.
421
+ */
422
+ export function mapOrgContactRowsToPreferredContactsMap(
423
+ rows?: Array<Partial<OrganizationContactData>> | null,
424
+ ): Record<string, OrgContact> {
425
+ return mapOrgContactRowsToContacts(rows).reduce(
426
+ (acc, contact) => {
427
+ acc[contact.department] = contact;
428
+ return acc;
429
+ },
430
+ {} as Record<string, OrgContact>,
431
+ );
432
+ }
433
+
434
+ /*
435
+ * Split one org's contact rows into own-directory rows and one parent's override rows.
436
+ */
437
+ export function splitOrgContactRowsByScope(
438
+ rows: Array<Partial<OrganizationContactData>>,
439
+ ownerOrgId?: number | bigint | null,
440
+ ): {
441
+ ownRows: Array<Partial<OrganizationContactData>>;
442
+ overrideRows: Array<Partial<OrganizationContactData>>;
443
+ } {
444
+ const ownRows: Array<Partial<OrganizationContactData>> = [];
445
+ const overrideRows: Array<Partial<OrganizationContactData>> = [];
446
+
447
+ for (const row of rows) {
448
+ if (row.ownerOrgId == null) {
449
+ ownRows.push(row);
450
+ } else if (ownerOrgId != null && row.ownerOrgId == ownerOrgId) {
451
+ overrideRows.push(row);
452
+ }
453
+ }
454
+
455
+ return { ownRows, overrideRows };
456
+ }
457
+
458
+ /**
459
+ * Check if preferred contact overrides at least one directory field.
460
+ */
461
+
462
+ function hasPreferredOverride(dirContact: OrgContact, preferred?: OrgContact) {
463
+ if (!preferred) {
464
+ return false;
215
465
  }
216
466
 
217
- return orgSettings;
467
+ return (
468
+ (preferred.name !== undefined && preferred.name !== dirContact.name) ||
469
+ (preferred.phoneNumber !== undefined &&
470
+ preferred.phoneNumber !== dirContact.phoneNumber) ||
471
+ (preferred.emailAddress !== undefined &&
472
+ preferred.emailAddress !== dirContact.emailAddress)
473
+ );
218
474
  }
219
475
 
220
476
  /**
221
- * Get the enabled features for the organization;
222
- * If none or empty, return the default features based on operation
223
- */
224
-
225
- export function getOrganizationFeatures(
226
- operation: OrganizationOperationEnum,
227
- enabledFeatures?: OrganizationFeatureEnum[] | null,
228
- ): OrganizationFeatureEnum[] {
229
- // @ts-expect-error - Allow operation as string
230
- const allowedFeatures = FEATURES_BY_OPERATION[operation] || [];
231
- const filteredFeatures = intersection(enabledFeatures || [], allowedFeatures);
232
- return filteredFeatures.length ? filteredFeatures : allowedFeatures[0] ? [allowedFeatures[0]] : [];
477
+ * Merge directory with preferred contacts
478
+ */
479
+
480
+ export function mergeOrgDirectory(
481
+ directory: OrgContact[],
482
+ preferredContacts?: OrgContact[],
483
+ duplicateOrgContacts: boolean = false,
484
+ ): MergedOrgContact[] {
485
+ if (!preferredContacts?.length) {
486
+ return directory || [];
487
+ }
488
+
489
+ // Create a map of preferredContacts by department
490
+ const preferredMap = new Map<string, OrgContact>();
491
+ for (const contact of preferredContacts) {
492
+ if (contact.department) {
493
+ preferredMap.set(contact.department, contact);
494
+ }
495
+ }
496
+
497
+ // Merge directory with preferred contacts, removing matched entries from map
498
+ const merged: MergedOrgContact[] = [];
499
+ for (const dirContact of directory || []) {
500
+ const preferred = preferredMap.get(dirContact.department);
501
+ const hasOverride = hasPreferredOverride(dirContact, preferred);
502
+ const hasPreferredContact = !!preferred;
503
+ preferredMap.delete(dirContact.department);
504
+
505
+ const mergedContact: MergedOrgContact = {
506
+ department: dirContact.department,
507
+ name: preferred?.name ?? dirContact.name,
508
+ phoneNumber: preferred?.phoneNumber ?? dirContact.phoneNumber,
509
+ emailAddress: preferred?.emailAddress ?? dirContact.emailAddress,
510
+ defaultName: dirContact.name,
511
+ defaultPhoneNumber: dirContact.phoneNumber,
512
+ defaultEmailAddress: dirContact.emailAddress,
513
+ officialContact: !hasPreferredContact,
514
+ };
515
+ merged.push(mergedContact);
516
+
517
+ if (duplicateOrgContacts && hasOverride) {
518
+ merged.push({
519
+ department: dirContact.department,
520
+ name: dirContact.name,
521
+ phoneNumber: dirContact.phoneNumber,
522
+ emailAddress: dirContact.emailAddress,
523
+ defaultName: dirContact.name,
524
+ defaultPhoneNumber: dirContact.phoneNumber,
525
+ defaultEmailAddress: dirContact.emailAddress,
526
+ officialContact: true,
527
+ locked: true,
528
+ });
529
+ }
530
+ }
531
+
532
+ // Add remaining preferred contacts (not in directory)
533
+ for (const [, preferred] of preferredMap) {
534
+ merged.push({
535
+ department: preferred.department,
536
+ name: preferred.name,
537
+ phoneNumber: preferred.phoneNumber,
538
+ emailAddress: preferred.emailAddress,
539
+ defaultName: null,
540
+ defaultPhoneNumber: null,
541
+ defaultEmailAddress: null,
542
+ });
543
+ }
544
+
545
+ return merged;
546
+ }
547
+
548
+ /*
549
+ * Upsert one preferred contact by department without mutating the source list.
550
+ */
551
+ export function upsertOrgPreferredContactByDepartment(
552
+ preferredContacts: OrgContact[] | undefined,
553
+ department: OrgContact['department'],
554
+ values: Partial<Pick<OrgContact, 'emailAddress' | 'name' | 'phoneNumber'>>,
555
+ ): OrgContact[] {
556
+ const source = preferredContacts || [];
557
+ const nextContact: OrgContact = {
558
+ department,
559
+ name: values.name || null,
560
+ phoneNumber: values.phoneNumber || null,
561
+ emailAddress: values.emailAddress || null,
562
+ };
563
+
564
+ if (!source.some((contact) => contact.department === department)) {
565
+ return [...source, nextContact];
566
+ }
567
+
568
+ return source.map((contact) =>
569
+ contact.department === department ? nextContact : contact,
570
+ );
571
+ }
572
+
573
+ /*
574
+ * Remove one preferred contact department without mutating the source list.
575
+ */
576
+ export function removeOrgPreferredContactByDepartment(
577
+ preferredContacts: OrgContact[] | undefined,
578
+ department: OrgContact['department'],
579
+ ): OrgContact[] {
580
+ return (preferredContacts || []).filter(
581
+ (contact) => contact.department !== department,
582
+ );
583
+ }
584
+
585
+ /*
586
+ * Restore one preferred contact department from a saved contact snapshot.
587
+ */
588
+ export function restoreOrgPreferredContactByDepartment(
589
+ currentPreferredContacts: OrgContact[] | undefined,
590
+ savedPreferredContacts: OrgContact[] | undefined,
591
+ department: OrgContact['department'],
592
+ ): OrgContact[] {
593
+ const savedContact = (savedPreferredContacts || []).find(
594
+ (contact) => contact.department === department,
595
+ );
596
+ const withoutDepartment = (currentPreferredContacts || []).filter(
597
+ (contact) => contact.department !== department,
598
+ );
599
+
600
+ return savedContact
601
+ ? [...withoutDepartment, savedContact]
602
+ : withoutDepartment;
603
+ }
604
+
605
+ /*
606
+ * Find the editable version of a merged contact department.
607
+ */
608
+ export function getEditableOrgContactByDepartment(
609
+ list: MergedOrgContact[],
610
+ department: OrgContact['department'],
611
+ ): MergedOrgContact | null {
612
+ return (
613
+ list.find((item) => item.department === department && !item.locked) || null
614
+ );
615
+ }
616
+
617
+ /*
618
+ * Compare preferred-contact lists by normalized department and value pairs.
619
+ */
620
+ export function areOrgPreferredContactsEqual(
621
+ a?: OrgContact[] | null,
622
+ b?: OrgContact[] | null,
623
+ ) {
624
+ const sourceA = a || [];
625
+ const sourceB = b || [];
626
+
627
+ if (sourceA.length !== sourceB.length) {
628
+ return false;
629
+ }
630
+
631
+ const normalizedA = [...sourceA].sort((x, y) =>
632
+ x.department.localeCompare(y.department),
633
+ );
634
+ const normalizedB = [...sourceB].sort((x, y) =>
635
+ x.department.localeCompare(y.department),
636
+ );
637
+
638
+ return normalizedA.every((item, index) => {
639
+ const other = normalizedB[index];
640
+
641
+ return (
642
+ item.department === other.department &&
643
+ (item.name || null) === (other.name || null) &&
644
+ (item.phoneNumber || null) === (other.phoneNumber || null) &&
645
+ (item.emailAddress || null) === (other.emailAddress || null)
646
+ );
647
+ });
648
+ }
649
+
650
+ /*
651
+ * Return one preferred contact with a department supplied from the map key when needed.
652
+ */
653
+ function normalizeOrganizationChildPreferredContact(
654
+ department: string,
655
+ contact?: Partial<OrgContact> | null,
656
+ ): OrgContact | null {
657
+ if (!contact) {
658
+ return null;
659
+ }
660
+
661
+ const contactDepartment =
662
+ contact.department || (department as OrganizationDepartmentEnum);
663
+
664
+ if (!contactDepartment) {
665
+ return null;
666
+ }
667
+
668
+ return {
669
+ department: contactDepartment,
670
+ name: contact.name,
671
+ phoneNumber: contact.phoneNumber,
672
+ emailAddress: contact.emailAddress,
673
+ };
674
+ }
675
+
676
+ /*
677
+ * Return preferred child-organization contacts in the array shape expected by directory helpers.
678
+ */
679
+ export function getOrganizationChildPreferredContacts(
680
+ childOrganization?: OrganizationChildContactSource | null,
681
+ ): OrgContact[] {
682
+ const preferredContacts = childOrganization?.preferredContacts;
683
+
684
+ if (Array.isArray(preferredContacts)) {
685
+ return preferredContacts
686
+ .map((contact) =>
687
+ normalizeOrganizationChildPreferredContact(contact.department, contact),
688
+ )
689
+ .filter(Boolean) as OrgContact[];
690
+ }
691
+
692
+ return Object.entries(preferredContacts || {})
693
+ .map(([department, contact]) =>
694
+ normalizeOrganizationChildPreferredContact(department, contact),
695
+ )
696
+ .filter(Boolean) as OrgContact[];
697
+ }
698
+
699
+ /*
700
+ * Return the child organization's directory with parent-specific preferred contacts applied.
701
+ */
702
+ export function getOrganizationChildMergedDirectory(
703
+ childOrganization?: OrganizationChildContactSource | null,
704
+ ): MergedOrgContact[] {
705
+ const organization = childOrganization?.organization;
706
+
707
+ return mergeOrgDirectory(
708
+ organization?.directory || [],
709
+ getOrganizationChildPreferredContacts(childOrganization),
710
+ );
711
+ }
712
+
713
+ /*
714
+ * Return the primary contact shown for one child organization relationship.
715
+ */
716
+ export function getOrganizationChildPrimaryContact(
717
+ childOrganization?: OrganizationChildContactSource | null,
718
+ ): MergedOrgContact | null {
719
+ const directory = getOrganizationChildMergedDirectory(childOrganization);
720
+
721
+ return (
722
+ directory.find((contact) => contact.department === 'PRIMARY_CONTACT') ||
723
+ directory[0] ||
724
+ null
725
+ );
726
+ }
727
+
728
+ /*
729
+ * Return whether one child-organization list cell should open the organization profile.
730
+ */
731
+ export function isOrganizationChildProfileLinkCellKey(cellKey: string) {
732
+ return (
733
+ cellKey === 'organizationId' ||
734
+ cellKey === 'vendorName' ||
735
+ cellKey === 'name'
736
+ );
737
+ }
738
+
739
+ /*
740
+ * Return the display text used by child-organization lists and Sheet custom source cells.
741
+ */
742
+ export function getOrganizationChildListCellValue(
743
+ childOrganization:
744
+ | OrganizationChildData
745
+ | OrganizationChildGQL
746
+ | OrganizationChildContactSource
747
+ | null
748
+ | undefined,
749
+ cellKey: string,
750
+ ): string {
751
+ const organization = childOrganization?.organization;
752
+ const primaryContact = getOrganizationChildPrimaryContact(childOrganization);
753
+
754
+ switch (cellKey) {
755
+ case 'organizationId': {
756
+ const organizationReadableId =
757
+ organization && 'readableId' in organization
758
+ ? organization.readableId
759
+ : null;
760
+ const organizationId =
761
+ organization && 'id' in organization ? organization.id : null;
762
+ const childOrganizationId =
763
+ childOrganization && 'childId' in childOrganization
764
+ ? childOrganization.childId
765
+ : null;
766
+
767
+ return (
768
+ organizationReadableId ||
769
+ (organizationId
770
+ ? String(organizationId)
771
+ : childOrganizationId
772
+ ? String(childOrganizationId)
773
+ : '')
774
+ );
775
+ }
776
+ case 'name':
777
+ return organization?.name || '';
778
+ case 'phone':
779
+ return primaryContact?.phoneNumber || '';
780
+ case 'email':
781
+ return primaryContact?.emailAddress || '';
782
+ case 'type':
783
+ return organization?.operation || '';
784
+ default:
785
+ return '';
786
+ }
787
+ }
788
+
789
+ /*
790
+ * Return the organization id that backs formula comparisons for a child-organization list cell.
791
+ */
792
+ export function getOrganizationChildListCellFormulaValue(
793
+ childOrganization:
794
+ | OrganizationChildData
795
+ | OrganizationChildGQL
796
+ | OrganizationChildContactSource
797
+ | null
798
+ | undefined,
799
+ formulaValueSource?:
800
+ | SheetCustomRegionSourceColumnFormulaValueSourceEnum
801
+ | string
802
+ | null,
803
+ ): string | null {
804
+ if (formulaValueSource !== 'CHILD_ORGANIZATION_ID') {
805
+ return null;
806
+ }
807
+
808
+ const organization = childOrganization?.organization;
809
+ const organizationId =
810
+ organization && 'id' in organization ? organization.id : null;
811
+ const childOrganizationId =
812
+ childOrganization && 'childId' in childOrganization
813
+ ? childOrganization.childId
814
+ : null;
815
+ const formulaValue = organizationId ?? childOrganizationId ?? null;
816
+
817
+ return formulaValue !== null ? String(formulaValue) : null;
818
+ }
819
+
820
+ /*
821
+ * Return the formula comparison value for a child-organization list cell when only its row id is available.
822
+ */
823
+ export function getOrganizationChildListCellFormulaValueFromId(
824
+ childOrganizationId: string | number | bigint | null | undefined,
825
+ formulaValueSource?:
826
+ | SheetCustomRegionSourceColumnFormulaValueSourceEnum
827
+ | string
828
+ | null,
829
+ ): string | null {
830
+ return formulaValueSource === 'CHILD_ORGANIZATION_ID' &&
831
+ childOrganizationId !== null &&
832
+ childOrganizationId !== undefined
833
+ ? String(childOrganizationId)
834
+ : null;
233
835
  }