@jsb188/mday 1.1.10 → 1.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/package.json +105 -54
  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 +35 -9
  7. package/src/constants/dataTableFieldTypes.generated.ts +63 -0
  8. package/src/constants/docAccess.ts +32 -0
  9. package/src/constants/email.ts +20 -4
  10. package/src/constants/fieldDoc.ts +34 -0
  11. package/src/constants/graphqlReactivity.ts +113 -0
  12. package/src/constants/integration.ts +8 -9
  13. package/src/constants/log.ts +7 -410
  14. package/src/constants/logActivityGroupColors.generated.ts +19 -0
  15. package/src/constants/logTaxonomy.generated.ts +1103 -0
  16. package/src/constants/noteDoc.ts +77 -0
  17. package/src/constants/organization.ts +13 -15
  18. package/src/constants/pageRoute.ts +23 -0
  19. package/src/constants/schedule.ts +220 -0
  20. package/src/constants/scheduleRuleTemplateSeed.ts +138 -0
  21. package/src/constants/scheduleRuleTemplates.generated.ts +145 -0
  22. package/src/constants/sheet.ts +154 -6
  23. package/src/constants/sheetRegionSources.generated.ts +578 -0
  24. package/src/constants/square.ts +6 -6
  25. package/src/constants/storage.ts +56 -7
  26. package/src/constants/usage.ts +79 -0
  27. package/src/schemas/editLogEntry.ts +1010 -777
  28. package/src/schemas/fieldDocsQuery.ts +12 -0
  29. package/src/schemas/inboundContact.ts +60 -55
  30. package/src/schemas/logsQuery.ts +55 -49
  31. package/src/schemas/organization.ts +49 -46
  32. package/src/types/account.d.ts +4 -1
  33. package/src/types/agentDoc.d.ts +64 -0
  34. package/src/types/agentMemory.d.ts +74 -0
  35. package/src/types/campaign.d.ts +683 -0
  36. package/src/types/dataTable.d.ts +175 -256
  37. package/src/types/docAccess.d.ts +96 -0
  38. package/src/types/email.d.ts +83 -12
  39. package/src/types/fieldDoc.d.ts +273 -0
  40. package/src/types/inboundContact.d.ts +2 -1
  41. package/src/types/log.d.ts +209 -341
  42. package/src/types/noteDoc.d.ts +86 -0
  43. package/src/types/organization.d.ts +83 -40
  44. package/src/types/pageRoute.d.ts +48 -0
  45. package/src/types/schedule.d.ts +391 -0
  46. package/src/types/sheet.d.ts +862 -30
  47. package/src/types/storage.d.ts +206 -125
  48. package/src/types/usage.d.ts +106 -0
  49. package/src/types/workflow.d.ts +149 -18
  50. package/src/utils/agentDoc.ts +109 -0
  51. package/src/utils/aiChat.ts +26 -0
  52. package/src/utils/campaign.ts +741 -0
  53. package/src/utils/campaignFormEditor.ts +871 -0
  54. package/src/utils/dataTable.ts +425 -410
  55. package/src/utils/dataTableFieldTypeRegistry.ts +105 -0
  56. package/src/utils/dataTableRealtimeAuthority.ts +209 -0
  57. package/src/utils/dataTableRealtimeSelection.ts +134 -0
  58. package/src/utils/dataTableRowDocument.ts +508 -0
  59. package/src/utils/dataTableSource.ts +230 -0
  60. package/src/utils/docAccess.ts +383 -0
  61. package/src/utils/documentName.ts +53 -0
  62. package/src/utils/email.ts +112 -53
  63. package/src/utils/fieldDoc.ts +113 -0
  64. package/src/utils/log.ts +169 -176
  65. package/src/utils/logRegistryValue.ts +90 -0
  66. package/src/utils/logStoreRead.ts +266 -0
  67. package/src/utils/logTaxonomy.ts +76 -0
  68. package/src/utils/logTaxonomyDisplay.ts +439 -0
  69. package/src/utils/noteDoc.ts +827 -0
  70. package/src/utils/organization.ts +510 -91
  71. package/src/utils/pageRoute.ts +71 -0
  72. package/src/utils/schedule.ts +799 -0
  73. package/src/utils/scheduleEvaluation.ts +1994 -0
  74. package/src/utils/scheduleICS.ts +246 -0
  75. package/src/utils/scheduleRuleTemplates.ts +188 -0
  76. package/src/utils/sheet.ts +4842 -39
  77. package/src/utils/sheetAxisMove.ts +830 -0
  78. package/src/utils/sheetBootstrap.ts +1769 -0
  79. package/src/utils/sheetCommand.ts +423 -0
  80. package/src/utils/sheetExport.ts +238 -0
  81. package/src/utils/sheetFormulaEvaluation.ts +914 -0
  82. package/src/utils/sheetFormulaEvaluator.ts +852 -0
  83. package/src/utils/sheetJournal.ts +78 -0
  84. package/src/utils/sheetNumberFormat.ts +1211 -0
  85. package/src/utils/sheetRegion.ts +374 -0
  86. package/src/utils/sheetRegionFilter.ts +1259 -0
  87. package/src/utils/sheetRegionSourceRegistry.ts +594 -0
  88. package/src/utils/sheetSequence.ts +148 -0
  89. package/src/utils/sheetSnapshot.ts +992 -0
  90. package/src/utils/sheetStructureEdit.ts +1284 -0
  91. package/src/utils/square.ts +22 -12
  92. package/src/utils/storage.ts +152 -0
  93. package/src/utils/table-route.ts +127 -11
  94. package/src/utils/workflow.ts +191 -23
  95. package/tests/dataTableFieldTypeRegistry.test.ts +110 -0
  96. package/tests/docAccess.test.ts +525 -0
  97. package/tests/editLogEntry.test.ts +112 -0
  98. package/tests/noteDoc.test.ts +669 -0
  99. package/tests/schedule.test.ts +693 -0
  100. package/tests/scheduleEvaluation.test.ts +1970 -0
  101. package/tests/scheduleICS.test.ts +208 -0
  102. package/tests/scheduleRuleTemplates.test.ts +176 -0
  103. package/tests/scheduleSweepInvariants.test.ts +428 -0
  104. package/tests/sheetAxisMove.test.ts +343 -0
  105. package/tests/sheetFormulaEvaluator.test.ts +575 -0
  106. package/tests/sheetRegionFilter.test.ts +1135 -0
  107. package/tests/sheetSequence.test.ts +41 -0
  108. package/tests/sheetStructureEdit.test.ts +82 -0
  109. package/tsconfig.json +10 -10
  110. package/vitest.config.ts +8 -0
  111. package/src/constants/log-activityTexts.ts +0 -235
  112. package/src/constants/product.ts +0 -42
  113. package/src/constants/report.ts +0 -44
  114. package/src/schemas/productsQuery.ts +0 -53
  115. package/src/schemas/reportsQuery.ts +0 -20
  116. package/src/types/product.d.ts +0 -84
  117. package/src/types/report.d.ts +0 -290
  118. package/src/utils/product-calEvent.ts +0 -455
  119. package/src/utils/report.ts +0 -158
