@jsb188/mday 1.1.8 → 1.1.10

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 (45) hide show
  1. package/package.json +39 -20
  2. package/src/constants/dataTable.ts +22 -0
  3. package/src/constants/email.ts +28 -0
  4. package/src/constants/inboundContact.ts +8 -0
  5. package/src/constants/integration.ts +14 -0
  6. package/src/constants/log-activityTexts.ts +54 -28
  7. package/src/constants/log.ts +82 -38
  8. package/src/constants/organization.ts +11 -2
  9. package/src/constants/product.ts +9 -33
  10. package/src/constants/report.ts +29 -10
  11. package/src/constants/sheet.ts +20 -0
  12. package/src/constants/square.ts +16 -0
  13. package/src/constants/storage.ts +12 -0
  14. package/src/schemas/editLogEntry.ts +90 -44
  15. package/src/schemas/inboundContact.ts +72 -0
  16. package/src/schemas/logsQuery.ts +7 -272
  17. package/src/schemas/organization.ts +11 -174
  18. package/src/schemas/productsQuery.ts +2 -94
  19. package/src/schemas/reportsQuery.ts +8 -95
  20. package/src/types/account.d.ts +78 -0
  21. package/src/types/dataTable.d.ts +447 -0
  22. package/src/types/email.d.ts +71 -0
  23. package/src/types/inboundContact.d.ts +56 -0
  24. package/src/types/integration.d.ts +42 -0
  25. package/src/types/log.d.ts +289 -178
  26. package/src/types/organization.d.ts +106 -50
  27. package/src/types/product.d.ts +7 -96
  28. package/src/types/report.d.ts +239 -152
  29. package/src/types/sheet.d.ts +298 -0
  30. package/src/types/storage.d.ts +161 -0
  31. package/src/types/workflow.d.ts +174 -0
  32. package/src/utils/dataTable.ts +834 -0
  33. package/src/utils/email.ts +113 -0
  34. package/src/utils/log.ts +30 -628
  35. package/src/utils/organization.ts +227 -44
  36. package/src/utils/product-calEvent.ts +7 -60
  37. package/src/utils/report.ts +158 -0
  38. package/src/utils/sheet.ts +170 -0
  39. package/src/utils/square.ts +22 -0
  40. package/src/utils/table-route.ts +146 -0
  41. package/src/utils/workflow.ts +212 -0
  42. package/tsconfig.json +12 -0
  43. package/src/schemas/childOrganizationsQuery.ts +0 -44
  44. package/src/types/action.d.ts +0 -42
  45. package/src/utils/route-helpers.ts +0 -583
@@ -1,23 +1,42 @@
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 { intersection } from '@jsb188/app/utils/object.ts';
3
+ import { shortenToSpace } from '@jsb188/app/utils/string.ts';
4
+ import { DEFAULT_TIMEZONE } from '@jsb188/app/utils/timeZone.ts';
5
+ import { FEATURES_BY_OPERATION } from '../constants/product.ts';
7
6
  import type {
8
- OrganizationContact,
7
+ ACLPermissionEnum,
8
+ MergedOrgContact,
9
+ OrgContact,
9
10
  OrganizationFeatureEnum,
10
- OrganizationGQL,
11
11
  OrganizationOperationEnum,
12
12
  OrganizationRelData,
13
13
  OrganizationRelGQL,
14
14
  OrganizationRoleEnum,
15
15
  OrganizationSettingsObj
16
- } from '../types/organization.d';
16
+ } from '../types/organization.d.ts';
17
17
 
18
18
  // Placeholder to match Server import
19
19
  type ViewerOrganization = any;
20
20
 
