@jsb188/mday 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.
Files changed (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +22 -0
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,669 @@
1
+ import type { SupportedLogLanguage } from '@jsb188/app/constants/app.ts';
2
+ import { COLORS, isSupportedLogLanguage } from '@jsb188/app/constants/app.ts';
3
+ import { shortenToSpace } from '@jsb188/app/utils/string.ts';
4
+ import { DEFAULT_TIMEZONE } from '@jsb188/app/utils/timeZone.ts';
5
+ import { ORG_CONTACTS } from '../constants/organization.ts';
6
+ import type {
7
+ ACLPermissionEnum,
8
+ MergedOrgContact,
9
+ OrganizationChildData,
10
+ OrganizationChildGQL,
11
+ OrganizationContactData,
12
+ OrganizationDepartmentEnum,
13
+ OrganizationOperationEnum,
14
+ OrganizationRelData,
15
+ OrganizationRelGQL,
16
+ OrganizationRoleEnum,
17
+ OrganizationSettingsObj,
18
+ OrgContact,
19
+ } from '../types/organization.d.ts';
20
+
21
+ // Placeholder to match Server import
22
+ type ViewerOrganization = any;
23
+
24
+ type OperationPermissionTuple = readonly [PermissionCheckFor, ACLPermissionEnum, string];
25
+ type OperationPermissionsMap = Record<string, OperationPermissionTuple>;
26
+ type OrganizationChildPreferredContacts = OrgContact[] | Record<string, Partial<OrgContact> | null | undefined> | null | undefined;
27
+ type OrganizationChildContactSource = {
28
+ organization?: {
29
+ id?: string | number | bigint | null;
30
+ readableId?: string | null;
31
+ directory?: OrgContact[] | null;
32
+ name?: string | null;
33
+ operation?: OrganizationOperationEnum | string | null;
34
+ } | null;
35
+ preferredContacts?: OrganizationChildPreferredContacts;
36
+ };
37
+
38
+ export const OPERATION_PERMISSIONS = {
39
+ billing_read: ['billing', 'READ', "You do not have permission to view this organization's billing usage."],
40
+ billing_manage: ['billing', 'MANAGE', "You do not have permission to manage this organization's billing."],
41
+ chat: ['viewData', 'READ', 'You do not have permission to chat with AI in this organization.'],
42
+ campaign_edit: ['products', 'WRITE', 'You do not have permission to edit campaigns in this organization.'],
43
+ general_read: ['viewData', 'READ', "You do not have permission to view this organization's data."],
44
+ general_write: ['viewData', 'WRITE', 'You do not have permission to write data in this organization.'],
45
+ integrations_update: ['integrations', 'MANAGE', "You do not have permission to manage this organization's app connections."],
46
+ ai_inbox_management: ['orgManagement', 'MANAGE', "You do not have permission to manage this organization's AI inbox."],
47
+ ai_inbox_read: ['orgManagement', 'READ', "You do not have permission to read this organization's AI inbox."],
48
+ logs_write: ['logs', 'WRITE', 'You do not have permission to write logs in this organization.'],
49
+ member_sessions_manage: ['members', 'MANAGE', 'You do not have permission to manage member sessions in this organization.'],
50
+ org_directory: ['logs', 'WRITE', "You do not have permission to manage this organization's directory book."],
51
+ agent_notes_manage: ['viewData', 'MANAGE', 'You do not have permission to manage AI notes in this organization.'],
52
+ org_management: ['orgManagement', 'WRITE', "You do not have permission to edit this organization's data."],
53
+ org_settings_manage: ['settings', 'MANAGE', "You do not have permission to manage this organization's settings."],
54
+ org_sites_update: ['logs', 'WRITE', 'You do not have permission to update organization sites.'],
55
+ schedule_edit: ['viewData', 'MANAGE', 'You do not have permission to edit schedules in this organization.'],
56
+ sheets_edit: ['viewData', 'MANAGE', 'You do not have permission to edit sheets & data tables in this organization.'],
57
+ } as const satisfies OperationPermissionsMap;
58
+
59
+ export type OperationName = keyof typeof OPERATION_PERMISSIONS;
60
+
61
+ export const PERMISSION_TO_INT = {
62
+ NONE: 0,
63
+ READ: 1,
64
+ WRITE: 2,
65
+ MANAGE: 3,
66
+ };
67
+
68
+ export const ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH = 40;
69
+
70
+ const ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX = /^[a-z0-9_-]+$/;
71
+
72
+ /*
73
+ * Convert free-form input into the closest inbound email handle candidate.
74
+ */
75
+
76
+ export function normalizeOrganizationInboundEmailHandle(value?: string | null): string {
77
+ return String(value || '')
78
+ .trim()
79
+ .toLowerCase()
80
+ .replace(/[^a-z0-9_-]+/g, '')
81
+ .replace(/[-_]{2,}/g, (match) => match[0])
82
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
83
+ }
84
+
85
+ /*
86
+ * Build the default inbound email handle placeholder from an organization name.
87
+ */
88
+
89
+ export function buildOrganizationInboundEmailPlaceholder(orgName?: string | null): string {
90
+ return normalizeOrganizationInboundEmailHandle(shortenToSpace(String(orgName || ''), 20));
91
+ }
92
+
93
+ /*
94
+ * Keep typed input limited to the inbound email handle character set.
95
+ */
96
+
97
+ export function sanitizeOrganizationInboundEmailHandleInput(value?: string | null): string {
98
+ return String(value || '')
99
+ .toLowerCase()
100
+ .replace(/[^a-z0-9_-]+/g, '')
101
+ .replace(/[-_]{2,}/g, (match) => match[0])
102
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
103
+ }
104
+
105
+ /*
106
+ * Check whether a normalized inbound email handle is valid to store.
107
+ */
108
+
109
+ export function isValidOrganizationInboundEmailHandle(value?: string | null): boolean {
110
+ const handle = String(value || '');
111
+
112
+ return !!(handle && handle.length <= ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH && ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX.test(handle));
113
+ }
114
+
115
+ const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
116
+
117
+ /**
118
+ * Get numeric value of role's permission level (used for comparisons)
119
+ * @param role - Role enum
120
+ */
121
+
122
+ export function getRoleValue(role: OrganizationRoleEnum): number {
123
+ return ['GUEST', 'MEMBER', 'MANAGER', 'ADMIN', 'OWNER'].indexOf(role);
124
+ }
125
+
126
+ /**
127
+ * Get default permissions by role
128
+ */
129
+
130
+ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization) {
131
+ const role = orgRel?.role || 'MEMBER';
132
+ const acl: Record<string, any> = { ...orgRel?.acl };
133
+
134
+ for (const key in acl) {
135
+ // if (typeof acl[key] === 'number') {
136
+ if (!isNaN(Number(acl[key]))) {
137
+ acl[key] = INT_TO_PERMISSION[acl[key]] || 'NONE';
138
+ }
139
+ }
140
+
141
+ // Also keep this synced with [resolvers/organizationTypeResolvers.ts]
142
+
143
+ // 3 = "MANAGE"
144
+ // 2 = "WRITE"
145
+ // 1 = "READ"
146
+ // 0 = "NONE"
147
+
148
+ switch (role) {
149
+ case 'OWNER':
150
+ return {
151
+ billing: 'MANAGE',
152
+ compliance: 'MANAGE',
153
+ digests: 'MANAGE',
154
+ finances: 'MANAGE',
155
+ integrations: 'MANAGE',
156
+ logs: 'MANAGE',
157
+ members: 'MANAGE',
158
+ orgManagement: 'MANAGE',
159
+ products: 'MANAGE',
160
+ settings: 'MANAGE',
161
+ viewData: 'MANAGE',
162
+ };
163
+ case 'ADMIN':
164
+ return {
165
+ billing: acl.billing || 'MANAGE',
166
+ compliance: acl.compliance || 'MANAGE',
167
+ digests: acl.digests || 'MANAGE', // 2/3 = receive digests, 1 = only see from web app
168
+ finances: acl.finances || 'MANAGE',
169
+ integrations: acl.integrations || 'MANAGE',
170
+ logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
171
+ members: acl.members || 'MANAGE',
172
+ orgManagement: acl.orgManagement || 'MANAGE',
173
+ products: acl.products || 'MANAGE', // products = field docs
174
+ settings: acl.settings || 'MANAGE',
175
+ viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
176
+ };
177
+ case 'MANAGER':
178
+ return {
179
+ billing: acl.billing || 'READ',
180
+ compliance: acl.compliance || 'WRITE',
181
+ digests: acl.digests || 'READ', // 2/3 = receive digests, 1 = only see from web app
182
+ finances: acl.finances || 'READ',
183
+ integrations: acl.integrations || 'NONE',
184
+ logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
185
+ members: acl.members || 'WRITE',
186
+ orgManagement: acl.orgManagement || 'WRITE',
187
+ products: acl.products || 'READ',
188
+ settings: acl.settings || 'READ',
189
+ viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
190
+ };
191
+ case 'GUEST':
192
+ return {
193
+ billing: acl.billing || 'NONE',
194
+ compliance: acl.compliance || 'NONE',
195
+ digests: acl.digests || 'NONE',
196
+ finances: acl.finances || 'NONE',
197
+ integrations: acl.integrations || 'NONE',
198
+ logs: acl.logs || 'NONE',
199
+ members: acl.members || 'NONE',
200
+ orgManagement: acl.orgManagement || 'NONE',
201
+ products: acl.products || 'READ', // products = field docs
202
+ settings: acl.settings || 'NONE',
203
+ viewData: acl.viewData || 'READ',
204
+ };
205
+ case 'MEMBER':
206
+ default:
207
+ }
208
+
209
+ return {
210
+ billing: acl.billing || 'NONE',
211
+ compliance: acl.compliance || 'READ',
212
+ digests: acl.digests || 'NONE', // 2/3 = receive digests, 1 = only see from web app
213
+ finances: acl.finances || 'NONE',
214
+ integrations: acl.integrations || 'NONE',
215
+ logs: acl.logs || 'WRITE', // "READ" for logs does nothing, also "WRITE" is required for directory/site management
216
+ members: acl.members || 'READ',
217
+ orgManagement: acl.orgManagement || 'READ',
218
+ products: acl.products || 'READ', // products = field docs
219
+ settings: acl.settings || 'READ',
220
+ viewData: acl.viewData || 'WRITE',
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Check if this account's ACL has required permissions for an action
226
+ */
227
+
228
+ export type PermissionCheckFor = keyof ReturnType<typeof getDefaultPermissionsByRole>;
229
+ export type ACLPermissionCheck = 'READ' | 'WRITE' | 'MANAGE';
230
+
231
+ export function checkACLPermission(
232
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
233
+ check: PermissionCheckFor,
234
+ requiredPermission: ACLPermissionCheck,
235
+ ): boolean | null {
236
+ if (!orgRel) {
237
+ return null;
238
+ }
239
+
240
+ const acl = getDefaultPermissionsByRole(orgRel);
241
+ const requiredInt = PERMISSION_TO_INT[requiredPermission] || 4; // If invalid, it will always return false
242
+ const permission = acl[check] as ACLPermissionCheck;
243
+ const acccountPermissionInt = PERMISSION_TO_INT[permission] || 0; // If invalid, it will always return false
244
+
245
+ return acccountPermissionInt >= requiredInt;
246
+ }
247
+
248
+ /**
249
+ * Check ACL permission from pre-defined constants
250
+ */
251
+
252
+ export function checkACL(
253
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
254
+ opName: OperationName,
255
+ ) {
256
+ const [permissionCheckFor, requiredPermission] = OPERATION_PERMISSIONS[opName] || [];
257
+ if (!permissionCheckFor || !requiredPermission) {
258
+ console.warn(`Operation ${opName} not found in permissions map.`);
259
+ return null;
260
+ }
261
+ return checkACLPermission(orgRel, permissionCheckFor, requiredPermission);
262
+ }
263
+
264
+ /**
265
+ * Check whether the user's ACL differs from role defaults
266
+ * @returns true if at least one ACL permission differs from default role ACL
267
+ */
268
+
269
+ export function isCustomACLForRole(orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined): boolean {
270
+ if (!orgRel) {
271
+ return false;
272
+ }
273
+ if (orgRel.role === 'OWNER') {
274
+ return false;
275
+ }
276
+
277
+ const roleDefaultACL = getDefaultPermissionsByRole({
278
+ role: orgRel.role,
279
+ acl: {},
280
+ } as OrganizationRelGQL);
281
+
282
+ const effectiveACL = getDefaultPermissionsByRole(orgRel);
283
+ for (const aclKey in roleDefaultACL) {
284
+ if (effectiveACL[aclKey as PermissionCheckFor] !== roleDefaultACL[aclKey as PermissionCheckFor]) {
285
+ return true;
286
+ }
287
+ }
288
+
289
+ return false;
290
+ }
291
+
292
+ /**
293
+ * Get the default object for Oganization settings
294
+ * @param timeZone - Time zone string
295
+ * @return Default organization settings object
296
+ */
297
+
298
+ export function getDefaultOrganizationSettings(
299
+ timeZone: string | null,
300
+ // do params here for priority service + manage roles
301
+ ): Partial<OrganizationSettingsObj> {
302
+ return {
303
+ timeZone: timeZone || DEFAULT_TIMEZONE,
304
+ displayTranslatedLogs: true,
305
+ translateLanguage: 'en',
306
+ color: COLORS[Math.floor(Math.random() * COLORS.length)],
307
+ };
308
+ }
309
+
310
+ /*
311
+ * Return one effective organization log-language setting while preserving an explicit disabled value.
312
+ */
313
+ export function getOrganizationLogLanguageSetting(
314
+ settings: Partial<OrganizationSettingsObj> | Record<string, unknown> | null | undefined,
315
+ settingName: 'translateLanguage',
316
+ ): SupportedLogLanguage | null {
317
+ const value = settings?.[settingName];
318
+
319
+ if (value === null) {
320
+ return null;
321
+ }
322
+
323
+ return isSupportedLogLanguage(value) ? value : 'en';
324
+ }
325
+
326
+ /*
327
+ * Return whether organization log views should prefer available translated text.
328
+ */
329
+ export function getOrganizationDisplayTranslatedLogsSetting(
330
+ settings: Partial<OrganizationSettingsObj> | Record<string, unknown> | null | undefined,
331
+ ): boolean {
332
+ return typeof settings?.displayTranslatedLogs === 'boolean' ? settings.displayTranslatedLogs : true;
333
+ }
334
+
335
+ /*
336
+ * Resolve the translation locale used by read-only log views, or null when
337
+ * the organization prefers original text or has translation disabled.
338
+ */
339
+ export function getOrganizationLogDisplayLanguage(
340
+ settings: Partial<OrganizationSettingsObj> | Record<string, unknown> | null | undefined,
341
+ ): SupportedLogLanguage | null {
342
+ return getOrganizationDisplayTranslatedLogsSetting(settings)
343
+ ? getOrganizationLogLanguageSetting(settings, 'translateLanguage')
344
+ : null;
345
+ }
346
+
347
+ /*
348
+ * Map organization_contacts rows to plain directory contacts, ordered by department.
349
+ */
350
+ export function mapOrgContactRowsToContacts(rows?: Array<Partial<OrganizationContactData>> | null): OrgContact[] {
351
+ return (rows || [])
352
+ .filter((row) => row.department)
353
+ .map((row) => ({
354
+ department: row.department as OrganizationDepartmentEnum,
355
+ name: row.name || null,
356
+ phoneNumber: row.phoneNumber || null,
357
+ emailAddress: row.emailAddress || null,
358
+ }))
359
+ .sort((a, b) => ORG_CONTACTS.indexOf(a.department) - ORG_CONTACTS.indexOf(b.department));
360
+ }
361
+
362
+ /*
363
+ * Map parent-override organization_contacts rows to the department-keyed preferred contacts shape.
364
+ */
365
+ export function mapOrgContactRowsToPreferredContactsMap(
366
+ rows?: Array<Partial<OrganizationContactData>> | null,
367
+ ): Record<string, OrgContact> {
368
+ return mapOrgContactRowsToContacts(rows).reduce(
369
+ (acc, contact) => {
370
+ acc[contact.department] = contact;
371
+ return acc;
372
+ },
373
+ {} as Record<string, OrgContact>,
374
+ );
375
+ }
376
+
377
+ /*
378
+ * Split one org's contact rows into own-directory rows and one parent's override rows.
379
+ */
380
+ export function splitOrgContactRowsByScope(
381
+ rows: Array<Partial<OrganizationContactData>>,
382
+ ownerOrgId?: number | bigint | null,
383
+ ): {
384
+ ownRows: Array<Partial<OrganizationContactData>>;
385
+ overrideRows: Array<Partial<OrganizationContactData>>;
386
+ } {
387
+ const ownRows: Array<Partial<OrganizationContactData>> = [];
388
+ const overrideRows: Array<Partial<OrganizationContactData>> = [];
389
+
390
+ for (const row of rows) {
391
+ if (row.ownerOrgId == null) {
392
+ ownRows.push(row);
393
+ } else if (ownerOrgId != null && row.ownerOrgId == ownerOrgId) {
394
+ overrideRows.push(row);
395
+ }
396
+ }
397
+
398
+ return { ownRows, overrideRows };
399
+ }
400
+
401
+ /**
402
+ * Check if preferred contact overrides at least one directory field.
403
+ */
404
+
405
+ function hasPreferredOverride(dirContact: OrgContact, preferred?: OrgContact) {
406
+ if (!preferred) {
407
+ return false;
408
+ }
409
+
410
+ return (
411
+ (preferred.name !== undefined && preferred.name !== dirContact.name) ||
412
+ (preferred.phoneNumber !== undefined && preferred.phoneNumber !== dirContact.phoneNumber) ||
413
+ (preferred.emailAddress !== undefined && preferred.emailAddress !== dirContact.emailAddress)
414
+ );
415
+ }
416
+
417
+ /**
418
+ * Merge directory with preferred contacts
419
+ */
420
+
421
+ export function mergeOrgDirectory(
422
+ directory: OrgContact[],
423
+ preferredContacts?: OrgContact[],
424
+ duplicateOrgContacts: boolean = false,
425
+ ): MergedOrgContact[] {
426
+ if (!preferredContacts?.length) {
427
+ return directory || [];
428
+ }
429
+
430
+ // Create a map of preferredContacts by department
431
+ const preferredMap = new Map<string, OrgContact>();
432
+ for (const contact of preferredContacts) {
433
+ if (contact.department) {
434
+ preferredMap.set(contact.department, contact);
435
+ }
436
+ }
437
+
438
+ // Merge directory with preferred contacts, removing matched entries from map
439
+ const merged: MergedOrgContact[] = [];
440
+ for (const dirContact of directory || []) {
441
+ const preferred = preferredMap.get(dirContact.department);
442
+ const hasOverride = hasPreferredOverride(dirContact, preferred);
443
+ const hasPreferredContact = !!preferred;
444
+ preferredMap.delete(dirContact.department);
445
+
446
+ const mergedContact: MergedOrgContact = {
447
+ department: dirContact.department,
448
+ name: preferred?.name ?? dirContact.name,
449
+ phoneNumber: preferred?.phoneNumber ?? dirContact.phoneNumber,
450
+ emailAddress: preferred?.emailAddress ?? dirContact.emailAddress,
451
+ defaultName: dirContact.name,
452
+ defaultPhoneNumber: dirContact.phoneNumber,
453
+ defaultEmailAddress: dirContact.emailAddress,
454
+ officialContact: !hasPreferredContact,
455
+ };
456
+ merged.push(mergedContact);
457
+
458
+ if (duplicateOrgContacts && hasOverride) {
459
+ merged.push({
460
+ department: dirContact.department,
461
+ name: dirContact.name,
462
+ phoneNumber: dirContact.phoneNumber,
463
+ emailAddress: dirContact.emailAddress,
464
+ defaultName: dirContact.name,
465
+ defaultPhoneNumber: dirContact.phoneNumber,
466
+ defaultEmailAddress: dirContact.emailAddress,
467
+ officialContact: true,
468
+ locked: true,
469
+ });
470
+ }
471
+ }
472
+
473
+ // Add remaining preferred contacts (not in directory)
474
+ for (const [, preferred] of preferredMap) {
475
+ merged.push({
476
+ department: preferred.department,
477
+ name: preferred.name,
478
+ phoneNumber: preferred.phoneNumber,
479
+ emailAddress: preferred.emailAddress,
480
+ defaultName: null,
481
+ defaultPhoneNumber: null,
482
+ defaultEmailAddress: null,
483
+ });
484
+ }
485
+
486
+ return merged;
487
+ }
488
+
489
+ /*
490
+ * Upsert one preferred contact by department without mutating the source list.
491
+ */
492
+ export function upsertOrgPreferredContactByDepartment(
493
+ preferredContacts: OrgContact[] | undefined,
494
+ department: OrgContact['department'],
495
+ values: Partial<Pick<OrgContact, 'emailAddress' | 'name' | 'phoneNumber'>>,
496
+ ): OrgContact[] {
497
+ const source = preferredContacts || [];
498
+ const nextContact: OrgContact = {
499
+ department,
500
+ name: values.name || null,
501
+ phoneNumber: values.phoneNumber || null,
502
+ emailAddress: values.emailAddress || null,
503
+ };
504
+
505
+ if (!source.some((contact) => contact.department === department)) {
506
+ return [...source, nextContact];
507
+ }
508
+
509
+ return source.map((contact) => (contact.department === department ? nextContact : contact));
510
+ }
511
+
512
+ /*
513
+ * Remove one preferred contact department without mutating the source list.
514
+ */
515
+ export function removeOrgPreferredContactByDepartment(
516
+ preferredContacts: OrgContact[] | undefined,
517
+ department: OrgContact['department'],
518
+ ): OrgContact[] {
519
+ return (preferredContacts || []).filter((contact) => contact.department !== department);
520
+ }
521
+
522
+ /*
523
+ * Restore one preferred contact department from a saved contact snapshot.
524
+ */
525
+ export function restoreOrgPreferredContactByDepartment(
526
+ currentPreferredContacts: OrgContact[] | undefined,
527
+ savedPreferredContacts: OrgContact[] | undefined,
528
+ department: OrgContact['department'],
529
+ ): OrgContact[] {
530
+ const savedContact = (savedPreferredContacts || []).find((contact) => contact.department === department);
531
+ const withoutDepartment = (currentPreferredContacts || []).filter((contact) => contact.department !== department);
532
+
533
+ return savedContact ? [...withoutDepartment, savedContact] : withoutDepartment;
534
+ }
535
+
536
+ /*
537
+ * Find the editable version of a merged contact department.
538
+ */
539
+ export function getEditableOrgContactByDepartment(
540
+ list: MergedOrgContact[],
541
+ department: OrgContact['department'],
542
+ ): MergedOrgContact | null {
543
+ return list.find((item) => item.department === department && !item.locked) || null;
544
+ }
545
+
546
+ /*
547
+ * Compare preferred-contact lists by normalized department and value pairs.
548
+ */
549
+ export function areOrgPreferredContactsEqual(a?: OrgContact[] | null, b?: OrgContact[] | null) {
550
+ const sourceA = a || [];
551
+ const sourceB = b || [];
552
+
553
+ if (sourceA.length !== sourceB.length) {
554
+ return false;
555
+ }
556
+
557
+ const normalizedA = [...sourceA].sort((x, y) => x.department.localeCompare(y.department));
558
+ const normalizedB = [...sourceB].sort((x, y) => x.department.localeCompare(y.department));
559
+
560
+ return normalizedA.every((item, index) => {
561
+ const other = normalizedB[index];
562
+
563
+ return (
564
+ item.department === other.department &&
565
+ (item.name || null) === (other.name || null) &&
566
+ (item.phoneNumber || null) === (other.phoneNumber || null) &&
567
+ (item.emailAddress || null) === (other.emailAddress || null)
568
+ );
569
+ });
570
+ }
571
+
572
+ /*
573
+ * Return one preferred contact with a department supplied from the map key when needed.
574
+ */
575
+ function normalizeOrganizationChildPreferredContact(department: string, contact?: Partial<OrgContact> | null): OrgContact | null {
576
+ if (!contact) {
577
+ return null;
578
+ }
579
+
580
+ const contactDepartment = contact.department || (department as OrganizationDepartmentEnum);
581
+
582
+ if (!contactDepartment) {
583
+ return null;
584
+ }
585
+
586
+ return {
587
+ department: contactDepartment,
588
+ name: contact.name,
589
+ phoneNumber: contact.phoneNumber,
590
+ emailAddress: contact.emailAddress,
591
+ };
592
+ }
593
+
594
+ /*
595
+ * Return preferred child-organization contacts in the array shape expected by directory helpers.
596
+ */
597
+ export function getOrganizationChildPreferredContacts(childOrganization?: OrganizationChildContactSource | null): OrgContact[] {
598
+ const preferredContacts = childOrganization?.preferredContacts;
599
+
600
+ if (Array.isArray(preferredContacts)) {
601
+ return preferredContacts
602
+ .map((contact) => normalizeOrganizationChildPreferredContact(contact.department, contact))
603
+ .filter(Boolean) as OrgContact[];
604
+ }
605
+
606
+ return Object.entries(preferredContacts || {})
607
+ .map(([department, contact]) => normalizeOrganizationChildPreferredContact(department, contact))
608
+ .filter(Boolean) as OrgContact[];
609
+ }
610
+
611
+ /*
612
+ * Return the child organization's directory with parent-specific preferred contacts applied.
613
+ */
614
+ export function getOrganizationChildMergedDirectory(childOrganization?: OrganizationChildContactSource | null): MergedOrgContact[] {
615
+ const organization = childOrganization?.organization;
616
+
617
+ return mergeOrgDirectory(organization?.directory || [], getOrganizationChildPreferredContacts(childOrganization));
618
+ }
619
+
620
+ /*
621
+ * Return the primary contact shown for one child organization relationship.
622
+ */
623
+ export function getOrganizationChildPrimaryContact(
624
+ childOrganization?: OrganizationChildContactSource | null,
625
+ ): MergedOrgContact | null {
626
+ const directory = getOrganizationChildMergedDirectory(childOrganization);
627
+
628
+ return directory.find((contact) => contact.department === 'PRIMARY_CONTACT') || directory[0] || null;
629
+ }
630
+
631
+ /*
632
+ * Return whether one child-organization list cell should open the organization profile.
633
+ */
634
+ export function isOrganizationChildProfileLinkCellKey(cellKey: string) {
635
+ return cellKey === 'organizationId' || cellKey === 'vendorName' || cellKey === 'name';
636
+ }
637
+
638
+ /*
639
+ * Return the display text used by child-organization lists.
640
+ */
641
+ export function getOrganizationChildListCellValue(
642
+ childOrganization: OrganizationChildData | OrganizationChildGQL | OrganizationChildContactSource | null | undefined,
643
+ cellKey: string,
644
+ ): string {
645
+ const organization = childOrganization?.organization;
646
+ const primaryContact = getOrganizationChildPrimaryContact(childOrganization);
647
+
648
+ switch (cellKey) {
649
+ case 'organizationId': {
650
+ const organizationReadableId = organization && 'readableId' in organization ? organization.readableId : null;
651
+ const organizationId = organization && 'id' in organization ? organization.id : null;
652
+ const childOrganizationId = childOrganization && 'childId' in childOrganization ? childOrganization.childId : null;
653
+
654
+ return (
655
+ organizationReadableId || (organizationId ? String(organizationId) : childOrganizationId ? String(childOrganizationId) : '')
656
+ );
657
+ }
658
+ case 'name':
659
+ return organization?.name || '';
660
+ case 'phone':
661
+ return primaryContact?.phoneNumber || '';
662
+ case 'email':
663
+ return primaryContact?.emailAddress || '';
664
+ case 'type':
665
+ return organization?.operation || '';
666
+ default:
667
+ return '';
668
+ }
669
+ }