@@ -1,38 +1,124 @@
1
1
  import { COLORS } from '@jsb188/app/constants/app.ts';
2
- import { intersection } from '@jsb188/app/utils/object.ts';
3
2
  import { shortenToSpace } from '@jsb188/app/utils/string.ts';
4
3
  import { DEFAULT_TIMEZONE } from '@jsb188/app/utils/timeZone.ts';
5
- import { FEATURES_BY_OPERATION } from '../constants/product.ts';
4
+ import { ORG_CONTACTS } from '../constants/organization.ts';
6
5
  import type {
7
- ACLPermissionEnum,
8
- MergedOrgContact,
9
- OrgContact,
10
- OrganizationFeatureEnum,
11
- OrganizationOperationEnum,
12
- OrganizationRelData,
13
- OrganizationRelGQL,
14
- OrganizationRoleEnum,
15
- OrganizationSettingsObj
6
+ ACLPermissionEnum,
7
+ MergedOrgContact,
8
+ OrgContact,
9
+ OrganizationChildData,
10
+ OrganizationChildGQL,
11
+ OrganizationContactData,
12
+ OrganizationDepartmentEnum,
13
+ OrganizationOperationEnum,
14
+ OrganizationRelData,
15
+ OrganizationRelGQL,
16
+ OrganizationRoleEnum,
17
+ OrganizationSettingsObj,
16
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
 
21
- type OperationPermissionTuple = readonly [PermissionCheckFor, ACLPermissionEnum, string];
24
+ type OperationPermissionTuple = readonly [
25
+ PermissionCheckFor,
26
+ ACLPermissionEnum,
27
+ string,
28
+ ];
22
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
+ };
23
45
 
