@jsb188/mday 1.1.11 → 1.1.12

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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,16 +1,17 @@
1
+ import i18n from '@jsb188/app/i18n/index.ts';
1
2
  import { normalizeArrayLikeValue } from '@jsb188/app/utils/object.ts';
3
+ import { buildSingleText, type BuildSingleTextLine } from '@jsb188/app/utils/string.ts';
2
4
  import { hhmmFromDateOrTime } from '@jsb188/app/utils/timeZone.ts';
3
- import i18n from '@jsb188/app/i18n/index.ts';
4
5
  import { CronExpressionParser } from 'cron-parser';
5
- import type { LogTypeEnum } from '../types/log.d.ts';
6
6
  import type {
7
+ WorkflowData,
7
8
  WorkflowGQL,
8
9
  WorkflowLifecycleStatusEnum,
9
10
  WorkflowRunData,
10
11
  WorkflowStatusEnum,
11
12
  } from '../types/workflow.d.ts';
12
- import { getLogCategoryColor } from './log.ts';
13
- import { humanizeRegistryKey } from './logTaxonomyDisplay.ts';
13
+ import { getTaxonomyActivityLabel, getTaxonomyGroupLabel, humanizeRegistryKey } from './logTaxonomyDisplay.ts';
14
+ import { getWorkflowTriggerActivity, isWorkflowTriggerKeyAllowed } from './workflowTriggers.ts';
14
15
 
15
16
  const DEFAULT_SCHEDULE_WINDOW_MS = 24 * 60 * 60 * 1000; // once per day
16
17
 
@@ -29,25 +30,17 @@ export function normalizeWorkflowLogTypes(logTypes: unknown): string[] | null {
29
30
  }
30
31
 
31
32
  /**
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.
33
+ * Resolve a workflow group or activity label with a registry-key fallback.
45
34
  */
46
35
 