21
+ type OperationPermissionTuple = readonly [PermissionCheckFor, ACLPermissionEnum, string];
22
+ type OperationPermissionsMap = Record<string, OperationPermissionTuple>;
23
+
24
+ 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.'],
36
+ } as const satisfies OperationPermissionsMap;
37
+
38
+ export type OperationName = keyof typeof OPERATION_PERMISSIONS;
39
+
21
40
  export const PERMISSION_TO_INT = {
22
41
  NONE: 0,
23
42
  READ: 1,
@@ -25,6 +44,57 @@ export const PERMISSION_TO_INT = {
25
44
  MANAGE: 3,
26
45
  };
27
46
 
47
+ export const ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH = 40;
48
+
49
+ const ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX = /^[a-z0-9_-]+$/;
50
+
51
+ /*
52
+ * Convert free-form input into the closest inbound email handle candidate.
53
+ */
54
+
55
+ export function normalizeOrganizationInboundEmailHandle(value?: string | null): string {
56
+ return String(value || '')
57
+ .trim()
58
+ .toLowerCase()
59
+ .replace(/[^a-z0-9_-]+/g, '')
60
+ .replace(/[-_]{2,}/g, (match) => match[0])
61
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
62
+ }
63
+
64
+ /*
65
+ * Build the default inbound email handle placeholder from an organization name.
66
+ */
67
+
68
+ export function buildOrganizationInboundEmailPlaceholder(orgName?: string | null): string {
69
+ return normalizeOrganizationInboundEmailHandle(shortenToSpace(String(orgName || ''), 20));
70
+ }
71
+
72
+ /*
73
+ * Keep typed input limited to the inbound email handle character set.
74
+ */
75
+
76
+ export function sanitizeOrganizationInboundEmailHandleInput(value?: string | null): string {
77
+ return String(value || '')
78
+ .toLowerCase()
79
+ .replace(/[^a-z0-9_-]+/g, '')
80
+ .replace(/[-_]{2,}/g, (match) => match[0])
81
+ .substring(0, ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH);
82
+ }
83
+
84
+ /*
85
+ * Check whether a normalized inbound email handle is valid to store.
86
+ */
87
+
88
+ export function isValidOrganizationInboundEmailHandle(value?: string | null): boolean {
89
+ const handle = String(value || '');
90
+
91
+ return !!(
92
+ handle &&
93
+ handle.length <= ORGANIZATION_INBOUND_EMAIL_MAX_LENGTH &&
94
+ ORGANIZATION_INBOUND_EMAIL_ALLOWED_REGEX.test(handle)
95
+ );
96
+ }
97
+
28
98
  const INT_TO_PERMISSION = Object.keys(PERMISSION_TO_INT);
29
99
 
30
100
  /**
@@ -59,10 +129,10 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
59
129
 
60
130
  // Also keep this synced with [resolvers/organizationTypeResolvers.ts]
61
131
 
62
- // 0 = "NONE"
63
- // 1 = "READ"
64
- // 2 = "WRITE"
65
132
  // 3 = "MANAGE"
133
+ // 2 = "WRITE"
134
+ // 1 = "READ"
135
+ // 0 = "NONE"
66
136
 
67
137
  switch (role) {
68
138
  case 'ADMIN':
@@ -76,7 +146,7 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
76
146
  logs: acl.logs || 'MANAGE', // "READ" for logs does nothing
77
147
  members: acl.members || 'MANAGE',
78
148
  orgManagement: acl.orgManagement || 'MANAGE',
79
- products: acl.products || 'MANAGE',
149
+ products: acl.products || 'MANAGE', // products = reports
80
150
  settings: acl.settings || 'MANAGE',
81
151
  viewData: acl.viewData || 'MANAGE', // This blocks access from users being able to read other people's logs
82
152
  };
@@ -104,9 +174,9 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
104
174
  logs: acl.logs || 'NONE',
105
175
  members: acl.members || 'NONE',
106
176
  orgManagement: acl.orgManagement || 'NONE',
107
- products: acl.products || 'READ',
177
+ products: acl.products || 'READ', // products = reports
108
178
  settings: acl.settings || 'NONE',
109
- viewData: acl.viewData || 'NONE',
179
+ viewData: acl.viewData || 'READ',
110
180
  };
111
181
  case 'MEMBER':
112
182
  default:
@@ -118,12 +188,12 @@ export function getDefaultPermissionsByRole(orgRel: OrganizationRelGQL | Organiz
118
188
  digests: acl.digests || 'NONE', // 2/3 = receive digests, 1 = only see from web app
119
189
  finances: acl.finances || 'NONE',
120
190
  integrations: acl.integrations || 'NONE',
121
- logs: acl.logs || 'WRITE', // "READ" for logs does nothing
191
+ logs: acl.logs || 'WRITE', // "READ" for logs does nothing, also "WRITE" is required for directory/site management
122
192
  members: acl.members || 'READ',
123
193
  orgManagement: acl.orgManagement || 'READ',
124
- products: acl.products || 'READ',
194
+ products: acl.products || 'READ', // products = reports
125
195
  settings: acl.settings || 'READ',
126
- viewData: acl.viewData || 'NONE', // This blocks access from users being able to read other people's logs
196
+ viewData: acl.viewData || 'WRITE',
127
197
  };
128
198
  }
129
199
 
@@ -144,7 +214,6 @@ export function checkACLPermission(
144
214
  }
145
215
 
146
216
  const acl = getDefaultPermissionsByRole(orgRel);
147
-
148
217
  const requiredInt = PERMISSION_TO_INT[requiredPermission] || 4; // If invalid, it will always return false
149
218
  const permission = acl[check] as ACLPermissionCheck;
150
219
  const acccountPermissionInt = PERMISSION_TO_INT[permission] || 0; // If invalid, it will always return false
@@ -153,40 +222,49 @@ export function checkACLPermission(
153
222
  }
154
223
 
155
224
  /**
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
225
+ * Check ACL permission from pre-defined constants
160
226
  */
161
227
 
162
- export function getTitleIconsForOrganization(
163
- org: OrganizationGQL,
164
- showIconsRule: Record<string, boolean> = {},
228
+ export function checkACL(
229
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
230
+ opName: OperationName,
165
231
  ) {
166
- const { operation, compliance } = org;
167
- const titleIcons = [];
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);
238
+ }
168
239
 
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
- });
240
+ /**
241
+ * Check whether the user's ACL differs from role defaults
242
+ * @returns true if at least one ACL permission differs from default role ACL
243
+ */
244
+
245
+ export function isCustomACLForRole(
246
+ orgRel: OrganizationRelGQL | OrganizationRelData | ViewerOrganization | null | undefined,
247
+ ): boolean {
248
+ if (!orgRel) {
249
+ return false;
250
+ }
251
+ if (orgRel.role === 'OWNER') {
252
+ return false;
174
253
  }
175
254
 
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);
255
+ const roleDefaultACL = getDefaultPermissionsByRole({
256
+ role: orgRel.role,
257
+ acl: {},
258
+ } as OrganizationRelGQL);
180
259
 