24
46
  export const OPERATION_PERMISSIONS = {
25
- chat: ['viewData', 'READ', 'You do not have permission to chat with AI in this organization.'],
26
- general_read: ['viewData', 'READ', 'You do not have permission to view this organization\'s data.'],
27
- general_write: ['viewData', 'WRITE', 'You do not have permission to write data in this organization.'],
28
- integrations_update: ['integrations', 'MANAGE', 'You do not have permission to manage this organization\'s app connections.'],
29
- ai_inbox_management: ['orgManagement', 'MANAGE', 'You do not have permission to manage this organization\'s AI inbox.'],
30
- ai_inbox_read: ['orgManagement', 'READ', 'You do not have permission to read this organization\'s AI inbox.'],
31
- logs_write: ['logs', 'WRITE', 'You do not have permission to write logs in this organization.'],
32
- org_directory: ['logs', 'WRITE', 'You do not have permission to manage this organization\'s directory book.'],
33
- org_management: ['orgManagement', 'WRITE', 'You do not have permission to edit this organization\'s data.'],
34
- org_sites_update: ['logs', 'WRITE', 'You do not have permission to update organization sites.'],
35
- data_tables_edit: ['viewData', 'MANAGE', 'You do not have permission to edit dataTables in this organization.'],
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
+ ],
36
122
  } as const satisfies OperationPermissionsMap;
37
123
 
38
124
  export type OperationName = keyof typeof OPERATION_PERMISSIONS;
@@ -52,7 +138,9 @@ const ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX = /^[a-z0-9_-]+$/;
52
138
  * Convert free-form input into the closest inbound email handle candidate.
53
139
  */
54
140
 
