@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,22 +1,32 @@
1
1
  import type { SquareOAuthScope } from '../constants/square.ts';
2
2
 
3
3
  export type SquareConnectionCapabilities = {
4
- canReadMerchant: boolean;
5
- canReadLocations: boolean;
6
- canViewSalesData: boolean;
7
- canCreatePaymentRequests: boolean;
4
+ canReadMerchant: boolean;
5
+ canReadLocations: boolean;
6
+ canViewSalesData: boolean;
7
+ canCreatePaymentRequests: boolean;
8
8
  };
9
9
 
10
10
  /*
11
11
  * Convert Square OAuth scopes into app-level capabilities used by UI and agents.
12
12
  */
13
- export function getSquareConnectionCapabilities(scopes?: string[] | null): SquareConnectionCapabilities {
14
- const grantedScopes = new Set(scopes || []);
13
+ export function getSquareConnectionCapabilities(
14
+ scopes?: string[] | null,
15
+ ): SquareConnectionCapabilities {
16
+ const grantedScopes = new Set(scopes || []);
15
17
 
16
- return {
17
- canReadMerchant: grantedScopes.has('MERCHANT_PROFILE_READ' satisfies SquareOAuthScope),
18
- canReadLocations: grantedScopes.has('MERCHANT_PROFILE_READ' satisfies SquareOAuthScope),
19
- canViewSalesData: grantedScopes.has('PAYMENTS_READ' satisfies SquareOAuthScope) || grantedScopes.has('ORDERS_READ' satisfies SquareOAuthScope),
20
- canCreatePaymentRequests: grantedScopes.has('ORDERS_WRITE' satisfies SquareOAuthScope) && grantedScopes.has('PAYMENTS_WRITE' satisfies SquareOAuthScope),
21
- };
18
+ return {
19
+ canReadMerchant: grantedScopes.has(
20
+ 'MERCHANT_PROFILE_READ' satisfies SquareOAuthScope,
21
+ ),
22
+ canReadLocations: grantedScopes.has(
23
+ 'MERCHANT_PROFILE_READ' satisfies SquareOAuthScope,
24
+ ),
25
+ canViewSalesData:
26
+ grantedScopes.has('PAYMENTS_READ' satisfies SquareOAuthScope) ||
27
+ grantedScopes.has('ORDERS_READ' satisfies SquareOAuthScope),
28
+ canCreatePaymentRequests:
29
+ grantedScopes.has('ORDERS_WRITE' satisfies SquareOAuthScope) &&
30
+ grantedScopes.has('PAYMENTS_WRITE' satisfies SquareOAuthScope),
31
+ };
22
32
  }
@@ -0,0 +1,152 @@
1
+ import {
2
+ CAMPAIGN_HEADER_IMAGE_CONTENT_TYPES,
3
+ CAMPAIGN_HEADER_IMAGE_MAX_FILE_SIZE,
4
+ } from '../constants/storage.ts';
5
+ import type { StorageGQL, StorageIntentEnum } from '../types/storage.d.ts';
6
+
7
+ export interface OptimisticAIChatAttachmentInput {
8
+ id?: string | null;
9
+ uri: string;
10
+ name: string;
11
+ contentType: string;
12
+ }
13
+
14
+ /*
15
+ * Adapt pending AI chat attachments into the normalized relationship shape
16
+ * used by the message renderer before the canonical message query arrives.
17
+ */
18
+
19
+ export function getOptimisticAIChatMessageAttachments(
20
+ attachments: OptimisticAIChatAttachmentInput[],
21
+ at: string,
22
+ ) {
23
+ return attachments.map((attachment, ordinal) => ({
24
+ ordinal,
25
+ file: {
26
+ id: attachment.id || attachment.uri,
27
+ uri: attachment.uri,
28
+ size: 0,
29
+ contentType: attachment.contentType,
30
+ at,
31
+ intent: null,
32
+ name: attachment.name,
33
+ description: null,
34
+ aiNote: null,
35
+ uploadStatus: null,
36
+ },
37
+ }));
38
+ }
39
+
40
+ /*
41
+ * Parse the semicolon-delimited attachment value stored on an AI chat message.
42
+ */
43
+
44
+ export function parseAIChatAttachmentText(text: string) {
45
+ const [oaiFileId = '', fileUri = '', ...nameParts] = (text || '').split(';');
46
+ const fileName = nameParts.join(';');
47
+
48
+ return {
49
+ oaiFileId,
50
+ fileUri,
51
+ fileName,
52
+ };
53
+ }
54
+
55
+ /*
56
+ * Infer the content type needed by the asset viewer from an attachment name.
57
+ */
58
+
59
+ function getAIChatAttachmentContentType(fileName: string, isImage: boolean) {
60
+ const extension = fileName.split('.').pop()?.toLowerCase();
61
+ const contentTypes: Record<string, string> = {
62
+ gif: 'image/gif',
63
+ jpeg: 'image/jpeg',
64
+ jpg: 'image/jpeg',
65
+ pdf: 'application/pdf',
66
+ png: 'image/png',
67
+ webp: 'image/webp',
68
+ };
69
+
70
+ return (
71
+ (extension && contentTypes[extension]) ||
72
+ (isImage ? 'image/jpeg' : 'application/octet-stream')
73
+ );
74
+ }
75
+
76
+ /*
77
+ * Adapt one AI chat attachment into the storage-file shape used by the asset
78
+ * viewer modal.
79
+ */
80
+
81
+ export function getAIChatAttachmentStorageFile(
82
+ text: string,
83
+ isImage: boolean,
84
+ ): StorageGQL | null {
85
+ const { oaiFileId, fileUri, fileName } = parseAIChatAttachmentText(text);
86
+ if (!fileUri) {
87
+ return null;
88
+ }
89
+
90
+ const displayName =
91
+ fileName || fileUri.substring(fileUri.lastIndexOf('/') + 1);
92
+
93
+ return {
94
+ id: oaiFileId || fileUri,
95
+ organizationId: null,
96
+ accountId: null,
97
+ uri: fileUri,
98
+ size: 0,
99
+ checked: true,
100
+ at: '',
101
+ contentType: getAIChatAttachmentContentType(displayName, isImage),
102
+ intent: null,
103
+ name: displayName,
104
+ };
105
+ }
106
+
107
+ /*
108
+ * Check whether a GCS object name or public asset URL contains a permanent
109
+ * application asset path segment: static/ or fonts/.
110
+ */
111
+
112
+ export function isStaticStorageUri(fileUri?: string | null): boolean {
113
+ if (!fileUri) {
114
+ return false;
115
+ }
116
+
117
+ const pathWithoutQuery = fileUri.trim().split(/[?#]/, 1)[0];
118
+ return /(^|\/)(?:static|fonts)\//.test(pathWithoutQuery);
119
+ }
120
+
121
+ /*
122
+ * Preserve an explicit storage intent, otherwise classify permanent static
123
+ * asset paths so cleanup code can exclude them.
124
+ */
125
+
126
+ export function resolveStorageIntentForUri(
127
+ fileUri: string,
128
+ intent?: StorageIntentEnum | null,
129
+ ): StorageIntentEnum | undefined {
130
+ return intent || (isStaticStorageUri(fileUri) ? 'STATIC' : undefined);
131
+ }
132
+
133
+ /*
134
+ * Check whether one storage object is safe and small enough to use as a
135
+ * public Field Doc form header image.
136
+ */
137
+
138
+ export function isValidCampaignHeaderImageFile(
139
+ file?: {
140
+ contentType?: string | null;
141
+ size?: number | null;
142
+ } | null,
143
+ ): boolean {
144
+ return (
145
+ !!file?.contentType &&
146
+ CAMPAIGN_HEADER_IMAGE_CONTENT_TYPES.some(
147
+ (contentType) => contentType === file.contentType,
148
+ ) &&
149
+ !!file.size &&
150
+ file.size <= CAMPAIGN_HEADER_IMAGE_MAX_FILE_SIZE
151
+ );
152
+ }
@@ -2,36 +2,48 @@ export const TABLE_ROUTE_COLUMN_MIN_WIDTH = 50;
2
2
  export const TABLE_ROUTE_COLUMN_MAX_WIDTH = 800;
3
3
 
4
4
  export type TableRouteColumnWidths = Record<string, number>;
5
+ export type TableRouteColumnOrder = string[];
5
6
 
6
7
  export interface OrganizationRouteSettingsObj {
7
8
  columnWidths?: TableRouteColumnWidths | null;
9
+ columnOrder?: TableRouteColumnOrder | null;
8
10
  }
9
11
 
10
12
  /*
11
13
  * Keep a user-resized route table column width inside a practical range.
12
14
  */
13
15
  export function clampTableRouteColumnWidth(width: number) {
14
- return Math.min(TABLE_ROUTE_COLUMN_MAX_WIDTH, Math.max(TABLE_ROUTE_COLUMN_MIN_WIDTH, Math.round(width)));
16
+ return Math.min(
17
+ TABLE_ROUTE_COLUMN_MAX_WIDTH,
18
+ Math.max(TABLE_ROUTE_COLUMN_MIN_WIDTH, Math.round(width)),
19
+ );
15
20
  }
16
21
 
17
22
  /*
18
23
  * Return whether a route table column key can be safely stored in settings JSONB.
19
24
  */
20
- export function isValidTableRouteColumnSettingsKey(value: string | null | undefined) {
25
+ export function isValidTableRouteColumnSettingsKey(
26
+ value: string | null | undefined,
27
+ ) {
21
28
  return !!value && /^[A-Za-z0-9_-]+$/.test(value);
22
29
  }
23
30
 
24
31
  /*
25
32
  * Return whether a table route id can be safely stored in settings JSONB.
26
33
  */
27
- export function isValidTableRouteIdSettingsKey(value: string | null | undefined) {
34
+ export function isValidTableRouteIdSettingsKey(
35
+ value: string | null | undefined,
36
+ ) {
28
37
  return !!value && /^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(value);
29
38
  }
30
39
 
31
40
  /*
32
41
  * Return the app route id used for organization table settings.
33
42
  */
34
- export function getTableRouteIdFromPathname(pathname: string, fallbackRouteId = 'table') {
43
+ export function getTableRouteIdFromPathname(
44
+ pathname: string,
45
+ fallbackRouteId = 'table',
46
+ ) {
35
47
  const segments = pathname.split('/').filter(Boolean);
36
48
  const routeSegments = segments[0] === 'app' ? segments.slice(1) : segments;
37
49
  const routeId = routeSegments.join('/');
@@ -42,7 +54,9 @@ export function getTableRouteIdFromPathname(pathname: string, fallbackRouteId =
42
54
  /*
43
55
  * Return the route id from an OrgRoute cursor shaped as [organizationId, 0, routeId].
44
56
  */
45
- export function getTableRouteIdFromOrgRouteCursor(cursor: string | null | undefined) {
57
+ export function getTableRouteIdFromOrgRouteCursor(
58
+ cursor: string | null | undefined,
59
+ ) {
46
60
  const routeId = String(cursor || '').split(':')[2];
47
61
 
48
62
  return isValidTableRouteIdSettingsKey(routeId) ? routeId : null;
@@ -51,7 +65,9 @@ export function getTableRouteIdFromOrgRouteCursor(cursor: string | null | undefi
51
65
  /*
52
66
  * Convert GraphQL OrgRoute column width strings into a keyed width object.
53
67
  */
54
- export function getTableRouteColumnWidthsFromStrings(values: string[] | null | undefined) {
68
+ export function getTableRouteColumnWidthsFromStrings(
69
+ values: string[] | null | undefined,
70
+ ) {
55
71
  if (!Array.isArray(values)) {
56
72
  return {};
57
73
  }
@@ -63,7 +79,11 @@ export function getTableRouteColumnWidthsFromStrings(values: string[] | null | u
63
79
  const [columnKey, widthValue] = parts;
64
80
  const width = Number(widthValue);
65
81
 
66
- if (parts.length !== 2 || !isValidTableRouteColumnSettingsKey(columnKey) || !Number.isFinite(width)) {
82
+ if (
83
+ parts.length !== 2 ||
84
+ !isValidTableRouteColumnSettingsKey(columnKey) ||
85
+ !Number.isFinite(width)
86
+ ) {
67
87
  continue;
68
88
  }
69
89
 
@@ -76,13 +96,18 @@ export function getTableRouteColumnWidthsFromStrings(values: string[] | null | u
76
96
  /*
77
97
  * Convert a keyed column width object into GraphQL OrgRoute width strings.
78
98
  */
79
- export function getTableRouteColumnWidthStrings(widths: TableRouteColumnWidths | null | undefined) {
99
+ export function getTableRouteColumnWidthStrings(
100
+ widths: TableRouteColumnWidths | null | undefined,
101
+ ) {
80
102
  if (!widths) {
81
103
  return [];
82
104
  }
83
105
 
84
106
  return Object.entries(widths).reduce((acc, [columnKey, width]) => {
85
- if (!isValidTableRouteColumnSettingsKey(columnKey) || !Number.isFinite(width)) {
107
+ if (
108
+ !isValidTableRouteColumnSettingsKey(columnKey) ||
109
+ !Number.isFinite(width)
110
+ ) {
86
111
  return acc;
87
112
  }
88
113
 
@@ -91,6 +116,74 @@ export function getTableRouteColumnWidthStrings(widths: TableRouteColumnWidths |
91
116
  }, [] as string[]);
92
117
  }
93
118
 
119
+ /*
120
+ * Return a unique ordered column key list from GraphQL route settings values.
121
+ */
122
+ export function getTableRouteColumnOrderFromStrings(
123
+ values: string[] | null | undefined,
124
+ ) {
125
+ if (!Array.isArray(values)) {
126
+ return [];
127
+ }
128
+
129
+ const seenColumnKeys = new Set<string>();
130
+
131
+ return values.reduce((acc, value) => {
132
+ const columnKey = String(value || '');
133
+
134
+ if (
135
+ !isValidTableRouteColumnSettingsKey(columnKey) ||
136
+ seenColumnKeys.has(columnKey)
137
+ ) {
138
+ return acc;
139
+ }
140
+
141
+ seenColumnKeys.add(columnKey);
142
+ acc.push(columnKey);
143
+ return acc;
144
+ }, [] as TableRouteColumnOrder);
145
+ }
146
+
147
+ /*
148
+ * Convert an ordered column key list into GraphQL OrgRoute order strings.
149
+ */
150
+ export function getTableRouteColumnOrderStrings(
151
+ columnOrder: TableRouteColumnOrder | null | undefined,
152
+ ) {
153
+ return getTableRouteColumnOrderFromStrings(columnOrder);
154
+ }
155
+
156
+ /*
157
+ * Return a complete column order from saved keys and the current table design keys.
158
+ */
159
+ export function getTableRouteColumnOrderFromColumnKeys(
160
+ columnKeys: string[],
161
+ columnOrder: TableRouteColumnOrder | null | undefined,
162
+ ) {
163
+ const validColumnKeys = columnKeys.filter(isValidTableRouteColumnSettingsKey);
164
+ const validColumnKeySet = new Set(validColumnKeys);
165
+ const seenColumnKeys = new Set<string>();
166
+ const orderedColumnKeys = getTableRouteColumnOrderFromStrings(
167
+ columnOrder,
168
+ ).reduce((acc, columnKey) => {
169
+ if (!validColumnKeySet.has(columnKey) || seenColumnKeys.has(columnKey)) {
170
+ return acc;
171
+ }
172
+
173
+ seenColumnKeys.add(columnKey);
174
+ acc.push(columnKey);
175
+ return acc;
176
+ }, [] as TableRouteColumnOrder);
177
+
178
+ validColumnKeys.forEach((columnKey) => {
179
+ if (!seenColumnKeys.has(columnKey)) {
180
+ orderedColumnKeys.push(columnKey);
181
+ }
182
+ });
183
+
184
+ return orderedColumnKeys;
185
+ }
186
+
94
187
  /*
95
188
  * Convert a settings routes object into one GraphQL-friendly route settings list.
96
189
  */
@@ -106,6 +199,7 @@ export function getOrganizationSettingsRoutesList(
106
199
  .map(([routeId, route]) => ({
107
200
  routeId,
108
201
  columnWidths: route?.columnWidths || {},
202
+ columnOrder: getTableRouteColumnOrderStrings(route?.columnOrder),
109
203
  }));
110
204
  }
111
205
 
@@ -113,14 +207,36 @@ export function getOrganizationSettingsRoutesList(
113
207
  * Return route column widths from GraphQL OrganizationSettings.routes data.
114
208
  */
115
209
  export function getTableRouteColumnWidthsFromSettingsRoutes(
116
- routes: { id?: string | null; columnWidths?: string[] | null }[] | null | undefined,
210
+ routes:
211
+ | { id?: string | null; columnWidths?: string[] | null }[]
212
+ | null
213
+ | undefined,
117
214
  routeId: string,
118
215
  ) {
119
- const route = routes?.find((item) => getTableRouteIdFromOrgRouteCursor(item?.id) === routeId);
216
+ const route = routes?.find(
217
+ (item) => getTableRouteIdFromOrgRouteCursor(item?.id) === routeId,
218
+ );
120
219
 
121
220
  return getTableRouteColumnWidthsFromStrings(route?.columnWidths);
122
221
  }
123
222
 
223
+ /*
224
+ * Return route column order from GraphQL OrganizationSettings.routes data.
225
+ */
226
+ export function getTableRouteColumnOrderFromSettingsRoutes(
227
+ routes:
228
+ | { id?: string | null; columnOrder?: string[] | null }[]
229
+ | null
230
+ | undefined,
231
+ routeId: string,
232
+ ) {
233
+ const route = routes?.find(
234
+ (item) => getTableRouteIdFromOrgRouteCursor(item?.id) === routeId,
235
+ );
236
+
237
+ return getTableRouteColumnOrderFromStrings(route?.columnOrder);
238
+ }
239
+
124
240
  /*
125
241
  * Keep only local width patches that have not been confirmed by server settings.
126
242
  */
@@ -1,32 +1,191 @@
1
+ import { normalizeArrayLikeValue } from '@jsb188/app/utils/object.ts';
1
2
  import { hhmmFromDateOrTime } from '@jsb188/app/utils/timeZone.ts';
2
3
  import i18n from '@jsb188/app/i18n/index.ts';
3
4
  import { CronExpressionParser } from 'cron-parser';
4
- import type { WorkflowGQL, WorkflowRunData } from '../types/workflow';
5
+ import type { LogTypeEnum } from '../types/log.d.ts';
6
+ import type {
7
+ WorkflowGQL,
8
+ WorkflowLifecycleStatusEnum,
9
+ WorkflowRunData,
10
+ WorkflowStatusEnum,
11
+ } from '../types/workflow.d.ts';
5
12
  import { getLogCategoryColor } from './log.ts';
6
- import { getOrganizationFeatureColor } from './organization.ts';
13
+ import { humanizeRegistryKey } from './logTaxonomyDisplay.ts';
7
14
 
8
15
  const DEFAULT_SCHEDULE_WINDOW_MS = 24 * 60 * 60 * 1000; // once per day
9
16
 
10
17
  /**
11
- * Get the workflow display color from its trigger or feature.
18
+ * Normalize workflow log types from database, cache, or API-shaped values.
12
19
  */
13
20
 
14
- export function getWorkflowColor(workflow: Pick<WorkflowGQL, 'logType' | 'feature'>) {
15
- return workflow.logType
16
- ? getLogCategoryColor(workflow.logType)
17
- : getOrganizationFeatureColor(workflow.feature);
21
+ export function normalizeWorkflowLogTypes(logTypes: unknown): string[] | null {
22
+ const rawLogTypes = normalizeArrayLikeValue(logTypes);
23
+
24
+ const normalizedLogTypes = (rawLogTypes || [])
25
+ .map((logType) => (typeof logType === 'string' ? logType.trim() : ''))
26
+ .filter((logType) => !!logType && logType.toUpperCase() !== 'NULL');
27
+
28
+ return normalizedLogTypes.length ? normalizedLogTypes : null;
29
+ }
30
+
31
+ /**
32
+ * Get the workflow display color from its trigger log types.
33
+ */
34
+
35
+ export function getWorkflowColor(workflow: Pick<WorkflowGQL, 'logTypes'>) {
36
+ const firstLogType = workflow.logTypes?.[0];
37
+
38
+ return firstLogType
39
+ ? getLogCategoryColor(firstLogType as LogTypeEnum)
40
+ : 'stone';
41
+ }
42
+
43
+ /**
44
+ * Resolve a workflow log-group label with a registry-key fallback.
45
+ */
46
+
47
+ export function getWorkflowLogTypeLabel(
48
+ logType: string,
49
+ short: boolean = false,
50
+ ): string {
51
+ const i18nKey = `log.type${short ? '_short' : ''}.${logType}`;
52
+ if (i18n.has(i18nKey)) {
53
+ return i18n.t(i18nKey);
54
+ }
55
+ if (!short && i18n.has(`log.type_short.${logType}`)) {
56
+ return i18n.t(`log.type_short.${logType}`);
57
+ }
58
+ return humanizeRegistryKey(logType);
18
59
  }
19
60
 
20
61
  /**
21
62
  * Get the short workflow label used in cards and headers.
22
63
  */
23
64
 
24
- export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logType' | 'feature'>) {
25
- const { logType, feature } = workflow;
65
+ export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logTypes'>) {
66
+ const firstLogType = workflow.logTypes?.[0];
26
67
 
27
- return logType
28
- ? i18n.t(`log.type_short.${logType}`)
29
- : i18n.t(feature ? `product.feature_short.${feature}` : 'product.workflow');
68
+ return firstLogType
69
+ ? getWorkflowLogTypeLabel(firstLogType, true)
70
+ : i18n.t('form.workflow');
71
+ }
72
+
73
+ /**
74
+ * Check whether a workflow has an active trigger target.
75
+ */
76
+
77
+ export function hasWorkflowActiveTarget(
78
+ workflow: Pick<WorkflowGQL, 'logTypes' | 'fieldDocId' | 'nextAt'>,
79
+ ) {
80
+ return (
81
+ !!workflow.nextAt || !!workflow.logTypes?.length || !!workflow.fieldDocId
82
+ );
83
+ }
84
+
85
+ /**
86
+ * Check whether a workflow should display as active.
87
+ */
88
+
89
+ export function isWorkflowActive(
90
+ workflow: Pick<WorkflowGQL, 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'>,
91
+ ) {
92
+ return !!workflow.active && hasWorkflowActiveTarget(workflow);
93
+ }
94
+
95
+ /**
96
+ * Check whether a workflow row is a reminder (kind=REMINDER).
97
+ */
98
+
99
+ export function isReminder(workflow: Pick<WorkflowGQL, 'kind'>) {
100
+ return workflow.kind === 'REMINDER';
101
+ }
102
+
103
+ /**
104
+ * Check whether a reminder is still actionable (cancelable): scheduled to
105
+ * fire, or already fired with its run still ongoing. Completed and canceled
106
+ * reminders are not active.
107
+ */
108
+
109
+ export function isReminderActive(reminder: Pick<WorkflowGQL, 'status'>) {
110
+ return reminder.status === 'SCHEDULED' || reminder.status === 'IN_PROGRESS';
111
+ }
112
+
113
+ /**
114
+ * Derive the lifecycle status for a workflow or reminder.
115
+ * `active` is pure user intent (enabled vs canceled/paused); everything
116
+ * time- or run-dependent is derived at read time so it can never go stale.
117
+ * For a fired one-time reminder the latest run decides ongoing vs completed;
118
+ * pass `latestRun` as undefined when the run state is unknown, and the
119
+ * result is undefined too (callers omit the field instead of guessing).
120
+ */
121
+
122
+ export function getWorkflowLifecycleStatus(
123
+ workflow: Pick<
124
+ WorkflowGQL,
125
+ 'kind' | 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'
126
+ >,
127
+ latestRun?: {
128
+ status: WorkflowStatusEnum;
129
+ followUpAt: Date | string | null;
130
+ } | null,
131
+ now = new Date(),
132
+ ): WorkflowLifecycleStatusEnum | undefined {
133
+ if (!isReminder(workflow)) {
134
+ return isWorkflowActive(workflow) ? 'ACTIVE' : 'INACTIVE';
135
+ }
136
+
137
+ if (!workflow.active) {
138
+ return 'INACTIVE';
139
+ }
140
+
141
+ if (workflow.nextAt) {
142
+ return 'SCHEDULED';
143
+ }
144
+
145
+ // Fired one-time reminder; the latest run decides ongoing vs completed
146
+
147
+ if (latestRun === undefined) {
148
+ return undefined;
149
+ }
150
+
151
+ return isWorkflowRunSettled(latestRun, now) ? 'COMPLETED' : 'IN_PROGRESS';
152
+ }
153
+
154
+ /**
155
+ * Check whether a workflow run is settled (no further automatic action will occur).
156
+ * An open run counts as ongoing only while it has a future resume point;
157
+ * both reply waits and scheduled follow-ups set followUpAt on the run.
158
+ */
159
+
160
+ export function isWorkflowRunSettled(
161
+ workflowRun:
162
+ | {
163
+ status: WorkflowStatusEnum;
164
+ followUpAt: Date | string | null;
165
+ }
166
+ | null
167
+ | undefined,
168
+ now = new Date(),
169
+ ) {
170
+ if (!workflowRun) {
171
+ return true;
172
+ }
173
+
174
+ if (!['QUEUED', 'STARTED'].includes(workflowRun.status)) {
175
+ return true;
176
+ }
177
+
178
+ return !workflowRun.followUpAt || new Date(workflowRun.followUpAt) <= now;
179
+ }
180
+
181
+ /**
182
+ * Check whether a reminder repeats on a cron schedule.
183
+ */
184
+
185
+ export function isRecurringReminder(
186
+ workflow: Pick<WorkflowGQL, 'triggerType'>,
187
+ ) {
188
+ return workflow.triggerType === 'SCHEDULE';
30
189
  }
31
190
 
32
191
  /**
@@ -36,7 +195,7 @@ export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logType' | 'f
36
195
  export function replaceWorkflowTemplateValues(
37
196
  text: string,
38
197
  values?: Record<string, any> | null,
39
- timeZone: string | null = null,
198
+ timeZone: string | null = null,
40
199
  ) {
41
200
  if (!text || !values || typeof values !== 'object' || Array.isArray(values)) {
42
201
  return text;
@@ -57,7 +216,10 @@ export function replaceWorkflowTemplateValues(
57
216
  break;
58
217
  }
59
218
 
60
- return hhmmFromDateOrTime(normalized, null, true, timeZone, true) || String(value);
219
+ return (
220
+ hhmmFromDateOrTime(normalized, null, true, timeZone, true) ||
221
+ String(value)
222
+ );
61
223
  }
62
224
  }
63
225
 
@@ -73,14 +235,16 @@ export function replaceWorkflowTemplateValues(
73
235
  * Get window for workflow schedule
74
236
  */
75
237
 
76
- function getScheduleWindowMs(schedule: string | null | undefined, nextAt: Date) {
238
+ function getScheduleWindowMs(
239
+ schedule: string | null | undefined,
240
+ nextAt: Date,
241
+ ) {
77
242
  if (!schedule) {
78
243
  return DEFAULT_SCHEDULE_WINDOW_MS;
79
244
  }
80
245
 
81
246
  try {
82
- const nextMs = CronExpressionParser
83
- .parse(schedule, { currentDate: nextAt })
247
+ const nextMs = CronExpressionParser.parse(schedule, { currentDate: nextAt })
84
248
  .next()
85
249
  .toDate()
86
250
  .getTime();
@@ -132,7 +296,9 @@ export function isWithinScheduleWindow(
132
296
  * Normalize workflow schedule interval into a valid positive integer.
133
297
  */
134
298
 
135
- function normalizeScheduleInterval(scheduleInterval: number | null | undefined) {
299
+ function normalizeScheduleInterval(
300
+ scheduleInterval: number | null | undefined,
301
+ ) {
136
302
  if (!Number.isFinite(scheduleInterval)) {
137
303
  return 1;
138
304
  }
@@ -192,17 +358,19 @@ export function isWorkflowRunActive(
192
358
 
193
359
  const nextFollowUpAt = workflowRun.followUpAt;
194
360
  if (!nextFollowUpAt) {
195
- if (['COMPLETED', 'ERRORED', 'CANCELED'].includes(workflowRun.status)) {
196
- const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
197
- return workflowRun.activityAt > oneDayAgo;
198
- }
361
+ if (['COMPLETED', 'ERRORED', 'CANCELED'].includes(workflowRun.status)) {
362
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
363
+ return workflowRun.activityAt > oneDayAgo;
364
+ }
199
365
 
200
366
  return true;
201
367
  }
202
368
 
203
369
  if (isFollowUp) {
204
370
  const now = new Date();
205
- const followUpWindowStart = new Date(nextFollowUpAt.getTime() - 10 * 60 * 1000);
371
+ const followUpWindowStart = new Date(
372
+ nextFollowUpAt.getTime() - 10 * 60 * 1000,
373
+ );
206
374
 
207
375
  // Allow follow-up run only after entering the 10-minute pre-follow-up window.
208
376
  return now >= followUpWindowStart;