181
- if (notExpired.length > 0) {
182
- titleIcons.push({
183
- iconName: 'document-license',
184
- tooltipText: notExpired.map((item: any) => item.name).join(', '),
185
- });
260
+ const effectiveACL = getDefaultPermissionsByRole(orgRel);
261
+ for (const aclKey in roleDefaultACL) {
262
+ if (effectiveACL[aclKey as PermissionCheckFor] !== roleDefaultACL[aclKey as PermissionCheckFor]) {
263
+ return true;
186
264
  }
187
265
  }
188
266
 
189
- return titleIcons;
267
+ return false;
190
268
  }
191
269
 
192
270
  /**
@@ -197,7 +275,7 @@ export function getTitleIconsForOrganization(
197
275
 
198
276
  export function getDefaultOrganizationSettings(
199
277
  timeZone: string | null,
200
- contacts?: OrganizationContact[],
278
+ contacts?: OrgContact[],
201
279
  // do params here for priority service + manage roles
202
280
  ): Partial<OrganizationSettingsObj> {
203
281
  const orgSettings: Record<string, any> = {
@@ -231,3 +309,108 @@ export function getOrganizationFeatures(
231
309
  const filteredFeatures = intersection(enabledFeatures || [], allowedFeatures);
232
310
  return filteredFeatures.length ? filteredFeatures : allowedFeatures[0] ? [allowedFeatures[0]] : [];
233
311
  }
312
+
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
317
+ */
318
+
319
+ export function getOrganizationFeatureColor(feature?: OrganizationFeatureEnum | null) {
320
+ const featureToColor = {
321
+ FOOD_SAFETY: 'sky',
322
+ GLOBAL_GAP: 'brown',
323
+ } as Record<OrganizationFeatureEnum, string>;
324
+
325
+ return (feature && featureToColor[feature]) || 'stone';
326
+ }
327
+
328
+ /**
329
+ * Check if preferred contact overrides at least one directory field.
330
+ */
331
+
332
+ function hasPreferredOverride(dirContact: OrgContact, preferred?: OrgContact) {
333
+ if (!preferred) {
334
+ return false;
335
+ }
336
+
337
+ 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
343
+ );
344
+ }
345
+
346
+ /**
347
+ * Merge directory with preferred contacts
348
+ */
349
+
350
+ export function mergeOrgDirectory(
351
+ directory: OrgContact[],
352
+ preferredContacts?: OrgContact[],
353
+ duplicateOrgContacts: boolean = false,
354
+ ): MergedOrgContact[] {
355
+ if (!preferredContacts?.length) {
356
+ return directory || [];
357
+ }
358
+
359
+ // Create a map of preferredContacts by department
360
+ const preferredMap = new Map<string, OrgContact>();
361
+ for (const contact of preferredContacts) {
362
+ if (contact.department) {
363
+ preferredMap.set(contact.department, contact);
364
+ }
365
+ }
366
+
367
+ // Merge directory with preferred contacts, removing matched entries from map
368
+ const merged: MergedOrgContact[] = [];
369
+ for (const dirContact of directory || []) {
370
+ const preferred = preferredMap.get(dirContact.department);
371
+ const hasOverride = hasPreferredOverride(dirContact, preferred);
372
+ const hasPreferredContact = !!preferred;
373
+ preferredMap.delete(dirContact.department);
374
+
375
+ const mergedContact: MergedOrgContact = {
376
+ department: dirContact.department,
377
+ name: preferred?.name ?? dirContact.name,
378
+ phoneNumber: preferred?.phoneNumber ?? dirContact.phoneNumber,
379
+ emailAddress: preferred?.emailAddress ?? dirContact.emailAddress,
380
+ defaultName: dirContact.name,
381
+ defaultPhoneNumber: dirContact.phoneNumber,
382
+ defaultEmailAddress: dirContact.emailAddress,
383
+ officialContact: !hasPreferredContact,
384
+ };
385
+ merged.push(mergedContact);
386
+
387
+ if (duplicateOrgContacts && hasOverride) {
388
+ merged.push({
389
+ department: dirContact.department,
390
+ name: dirContact.name,
391
+ phoneNumber: dirContact.phoneNumber,
392
+ emailAddress: dirContact.emailAddress,
393
+ defaultName: dirContact.name,
394
+ defaultPhoneNumber: dirContact.phoneNumber,
395
+ defaultEmailAddress: dirContact.emailAddress,
396
+ officialContact: true,
397
+ locked: true,
398
+ });
399
+ }
400
+ }
401
+
402
+ // Add remaining preferred contacts (not in directory)
403
+ for (const [, preferred] of preferredMap) {
404
+ merged.push({
405
+ department: preferred.department,
406
+ name: preferred.name,
407
+ phoneNumber: preferred.phoneNumber,
408
+ emailAddress: preferred.emailAddress,
409
+ defaultName: null,
410
+ defaultPhoneNumber: null,
411
+ defaultEmailAddress: null,
412
+ });
413
+ }
414
+
415
+ return merged;
416
+ }
@@ -1,10 +1,10 @@
1
- import i18n from '@jsb188/app/i18n';
2
- import type { AddressObj, ScheduleObj } from '@jsb188/app/types/other.d';
3
- import { getFullDate } from '@jsb188/app/utils/datetime';
4
- import { convertToMilitaryTime } from '@jsb188/app/utils/number';
5
- import { DEFAULT_TIMEZONE, formatCalDateInTimeZone, getDayOfWeekInTimeZone, hhmmFromDateOrTime, parseBoundaryDateInTimezone } from '@jsb188/app/utils/timeZone';
1
+ import i18n from '@jsb188/app/i18n/index.ts';
2
+ import type { AddressObj, ScheduleObj } from '@jsb188/app/types/other.d.ts';
3
+ import { getFullDate } from '@jsb188/app/utils/datetime.ts';
4
+ import { convertToMilitaryTime } from '@jsb188/app/utils/number.ts';
5
+ import { DEFAULT_TIMEZONE, formatCalDateInTimeZone, getDayOfWeekInTimeZone, hhmmFromDateOrTime, parseBoundaryDateInTimezone } from '@jsb188/app/utils/timeZone.ts';
6
6
  import { DateTime } from 'luxon';