55
- export function normalizeOrganizationInboundEmailHandle(value?: string | null): string {
141
+ export function normalizeOrganizationInboundEmailHandle(
142
+ value?: string | null,
143
+ ): string {
56
144
  return String(value || '')
57
145
  .trim()
58
146
  .toLowerCase()
@@ -65,15 +153,21 @@ export function normalizeOrganizationInboundEmailHandle(value?: string | null):
65
153
  * Build the default inbound email handle placeholder from an organization name.
66
154
  */
67
155
 
68
- export function buildOrganizationInboundEmailPlaceholder(orgName?: string | null): string {
69
- return normalizeOrganizationInboundEmailHandle(shortenToSpace(String(orgName || ''), 20));
156
+ export function buildOrganizationInboundEmailPlaceholder(
157
+ orgName?: string | null,
158
+ ): string {
159
+ return normalizeOrganizationInboundEmailHandle(
160
+ shortenToSpace(String(orgName || ''), 20),
161
+ );
70
162
  }
71
163
 
72
164
  /*
73
165
  * Keep typed input limited to the inbound email handle character set.
74
166
  */
75
167
 
76
- export function sanitizeOrganizationInboundEmailHandleInput(value?: string | null): string {
168
+ export function sanitizeOrganizationInboundEmailHandleInput(
169
+ value?: string | null,
170
+ ): string {
77
171
  return String(value || '')
78
172
  .toLowerCase()
79
173
  .replace(/[^a-z0-9_-]+/g, '')
@@ -85,7 +179,9 @@ export function sanitizeOrganizationInboundEmailHandleInput(value?: string | nul
85
179
  * Check whether a normalized inbound email handle is valid to store.
86
180
  */
87
181
 
88
- export function isValidOrganizationInboundEmailHandle(value?: string | null): boolean {
182
+ export function isValidOrganizationInboundEmailHandle(
183
+ value?: string | null,
184
+ ): boolean {
89
185
  const handle = String(value || '');
90
186
 
91
187
  return !!(
@@ -103,20 +199,16 @@ const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
103
199
  */
104
200
 
105
201
  export function getRoleValue(role: OrganizationRoleEnum): number {
106
- return [
107
- 'GUEST',
108
- 'MEMBER',
109
- 'MANAGER',
110
- 'ADMIN',
111
- 'OWNER',
112
- ].indexOf(role);
202
+ return ['GUEST', 'MEMBER', 'MANAGER', 'ADMIN', 'OWNER'].indexOf(role);
113
203
  }
114
204
 
115
205
  /**
116
206
  * Get default permissions by role
117
207
  */
118
208
 
119
- export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization) {
209
+ export function getDefaultPermissionsByRole(
210
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization,
211
+ ) {
120
212
  const role = orgRel?.role || 'MEMBER';
121
213
  const acl: Record<string, any> = { ...orgRel?.acl };
122
214
 
@@ -146,7 +238,7 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
146
238
  logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
147
239
  members: acl.members || 'MANAGE',
148
240
  orgManagement: acl.orgManagement || 'MANAGE',
149
- products: acl.products || 'MANAGE', // products = reports
241
+ products: acl.products || 'MANAGE', // products = field docs
150
242
  settings: acl.settings || 'MANAGE',
151
243
  viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
152
244
  };
@@ -174,7 +266,7 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
174
266
  logs: acl.logs || 'NONE',
175
267
  members: acl.members || 'NONE',
176
268
  orgManagement: acl.orgManagement || 'NONE',
177
- products: acl.products || 'READ', // products = reports
269
+ products: acl.products || 'READ', // products = field docs
178
270
  settings: acl.settings || 'NONE',
179
271
  viewData: acl.viewData || 'READ',
180
272
  };
@@ -191,7 +283,7 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
191
283
  logs: acl.logs || 'WRITE', // "READ" for logs does nothing, also "WRITE" is required for directory/site management
192
284
  members: acl.members || 'READ',
193
285
  orgManagement: acl.orgManagement || 'READ',
194
- products: acl.products || 'READ', // products = reports
286
+ products: acl.products || 'READ', // products = field docs
195
287
  settings: acl.settings || 'READ',
196
288
  viewData: acl.viewData || 'WRITE',
197
289
  };
@@ -201,11 +293,18 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
201
293
  * Check if this account's ACL has required permissions for an action
202
294
  */
203
295
 
204
- export type PermissionCheckFor = keyof ReturnType<typeof getDefaultPermissionsByRole>;
296
+ export type PermissionCheckFor = keyof ReturnType<
297
+ typeof getDefaultPermissionsByRole
298
+ >;
205
299
  export type ACLPermissionCheck = 'READ' | 'WRITE' | 'MANAGE';
206
300
 
207
301
  export function checkACLPermission(
208
- orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
302
+ orgRel:
303
+ | OrganizationRelGQL
304
+ | OrganizationRelData
305
+ | ViewerOrganization
306
+ | null
307
+ | undefined,
209
308
  check: PermissionCheckFor,
210
309
  requiredPermission: ACLPermissionCheck,
211
310
  ): boolean | null {
@@ -226,15 +325,21 @@ export function checkACLPermission(
226
325
  */
227
326
 
228
327
  export function checkACL(
229
- orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
230
- opName: OperationName,
328
+ orgRel:
329
+ | OrganizationRelGQL
330
+ | OrganizationRelData
331
+ | ViewerOrganization
332
+ | null
333
+ | undefined,
334
+ opName: OperationName,
231
335
  ) {
232
- const [permissionCheckFor, requiredPermission] = OPERATION_PERMISSIONS[opName] || [];
233
- if (!permissionCheckFor || !requiredPermission) {
234
- console.warn(`Operation ${opName} not found in permissions map.`);
235
- return null;
236
- }
237
- return checkACLPermission(orgRel, permissionCheckFor, requiredPermission);
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);
238
343
  }
239
344
 
240
345
  /**
@@ -243,7 +348,12 @@ export function checkACL(
243
348
  */
244
349
 
245
350
  export function isCustomACLForRole(
246
- orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
351
+ orgRel:
352
+ | OrganizationRelGQL
353
+ | OrganizationRelData
354
+ | ViewerOrganization
355
+ | null
356
+ | undefined,
247
357
  ): boolean {
248
358
  if (!orgRel) {
249
359
  return false;
@@ -259,7 +369,10 @@ export function isCustomACLForRole(
259
369
 
260
370
  const effectiveACL = getDefaultPermissionsByRole(orgRel);
261
371
  for (const aclKey in roleDefaultACL) {
262
- if (effectiveACL[aclKey as PermissionCheckFor] !== roleDefaultACL[aclKey as PermissionCheckFor]) {
372
+ if (
373
+ effectiveACL[aclKey as PermissionCheckFor] !==
374
+ roleDefaultACL[aclKey as PermissionCheckFor]
375
+ ) {
263
376
  return true;
264
377
  }
265
378
  }
@@ -275,54 +388,71 @@ export function isCustomACLForRole(
275
388
 
276
389
  export function getDefaultOrganizationSettings(
277
390
  timeZone: string | null,
278
- contacts?: OrgContact[],
279
391
  // do params here for priority service + manage roles
280
392
  ): Partial<OrganizationSettingsObj> {
281
- const orgSettings: Record<string, any> = {
393
+ return {
282
394
  timeZone: timeZone || DEFAULT_TIMEZONE,
283
395
  color: COLORS[Math.floor(Math.random() * COLORS.length)],
284
396
  };
285
-
286
- if (contacts?.length) {
287
- orgSettings.directory = contacts.map((contact) => {
288
- return {
289
- ...contact,
290
- department: contact.department || 'OTHER',
291
- };
292
- }).filter((contact) => contact.emailAddress || contact.phoneNumber);
293
- }
294
-
295
- return orgSettings;
296
397
  }
297
398
 
298
- /**
299
- * Get the enabled features for the organization;
300
- * If none or empty, return the default features based on operation
399
+ /*
400
+ * Map organization_contacts rows to plain directory contacts, ordered by department.
301
401
  */
302
-
303
- export function getOrganizationFeatures(
304
- operation: OrganizationOperationEnum,
305
- enabledFeatures?: OrganizationFeatureEnum[] | null,
306
- ): OrganizationFeatureEnum[] {
307
- // @ts-expect-error - Allow operation as string
308
- const allowedFeatures = FEATURES_BY_OPERATION[operation] || [];
309
- const filteredFeatures = intersection(enabledFeatures || [], allowedFeatures);
310
- return filteredFeatures.length ? filteredFeatures : allowedFeatures[0] ? [allowedFeatures[0]] : [];
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
+ );
311
417
  }
312
418
 
313
- /**
314
- * Map organization feature to a color (used for workflows without logType)
315
- * @param feature - The feature of the workflow
316
- * @returns The color associated with the feature
419
+ /*
420
+ * Map parent-override organization_contacts rows to the department-keyed preferred contacts shape.
317
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
+ }
318
433
 
319
- export function getOrganizationFeatureColor(feature?: OrganizationFeatureEnum | null) {
320
- const featureToColor = {
321
- FOOD_SAFETY: 'sky',
322
- GLOBAL_GAP: 'brown',
323
- } as Record<OrganizationFeatureEnum, string>;
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
+ }
324
454
 
325
- return (feature && featureToColor[feature]) || 'stone';
455
+ return { ownRows, overrideRows };
326
456
  }
327
457
 
328
458
  /**
@@ -335,11 +465,11 @@ function hasPreferredOverride(dirContact: OrgContact, preferred?: OrgContact) {
335
465
  }
336
466
 
337
467
  return (
338
- preferred.name !== undefined && preferred.name !== dirContact.name
339
- ) || (
340
- preferred.phoneNumber !== undefined && preferred.phoneNumber !== dirContact.phoneNumber
341
- ) || (
342
- preferred.emailAddress !== undefined && preferred.emailAddress !== dirContact.emailAddress
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)
343
473
  );
344
474
  }
345
475
 
@@ -414,3 +544,292 @@ export function mergeOrgDirectory(
414
544
 
415
545
  return merged;
416
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;
835
+ }