47
- export function getWorkflowLogTypeLabel(
48
- logType: string,
49
- short: boolean = false,
50
- ): string {
36
+ export function getWorkflowLogTypeLabel(logType: string, short: boolean = false, operation?: string | null): string {
37
+ const activity = getWorkflowTriggerActivity(logType);
38
+ if (activity !== null)
39
+ return short && i18n.has(`log.activity_short.${activity}`)
40
+ ? i18n.t(`log.activity_short.${activity}`)
41
+ : getTaxonomyActivityLabel(null, activity);
42
+ if (logType === 'MARKET_OPERATION' || (logType === 'OPERATION' && operation === 'FARMERS_MARKET'))
43
+ return getTaxonomyGroupLabel(null, logType, operation, short);
51
44
  const i18nKey = `log.type${short ? '_short' : ''}.${logType}`;
52
45
  if (i18n.has(i18nKey)) {
53
46
  return i18n.t(i18nKey);
@@ -62,23 +55,24 @@ export function getWorkflowLogTypeLabel(
62
55
  * Get the short workflow label used in cards and headers.
63
56
  */
64
57
 
65
- export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logTypes'>) {
58
+ export function getWorkflowShortLabel(workflow: Pick<WorkflowGQL, 'logTypes'>, operation?: string | null) {
66
59
  const firstLogType = workflow.logTypes?.[0];
67
60
 
68
- return firstLogType
69
- ? getWorkflowLogTypeLabel(firstLogType, true)
70
- : i18n.t('form.workflow');
61
+ return firstLogType ? getWorkflowLogTypeLabel(firstLogType, true, operation) : i18n.t('c.workflow');
71
62
  }
72
63
 
73
64
  /**
74
- * Check whether a workflow has an active trigger target.
65
+ * Check whether a workflow has an active trigger target. App interaction
66
+ * subscriptions never match a log, so they are not a target. A workflow an
67
+ * agent note manages (an insight tracker) always has one: its log triggers,
68
+ * or the web form campaigns it is bound to.
75
69
  */
76
70
 
77
71
  export function hasWorkflowActiveTarget(
78
- workflow: Pick<WorkflowGQL, 'logTypes' | 'fieldDocId' | 'nextAt'>,
72
+ workflow: Pick<WorkflowGQL, 'logTypes' | 'fieldDocId' | 'nextAt'> & Partial<Pick<WorkflowGQL, 'agentNoteId'>>,
79
73
  ) {
80
74
  return (
81
- !!workflow.nextAt || !!workflow.logTypes?.length || !!workflow.fieldDocId
75
+ !!workflow.nextAt || !!workflow.logTypes?.some(isWorkflowTriggerKeyAllowed) || !!workflow.fieldDocId || !!workflow.agentNoteId
82
76
  );
83
77
  }
84
78
 
@@ -87,7 +81,7 @@ export function hasWorkflowActiveTarget(
87
81
  */
88
82
 
89
83
  export function isWorkflowActive(
90
- workflow: Pick<WorkflowGQL, 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'>,
84
+ workflow: Pick<WorkflowGQL, 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'> & Partial<Pick<WorkflowGQL, 'agentNoteId'>>,
91
85
  ) {
92
86
  return !!workflow.active && hasWorkflowActiveTarget(workflow);
93
87
  }
@@ -114,16 +108,17 @@ export function isReminderActive(reminder: Pick<WorkflowGQL, 'status'>) {
114
108
  * Derive the lifecycle status for a workflow or reminder.
115
109
  * `active` is pure user intent (enabled vs canceled/paused); everything
116
110
  * time- or run-dependent is derived at read time so it can never go stale.
111
+ * An inactive reminder whose terminal record (values.reminderEnd) says
112
+ * COMPLETED is COMPLETED; every other inactive reminder is INACTIVE.
117
113
  * For a fired one-time reminder the latest run decides ongoing vs completed;
118
114
  * pass `latestRun` as undefined when the run state is unknown, and the
119
115
  * result is undefined too (callers omit the field instead of guessing).
120
116
  */
121
117
 
122
118
  export function getWorkflowLifecycleStatus(
123
- workflow: Pick<
124
- WorkflowGQL,
125
- 'kind' | 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'
126
- >,
119
+ workflow: Pick<WorkflowGQL, 'kind' | 'active' | 'logTypes' | 'fieldDocId' | 'nextAt'> &
120
+ Partial<Pick<WorkflowGQL, 'agentNoteId'>> &
121
+ Partial<Pick<WorkflowData, 'values'>>,
127
122
  latestRun?: {
128
123
  status: WorkflowStatusEnum;
129
124
  followUpAt: Date | string | null;
@@ -135,10 +130,10 @@ export function getWorkflowLifecycleStatus(
135
130
  }
136
131
 
137
132
  if (!workflow.active) {
138
- return 'INACTIVE';
133
+ return workflow.values?.reminderEnd?.outcome === 'COMPLETED' ? 'COMPLETED' : 'INACTIVE';
139
134
  }
140
135
 
141
- if (workflow.nextAt) {
136
+ if (workflow.nextAt || workflow.values?.agentTask?.trigger === 'SOURCE_CHANGE') {
142
137
  return 'SCHEDULED';
143
138
  }
144
139
 
@@ -182,9 +177,7 @@ export function isWorkflowRunSettled(
182
177
  * Check whether a reminder repeats on a cron schedule.
183
178
  */
184
179
 
185
- export function isRecurringReminder(
186
- workflow: Pick<WorkflowGQL, 'triggerType'>,
187
- ) {
180
+ export function isRecurringReminder(workflow: Pick<WorkflowGQL, 'triggerType'>) {
188
181
  return workflow.triggerType === 'SCHEDULE';
189
182
  }
190
183
 
@@ -192,11 +185,7 @@ export function isRecurringReminder(
192
185
  * Replace workflow template values in text using {{key}} placeholders
193
186
  */
194
187
 
195
- export function replaceWorkflowTemplateValues(
196
- text: string,
197
- values?: Record<string, any> | null,
198
- timeZone: string | null = null,
199
- ) {
188
+ export function replaceWorkflowTemplateValues(text: string, values?: Record<string, any> | null, timeZone: string | null = null) {
200
189
  if (!text || !values || typeof values !== 'object' || Array.isArray(values)) {
201
190
  return text;
202
191
  }
@@ -216,10 +205,7 @@ export function replaceWorkflowTemplateValues(
216
205
  break;
217
206
  }
218
207
 
219
- return (
220
- hhmmFromDateOrTime(normalized, null, true, timeZone, true) ||
221
- String(value)
222
- );
208
+ return hhmmFromDateOrTime(normalized, null, true, timeZone, true) || String(value);
223
209
  }
224
210
  }
225
211
 
@@ -232,27 +218,178 @@ export function replaceWorkflowTemplateValues(
232
218
  }
233
219
 
234
220
  /**
235
- * Get window for workflow schedule
221
+ * Render one workflow instruction section with the same truthy config and placeholder rules.
222
+ * A null config enables no conditional keys and leaves every placeholder unchanged.
236
223
  */
237
224
 
238
- function getScheduleWindowMs(
239
- schedule: string | null | undefined,
240
- nextAt: Date,
225
+ export function renderWorkflowInstruction(
226
+ instruction: string | BuildSingleTextLine[] | null | undefined,
227
+ config: Record<string, any> | null = {},
228
+ timeZone: string | null = null,
241
229
  ) {
230
+ const text =
231
+ typeof instruction === 'string'
232
+ ? instruction
233
+ : buildSingleText(
234
+ instruction || [],
235
+ ' ',
236
+ Object.keys(config || {}).filter((key) => config?.[key]),
237
+ );
238
+ return replaceWorkflowTemplateValues(text, config, timeZone);
239
+ }
240
+
241
+ /*
242
+ * Render a reminder's main content, omitting unread columns from partial realtime updates.
243
+ */
244
+ export function getReminderContent(workflow: Pick<WorkflowData, 'kind' | 'instructions' | 'values'>, timeZone: string | null = null) {
245
+ if (workflow.kind === undefined || workflow.instructions === undefined) return undefined;
246
+ if (workflow.kind !== 'REMINDER') return null;
247
+ return renderWorkflowInstruction(workflow.instructions?.main, workflow.values?.config, timeZone).trim() || null;
248
+ }
249
+
250
+ /**
251
+ * Compose a program-managed workflow's catalog instructions with the organization's user instructions.
252
+ * Blank user instructions leave the catalog text unchanged; otherwise they follow it under a "User instructions:" heading.
253
+ */
254
+
255
+ export function composeWorkflowUserInstructions(catalogText: string, userInstructions: string | null | undefined): string {
256
+ const user = userInstructions?.trim();
257
+ if (!user) return catalogText;
258
+ return [catalogText.trim(), `User instructions:\n${user}`].filter(Boolean).join('\n');
259
+ }
260
+
261
+ /**
262
+ * Return the first plain-text line of a workflow instruction (e.g. a reminder task).
263
+ * A string instruction is returned whole instead of its first character.
264
+ */
265
+
266
+ export function getWorkflowInstructionFirstLine(instruction: string | BuildSingleTextLine[] | null | undefined) {
267
+ if (typeof instruction === 'string') {
268
+ return instruction;
269
+ }
270
+ return Array.isArray(instruction) && typeof instruction[0] === 'string' ? instruction[0] : null;
271
+ }
272
+
273
+ /**
274
+ * Build special step template values that are not stored in workflow config.
275
+ */
276
+
277
+ export function makeWorkflowDataTableVariableValues(dataTableNames: string[] | null | undefined) {
278
+ return dataTableNames?.length ? { data_table_names: dataTableNames.join(', ') } : null;
279
+ }
280
+
281
+ /**
282
+ * Resolve required config keys for one conditional step override.
283
+ * Without an explicit list, placeholders in the override value are required.
284
+ */
285
+
286
+ function getRequiredWorkflowConfigKeys(required: unknown, value: unknown) {
287
+ if (Array.isArray(required)) {
288
+ return required as unknown[];
289
+ } else if (typeof value !== 'string' || !value) {
290
+ return [];
291
+ }
292
+
293
+ const templateKeys = new Set<string>();
294
+ for (const match of value.matchAll(/{{(.*?)}}/g)) {
295
+ const key = String(match[1] || '').trim();
296
+ if (key) {
297
+ templateKeys.add(key);
298
+ }
299
+ }
300
+
301
+ return Array.from(templateKeys);
302
+ }
303
+
304
+ /**
305
+ * Check whether all required config keys exist and are non-falsy (the string '0' counts as falsy).
306
+ */
307
+
308
+ function hasRequiredWorkflowConfigValues(config: unknown, required: unknown, value: unknown) {
309
+ const requiredKeys = getRequiredWorkflowConfigKeys(required, value);
310
+ if (!requiredKeys.length) {
311
+ return true;
312
+ }
313
+
314
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
315
+ return false;
316
+ }
317
+
318
+ const values = config as Record<string, unknown>;
319
+ return requiredKeys.every((key) => typeof key === 'string' && key in values && !!values[key] && values[key] !== '0');
320
+ }
321
+
322
+ /**
323
+ * Find the first conditional step override whose required config values are satisfied.
324
+ */
325
+
326
+ function findWorkflowConditionalStep(step: any, config: unknown) {
327
+ if (!step || typeof step !== 'object' || !Array.isArray(step.conditional)) {
328
+ return null;
329
+ }
330
+
331
+ return (
332
+ step.conditional.find(
333
+ (conditionalStep: any) =>
334
+ conditionalStep &&
335
+ typeof conditionalStep === 'object' &&
336
+ hasRequiredWorkflowConfigValues(config, conditionalStep.required, conditionalStep.value),
337
+ ) || null
338
+ );
339
+ }
340
+
341
+ /**
342
+ * Merge one workflow step with its first matching conditional override and render its value.
343
+ */
344
+
345
+ function resolveWorkflowStep(step: any, config: Record<string, any> | null, timeZone: string | null = null) {
346
+ if (!step || typeof step !== 'object') {
347
+ return step;
348
+ }
349
+
350
+ const conditionalStep = findWorkflowConditionalStep(step, config);
351
+ const { required: _required, ...conditionalStepValues } = conditionalStep || {};
352
+ const mappedStep = conditionalStep ? { ...step, ...conditionalStepValues } : step;
353
+
354
+ return {
355
+ label: mappedStep.label,
356
+ value: typeof mappedStep.value === 'string' ? replaceWorkflowTemplateValues(mappedStep.value, config, timeZone) : undefined,
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Check whether one resolved workflow step has visible text.
362
+ */
363
+
364
+ function hasWorkflowStepValue(step: any) {
365
+ return !!step && typeof step.value === 'string' && step.value.trim() !== '';
366
+ }
367
+
368
+ /**
369
+ * Resolve ordered conditional overrides and placeholders for every workflow step.
370
+ * Steps left without visible text are dropped. Runtime reads and authoring previews share this.
371
+ */
372
+
373
+ export function resolveWorkflowSteps(steps: unknown, config: Record<string, any> | null, timeZone: string | null = null): any[] {
374
+ return (Array.isArray(steps) ? steps : [])
375
+ .map((step) => resolveWorkflowStep(step, config, timeZone))
376
+ .filter((step) => hasWorkflowStepValue(step));
377
+ }
378
+
379
+ /**
380
+ * Get window for workflow schedule
381
+ */
382
+
383
+ function getScheduleWindowMs(schedule: string | null | undefined, nextAt: Date) {
242
384
  if (!schedule) {
243
385
  return DEFAULT_SCHEDULE_WINDOW_MS;
244
386
  }
245
387
 
246
388
  try {
247
- const nextMs = CronExpressionParser.parse(schedule, { currentDate: nextAt })
248
- .next()
249
- .toDate()
250
- .getTime();
389
+ const nextMs = CronExpressionParser.parse(schedule, { currentDate: nextAt }).next().toDate().getTime();
251
390
  const diffMs = nextMs - nextAt.getTime();
252
391
 
253
- return Number.isFinite(diffMs) && diffMs > 0
254
- ? diffMs
255
- : DEFAULT_SCHEDULE_WINDOW_MS;
392
+ return Number.isFinite(diffMs) && diffMs > 0 ? diffMs : DEFAULT_SCHEDULE_WINDOW_MS;
256
393
  } catch {
257
394
  return DEFAULT_SCHEDULE_WINDOW_MS;
258
395
  }
@@ -262,11 +399,7 @@ function getScheduleWindowMs(
262
399
  * Check if current date is within workflow's schedule window
263
400
  */
264
401
 
265
- export function isWithinScheduleWindow(
266
- nextAt: Date | string | null | undefined,
267
- schedule?: string | null,
268
- now = new Date(),
269
- ) {
402
+ export function isWithinScheduleWindow(nextAt: Date | string | null | undefined, schedule?: string | null, now = new Date()) {
270
403
  const nextAtDate = nextAt ? new Date(nextAt) : null;
271
404
  if (!nextAtDate) {
272
405
  return false;
@@ -296,9 +429,7 @@ export function isWithinScheduleWindow(
296
429
  * Normalize workflow schedule interval into a valid positive integer.
297
430
  */
298
431
 
299
- function normalizeScheduleInterval(
300
- scheduleInterval: number | null | undefined,
301
- ) {
432
+ function normalizeScheduleInterval(scheduleInterval: number | null | undefined) {
302
433
  if (!Number.isFinite(scheduleInterval)) {
303
434
  return 1;
304
435
  }
@@ -348,10 +479,7 @@ export function getNextWorkflowScheduleDate(
348
479
  * Helper; check if workflow run is still active based on next follow-up time.
349
480
  */
350
481
 
351
- export function isWorkflowRunActive(
352
- workflowRun: WorkflowRunData | null,
353
- isFollowUp: boolean = false,
354
- ) {
482
+ export function isWorkflowRunActive(workflowRun: WorkflowRunData | null, isFollowUp: boolean = false) {
355
483
  if (!workflowRun) {
356
484
  return false;
357
485
  }
@@ -368,9 +496,7 @@ export function isWorkflowRunActive(
368
496
 
369
497
  if (isFollowUp) {
370
498
  const now = new Date();
371
- const followUpWindowStart = new Date(
372
- nextFollowUpAt.getTime() - 10 * 60 * 1000,
373
- );
499
+ const followUpWindowStart = new Date(nextFollowUpAt.getTime() - 10 * 60 * 1000);
374
500
 
375
501
  // Allow follow-up run only after entering the 10-minute pre-follow-up window.
376
502
  return now >= followUpWindowStart;
@@ -0,0 +1,302 @@
1
+ export const WORKFLOW_RECEIPT_CONTENT_PROJECTION_VERSION =
2
+ 'receipt-content:v1' as const;
3
+ export const WORKFLOW_LOG_STATE_PROJECTION_VERSION =
4
+ 'workflow-log-state:v1' as const;
5
+
6
+ export type CanonicalWorkflowFingerprintValue =
7
+ | null
8
+ | boolean
9
+ | number
10
+ | string
11
+ | CanonicalWorkflowFingerprintValue[]
12
+ | { [key: string]: CanonicalWorkflowFingerprintValue };
13
+
14
+ export type WorkflowLogFingerprintSource = {
15
+ id?: unknown;
16
+ organizationId?: unknown;
17
+ childOrgId?: unknown;
18
+ siteId?: unknown;
19
+ date?: unknown;
20
+ summary?: unknown;
21
+ details?: null | {
22
+ activity?: unknown;
23
+ logType?: unknown;
24
+ notes?: unknown;
25
+ metadata?: null | Record<string, unknown>;
26
+ };
27
+ };
28
+
29
+ export type WorkflowReceiptFingerprintOptions = {
30
+ attachmentManifest?: unknown[] | null;
31
+ flagColor?: unknown;
32
+ presentation?: Record<string, unknown> | null;
33
+ };
34
+
35
+ export type WorkflowReceiptContentProjection = {
36
+ version: typeof WORKFLOW_RECEIPT_CONTENT_PROJECTION_VERSION;
37
+ logId: string | null;
38
+ organizationId: string | null;
39
+ vendorId: string | null;
40
+ siteId: string | null;
41
+ activity: string | null;
42
+ logType: string | null;
43
+ date: string | null;
44
+ summary: string | null;
45
+ notes: string | null;
46
+ referenceNumber: string | null;
47
+ vendorName: string | null;
48
+ item: string | null;
49
+ quantity: number | null;
50
+ unit: string | null;
51
+ price: number | null;
52
+ voided: boolean | null;
53
+ tax: number | null;
54
+ lineItems: Array<{
55
+ label: string | null;
56
+ quantity: number | null;
57
+ unit: string | null;
58
+ amount: number | null;
59
+ }>;
60
+ presentation: CanonicalWorkflowFingerprintValue;
61
+ attachmentManifest: CanonicalWorkflowFingerprintValue[];
62
+ };
63
+
64
+ export type WorkflowLogStateProjection = {
65
+ version: typeof WORKFLOW_LOG_STATE_PROJECTION_VERSION;
66
+ receiptContent: WorkflowReceiptContentProjection;
67
+ flagColor: string | null;
68
+ };
69
+
70
+ export type WorkflowLogFingerprintProjections = {
71
+ receiptContent: WorkflowReceiptContentProjection;
72
+ workflowState: WorkflowLogStateProjection;
73
+ };
74
+
75
+ /*
76
+ * Normalize one arbitrary value into the recursively stable JSON value used by
77
+ * workflow fingerprint projections.
78
+ */
79
+ export function canonicalizeWorkflowFingerprintValue(
80
+ value: unknown,
81
+ ): CanonicalWorkflowFingerprintValue {
82
+ if (value === null || value === undefined) {
83
+ return null;
84
+ }
85
+ if (typeof value === 'bigint') {
86
+ return String(value);
87
+ }
88
+ if (value instanceof Date) {
89
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
90
+ }
91
+ if (Array.isArray(value)) {
92
+ return value.map(canonicalizeWorkflowFingerprintValue);
93
+ }
94
+ if (typeof value === 'number') {
95
+ return Number.isFinite(value) ? (Object.is(value, -0) ? 0 : value) : null;
96
+ }
97
+ if (typeof value === 'string' || typeof value === 'boolean') {
98
+ return value;
99
+ }
100
+ if (typeof value === 'object') {
101
+ return Object.keys(value as Record<string, unknown>)
102
+ .sort()
103
+ .reduce<Record<string, CanonicalWorkflowFingerprintValue>>(
104
+ (result, key) => {
105
+ result[key] = canonicalizeWorkflowFingerprintValue(
106
+ (value as Record<string, unknown>)[key],
107
+ );
108
+ return result;
109
+ },
110
+ {},
111
+ );
112
+ }
113
+
114
+ return null;
115
+ }
116
+
117
+ /*
118
+ * Serialize one workflow fingerprint projection with stable recursive object
119
+ * ordering and explicit null values.
120
+ */
121
+ export function serializeWorkflowFingerprintProjection(value: unknown) {
122
+ return JSON.stringify(canonicalizeWorkflowFingerprintValue(value));
123
+ }
124
+
125
+ /*
126
+ * Normalize one database identifier into its stable string representation.
127
+ */
128
+ function normalizeWorkflowFingerprintId(value: unknown): string | null {
129
+ if (value === null || value === undefined || value === '') {
130
+ return null;
131
+ }
132
+ if (typeof value === 'bigint') {
133
+ return String(value);
134
+ }
135
+ if (typeof value === 'number') {
136
+ return Number.isFinite(value) ? String(value) : null;
137
+ }
138
+ if (typeof value === 'string') {
139
+ return value.trim() || null;
140
+ }
141
+
142
+ return null;
143
+ }
144
+
145
+ /*
146
+ * Normalize one optional receipt text without altering meaningful nonempty
147
+ * whitespace or casing.
148
+ */
149
+ function normalizeWorkflowFingerprintText(value: unknown): string | null {
150
+ if (value === null || value === undefined || value === '') {
151
+ return null;
152
+ }
153
+
154
+ return typeof value === 'string' ? value : String(value);
155
+ }
156
+
157
+ /*
158
+ * Normalize one optional receipt number into a finite JavaScript number.
159
+ */
160
+ function normalizeWorkflowFingerprintNumber(value: unknown): number | null {
161
+ if (value === null || value === undefined || value === '') {
162
+ return null;
163
+ }
164
+ const normalized = typeof value === 'number' ? value : Number(value);
165
+ if (!Number.isFinite(normalized)) {
166
+ return null;
167
+ }
168
+
169
+ return Object.is(normalized, -0) ? 0 : normalized;
170
+ }
171
+
172
+ /*
173
+ * Normalize one optional receipt date into an ISO string.
174
+ */
175
+ function normalizeWorkflowFingerprintDate(value: unknown): string | null {
176
+ if (value === null || value === undefined || value === '') {
177
+ return null;
178
+ }
179
+ const date =
180
+ value instanceof Date ? value : new Date(value as string | number);
181
+
182
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
183
+ }
184
+
185
+ /*
186
+ * Normalize one workflow flag color into the canonical enum-like value used
187
+ * for state comparisons.
188
+ */
189
+ function normalizeWorkflowFingerprintFlagColor(value: unknown): string | null {
190
+ if (typeof value !== 'string') {
191
+ return null;
192
+ }
193
+ const color = value.trim();
194
+
195
+ return color ? color.toUpperCase() : null;
196
+ }
197
+
198
+ /*
199
+ * Project ordered receipt rows into only the values that affect delivered
200
+ * receipt semantics.
201
+ */
202
+ function getWorkflowReceiptLineItems(
203
+ value: unknown,
204
+ ): WorkflowReceiptContentProjection['lineItems'] {
205
+ if (!Array.isArray(value)) {
206
+ return [];
207
+ }
208
+
209
+ return value.map((rawLine) => {
210
+ const line =
211
+ rawLine && typeof rawLine === 'object' && !Array.isArray(rawLine)
212
+ ? (rawLine as Record<string, unknown>)
213
+ : {};
214
+
215
+ return {
216
+ label: normalizeWorkflowFingerprintText(line.label),
217
+ quantity: normalizeWorkflowFingerprintNumber(line.quantity),
218
+ unit: normalizeWorkflowFingerprintText(line.unit),
219
+ amount: normalizeWorkflowFingerprintNumber(line.value),
220
+ };
221
+ });
222
+ }
223
+
224
+ /*
225
+ * Build the versioned canonical receipt-content projection for one persisted
226
+ * log without including workflow-only state such as flag color.
227
+ */
228
+ export function getWorkflowReceiptContentProjection(
229
+ log: WorkflowLogFingerprintSource,
230
+ options: WorkflowReceiptFingerprintOptions = {},
231
+ ): WorkflowReceiptContentProjection {
232
+ const details = log.details || {};
233
+ const metadata = details.metadata || {};
234
+ const presentation = canonicalizeWorkflowFingerprintValue(
235
+ options.presentation,
236
+ );
237
+ const attachmentManifest = canonicalizeWorkflowFingerprintValue(
238
+ options.attachmentManifest || [],
239
+ );
240
+
241
+ return {
242
+ version: WORKFLOW_RECEIPT_CONTENT_PROJECTION_VERSION,
243
+ logId: normalizeWorkflowFingerprintId(log.id),
244
+ organizationId: normalizeWorkflowFingerprintId(log.organizationId),
245
+ vendorId: normalizeWorkflowFingerprintId(
246
+ log.childOrgId ?? metadata.childOrgId,
247
+ ),
248
+ siteId: normalizeWorkflowFingerprintId(log.siteId ?? metadata.siteId),
249
+ activity: normalizeWorkflowFingerprintText(details.activity),
250
+ logType: normalizeWorkflowFingerprintText(details.logType),
251
+ date: normalizeWorkflowFingerprintDate(log.date),
252
+ summary: normalizeWorkflowFingerprintText(log.summary),
253
+ notes: normalizeWorkflowFingerprintText(details.notes),
254
+ referenceNumber: normalizeWorkflowFingerprintText(metadata.referenceNumber),
255
+ vendorName: normalizeWorkflowFingerprintText(metadata.otherParty),
256
+ item: normalizeWorkflowFingerprintText(metadata.item),
257
+ quantity: normalizeWorkflowFingerprintNumber(metadata.quantity),
258
+ unit: normalizeWorkflowFingerprintText(metadata.unit),
259
+ price: normalizeWorkflowFingerprintNumber(metadata.price),
260
+ voided: typeof metadata.voided === 'boolean' ? metadata.voided : null,
261
+ tax: normalizeWorkflowFingerprintNumber(metadata.tax),
262
+ lineItems: getWorkflowReceiptLineItems(metadata.values),
263
+ presentation,
264
+ attachmentManifest: Array.isArray(attachmentManifest)
265
+ ? attachmentManifest
266
+ : [],
267
+ };
268
+ }
269
+
270
+ /*
271
+ * Build the versioned workflow-state projection by combining receipt content
272
+ * with current non-content state that workflow instructions may reference.
273
+ */
274
+ export function getWorkflowLogStateProjection(
275
+ receiptContent: WorkflowReceiptContentProjection,
276
+ flagColor: unknown,
277
+ ): WorkflowLogStateProjection {
278
+ return {
279
+ version: WORKFLOW_LOG_STATE_PROJECTION_VERSION,
280
+ receiptContent,
281
+ flagColor: normalizeWorkflowFingerprintFlagColor(flagColor),
282
+ };
283
+ }
284
+
285
+ /*
286
+ * Build both canonical projections needed by a log-triggered workflow run.
287
+ */
288
+ export function getWorkflowLogFingerprintProjections(
289
+ log: WorkflowLogFingerprintSource,
290
+ options: WorkflowReceiptFingerprintOptions = {},
291
+ ): WorkflowLogFingerprintProjections {
292
+ const receiptContent = getWorkflowReceiptContentProjection(log, options);
293
+ const metadata = log.details?.metadata || {};
294
+ const flagColor = Object.hasOwn(options, 'flagColor')
295
+ ? options.flagColor
296
+ : metadata.flagColor;
297
+
298
+ return {
299
+ receiptContent,
300
+ workflowState: getWorkflowLogStateProjection(receiptContent, flagColor),
301
+ };
302
+ }