7
- import type { ProductAttendanceData, ProductCalEventData, ProductCalEventGQL } from '../types/product.d';
7
+ import type { ProductCalEventData, ProductCalEventGQL } from '../types/product.d.ts';
8
8
 
9
9
  /**
10
10
  * Get the address in a single line text format
@@ -155,7 +155,7 @@ export function getScheduleIcons(eventDetails: ProductCalEventGQL, alwaysFillIco
155
155
 
156
156
  if (once) {
157
157
  return [{
158
- iconName: 'circle-number-1-filled',
158
+ iconName: 'number-1-circle-filled',
159
159
  color: 'amber',
160
160
  tooltipText: i18n.t('org.single_event_msg'),
161
161
  }];
@@ -386,59 +386,6 @@ export function getTimeFromSchedule(
386
386
  ];
387
387
  }
388
388
 
389
- /**
390
- * Filter org event attendance based on manual check & edit history
391
- * @param attendance - Array of organization event attendance data objects
392
- * @param calDate - Calendar date in string format (YYYY-MM-DD)
393
- * @returns Filtered array of organization event attendance data objects
394
- */
395
-
396
- export function filterEventAttendance(
397
- attendance_: ProductAttendanceData[],
398
- calDate: string,
399
- ): ProductAttendanceData[] {
400
- const targetJSDate = new Date(calDate);
401
- const targetTimestamp = targetJSDate.getTime();
402
- const attendance = attendance_.filter((item) => !item.calDate || new Date(item.calDate).getTime() === targetTimestamp);
403
-
404
- const checkedAttendance = new Set<number | bigint>();
405
- for (const item of attendance) {
406
- if (item.attended !== null) {
407
- checkedAttendance.add(item.organizationId);
408
- }
409
- }
410
-
411
- const isActiveOnDate = (item: ProductAttendanceData): boolean => {
412
- if (
413
- item.calDate || // If "calDate" is set, this was a manual override by a human, so history is ignored
414
- !item.history || item.history.length === 0
415
- ) {
416
- return true;
417
- }
418
-
419
- // Sort history by date to be safe
420
- // NOTE: item.history.sort() will mutate the original array, but that's acceptable for our application
421
- const sorted = item.history.sort((a: any, b: any) => new Date(a[0]).getTime() - new Date(b[0]).getTime());
422
-
423
- let active = false;
424
- for (const [hDate, status] of sorted) {
425
- if (new Date(hDate) > targetJSDate) {
426
- break;
427
- }
428
- active = status === '1';
429
- }
430
- return active;
431
- };
432
-
433
- const filteredList = attendance.filter((item) =>
434
- !(item.attended === null && checkedAttendance.has(item.organizationId)) &&
435
- isActiveOnDate(item)
436
- );
437
-
438
- // Sort by organization.name
439
- return filteredList.sort((a, b) => a.organization.name.localeCompare(b.organization.name));
440
- }
441
-
442
389
  /**
443
390
  * Get all date this event happens between 2 calendar dates
444
391
  * @param calEvent
@@ -0,0 +1,158 @@
1
+ import type { LogEntryGQL } from '@jsb188/mday/types/log.d.ts';
2
+ import type { ReportFieldsRow, ReportSectionGQL } from '@jsb188/mday/types/report.d.ts';
3
+ import type { StorageGQL } from '@jsb188/mday/types/storage.d.ts';
4
+ import { REPORT_NUMBERED_PRESETS } from '../constants/report.ts';
5
+
6
+ /**
7
+ * Get report sections file status
8
+ * Returns whether a report has any finished files, if all sections have files, and if all sections are empty
9
+ */
10
+
11
+ export interface ReportSectionsFileStatus {
12
+ hasValidFile: boolean;
13
+ isComplete: boolean;
14
+ isEmpty: boolean;
15
+ }
16
+
17
+ export interface ReportSectionsFilesCount {
18
+ required: number;
19
+ hasFile: number;
20
+ }
21
+
22
+ /*
23
+ * Check whether one report row should contribute to automated line numbering.
24
+ */
25
+
26
+ export function isReportNumberedRow(row?: Pick<ReportFieldsRow, 'preset' | '__notAutomated'> | null): boolean {
27
+ return !!row && !row.__notAutomated && !!row.preset && REPORT_NUMBERED_PRESETS.includes(row.preset);
28
+ }
29
+
30
+ /*
31
+ * Build one report line number using the numbered row index and column index.
32
+ */
33
+
34
+ export function getReportLineNumber(lineIndex?: number | null, colIndex?: number | null): string | null {
35
+ if (!lineIndex || colIndex == null) {
36
+ return null;
37
+ }
38
+
39
+ return `${lineIndex}.${colIndex + 1}`;
40
+ }
41
+
42
+ /*
43
+ * Build the stable row identifier used by report answers and column fragment keys.
44
+ */
45
+
46
+ export function getReportRowIdentifier(answerKey?: string | null, rowKey?: string | null): string {
47
+ return `${answerKey || '__'}.${rowKey || 'ERROR'}`;
48
+ }
49
+
50
+ /*
51
+ * Build the stable column identifier used inside one report row.
52
+ */
53
+
54
+ export function getReportColumnIdentifier(rowIdentifier: string, columnKey: string): string {
55
+ return `${rowIdentifier}.${columnKey}`;
56
+ }
57
+
58
+ /*
59
+ * Build the realtime fragment data ID for one report submission question column.
60
+ */
61
+
62
+ export function getReportColumnFragmentDataId(
63
+ reportSubmissionIdKey: string | number | bigint,
64
+ rowIdentifier: string,
65
+ columnKey: string,
66
+ ): string {
67
+ return `${reportSubmissionIdKey}:${getReportColumnIdentifier(rowIdentifier, columnKey)}`;
68
+ }
69
+
70
+ /*
71
+ * Check whether a report file can render as an image preview.
72
+ */
73
+
74
+ export function isReportReferenceImageFile(file?: StorageGQL | null) {
75
+ return !file?.__deleted
76
+ && !file?.uploadStatus
77
+ && !!file?.uri
78
+ && file.contentType?.startsWith('image/');
79
+ }
80
+
81
+ /*
82
+ * Resolve the logs and files referenced by one report row.
83
+ */
84
+
85
+ export function getReportReferenceContent(
86
+ logEntriesForReport?: LogEntryGQL[] | null,
87
+ referenceIds?: (string | null | undefined)[] | null,
88
+ ) {
89
+ if (!logEntriesForReport?.length || !referenceIds?.length) {
90
+ return null;
91
+ }
92
+
93
+ const referenceIdSet = new Set(referenceIds.filter((referenceId): referenceId is string => !!referenceId));
94
+ if (!referenceIdSet.size) {
95
+ return null;
96
+ }
97
+
98
+ const logs = logEntriesForReport.filter((log) => referenceIdSet.has(log.id));
99
+ if (!logs.length) {
100
+ return null;
101
+ }
102
+
103
+ return {
104
+ files: logs.flatMap((log) => log.files || []),
105
+ logs,
106
+ };
107
+ }
108
+
109
+ export function getReportFilesCount(sections?: ReportSectionGQL[]): ReportSectionsFilesCount {
110
+ return (sections || []).reduce((acc, section) => {
111
+ if (section.requireFileUploads) {
112
+ acc.required++;
113
+ if (section.files?.filter((file) => !file.__deleted)?.length) {
114
+ acc.hasFile++;
115
+ }
116
+ }
117
+ return acc;
118
+ }, {
119
+ required: 0,
120
+ hasFile: 0,
121
+ });
122
+ }
123
+
124
+ export function getReportFileStatus(sections: ReportSectionGQL[] | undefined): ReportSectionsFileStatus {
125
+ let hasValidFile = false;
126
+ let totalRequiring = 0;
127
+ let totalWithFile = 0;
128
+
129
+ for (const section of sections || []) {
130
+ if (!section.requireFileUploads) continue;
131
+
132
+ totalRequiring++;
133
+
134
+ let hasNonDeleted = false;
135
+ let hasCompleted = false;
136
+
137
+ if (section.files) {
138
+ for (const file of section.files) {
139
+ if (!file.__deleted) {
140
+ hasNonDeleted = true;
141
+ if (!file.uploadStatus) {
142
+ hasCompleted = true;
143
+ break; // Found completed file, no need to check more
144
+ }
145
+ }
146
+ }
147
+ }
148
+
149
+ if (hasNonDeleted) totalWithFile++;
150
+ if (!hasCompleted) hasValidFile = true;
151
+ }
152
+
153
+ return {
154
+ hasValidFile,
155
+ isComplete: totalRequiring > 0 && totalWithFile === totalRequiring,
156
+ isEmpty: totalWithFile === 0,
157
+ };
158
+ }