@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
@@ -0,0 +1,589 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { SHEET_MAX_COLUMN_COUNT, SHEET_MAX_ROW_COUNT } from '../src/constants/sheet.ts';
3
+ import type { SheetNamedRangeObj, SheetStructureOperationEnum } from '../src/types/sheet.d.ts';
4
+ import { shiftSheetMergedRangesForStructureEdit } from '../src/utils/sheetDesign.ts';
5
+ import { parseSheetFormulaExpression } from '../src/utils/sheetFormulaParser.ts';
6
+ import { getSheetFormulaColumnLabel, getSheetFormulaExpression } from '../src/utils/sheetFormulaSyntax.ts';
7
+ import {
8
+ getSheetNamedRangeAfterStructureEdit,
9
+ getSheetStructureCellCoordAfterEdit,
10
+ type SheetStructureBounds,
11
+ } from '../src/utils/sheetStructureEdit.ts';
12
+ import {
13
+ getSheetStructureRangeReferenceAfterEdit,
14
+ getSheetStructureReferenceInverseEdit,
15
+ rewriteSheetFormulaForStructureEdit,
16
+ type SheetStructureReferenceEdit,
17
+ } from '../src/utils/sheetStructureReferences.ts';
18
+
19
+ const FILE_CONSTANTS = {
20
+ editedTabId: 'T1',
21
+ operations: ['INSERT_ROW_ABOVE', 'INSERT_COLUMN_LEFT', 'DELETE_ROW', 'DELETE_COLUMN'] as SheetStructureOperationEnum[],
22
+ region: {
23
+ endColumnIndex: 4,
24
+ endRowIndex: 20,
25
+ startColumnIndex: 2,
26
+ startRowIndex: 10,
27
+ } as SheetStructureBounds,
28
+ tabs: new Map([
29
+ ['main', 'T1'],
30
+ ['other', 'T2'],
31
+ ['my tab', 'T3'],
32
+ ]),
33
+ };
34
+
35
+ /*
36
+ * Return whether one operation inserts or deletes a row.
37
+ */
38
+ function isRowOperation(operation: SheetStructureOperationEnum) {
39
+ return operation === 'INSERT_ROW_ABOVE' || operation === 'DELETE_ROW';
40
+ }
41
+
42
+ /*
43
+ * Rewrite one formula on tab T1 (or `formulaTabId`) through an edit on T1,
44
+ * computing lossy spans against the inverse for an axis of `axisCountBefore`.
45
+ */
46
+ function rewrite(text: string, edit: SheetStructureReferenceEdit, options: { axisCountBefore?: number; formulaTabId?: string } = {}) {
47
+ const axisCountBefore = options.axisCountBefore ?? (isRowOperation(edit.operation) ? 400 : 200);
48
+
49
+ return rewriteSheetFormulaForStructureEdit(text, {
50
+ edit,
51
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
52
+ formulaSheetTabId: options.formulaTabId ?? FILE_CONSTANTS.editedTabId,
53
+ inverseEdit: getSheetStructureReferenceInverseEdit(edit, axisCountBefore),
54
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
55
+ });
56
+ }
57
+
58
+ /*
59
+ * Undo one rewrite: apply the inverse edit to its output with its lossy spans
60
+ * as overrides, the way a structure replay does.
61
+ */
62
+ function undo(
63
+ forwardText: string,
64
+ forward: ReturnType<typeof rewrite>,
65
+ edit: SheetStructureReferenceEdit,
66
+ axisCountBefore: number,
67
+ formulaTabId = FILE_CONSTANTS.editedTabId,
68
+ ) {
69
+ return rewriteSheetFormulaForStructureEdit(forwardText, {
70
+ edit: getSheetStructureReferenceInverseEdit(edit, axisCountBefore),
71
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
72
+ formulaSheetTabId: formulaTabId,
73
+ inverseEdit: edit,
74
+ overrides: forward.lossyTokens,
75
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
76
+ });
77
+ }
78
+
79
+ /*
80
+ * Verify the golden rewrite table for row and column inserts and deletes.
81
+ */
82
+ describe('structure edit formula references', () => {
83
+ it.each([
84
+ ['=A10', '=A11'],
85
+ ['=a10', '=a11'],
86
+ ['=$B$10', '=$B$11'],
87
+ ['=B$10+$B10', '=B$11+$B11'],
88
+ ['=A4', '=A4'],
89
+ ['=A5', '=A6'],
90
+ ['= A10 ', '= A11 '],
91
+ ['=SUM(A1:A10)', '=SUM(A1:A11)'],
92
+ ['=SUM(A5:A10)', '=SUM(A6:A11)'],
93
+ ['=SUM(A1:A4)', '=SUM(A1:A4)'],
94
+ ['=SUM(A10:A1)', '=SUM(A11:A1)'],
95
+ ['=SUM(a1 : $b$9)', '=SUM(a1 : $b$10)'],
96
+ ['=SUM(C3:C)', '=SUM(C3:C)'],
97
+ ['=SUM(C6:$c)', '=SUM(C7:$c)'],
98
+ ['=main!A10', '=main!A11'],
99
+ ['=MAIN!A10:B12', '=MAIN!A11:B13'],
100
+ ["='main'!A10", "='main'!A11"],
101
+ ['=main!A1:main!A10', '=main!A1:main!A11'],
102
+ ['=other!A10', '=other!A10'],
103
+ ['=missing!A10', '=missing!A10'],
104
+ ['=@orders(A10, "total")', '=@orders(A11, "total")'],
105
+ ['=@orders( A10+1 ,"total")', '=@orders( A11+1 ,"total")'],
106
+ ['=@orders("total") WHERE id=A10 AND name = B3', '=@orders("total") WHERE id=A11 AND name = B3'],
107
+ ['="A10"&A10', '="A10"&A11'],
108
+ ['=LOG10(A10)', '=LOG10(A11)'],
109
+ ['=SUM(A10,', '=SUM(A11,'],
110
+ ['=A10 +* B10', '=A11 +* B11'],
111
+ ['=#REF!+A10', '=#REF!+A11'],
112
+ ['=1+2', '=1+2'],
113
+ ['A10', 'A10'],
114
+ ])('INSERT_ROW_ABOVE 5: %s -> %s', (input, expected) => {
115
+ expect(rewrite(input, { index: 5, operation: 'INSERT_ROW_ABOVE' }).text).toBe(expected);
116
+ });
117
+
118
+ it.each([
119
+ ['=A10', '=#REF!', 1],
120
+ ['=main!A10+1', '=#REF!+1', 1],
121
+ ['=A11', '=A10', 0],
122
+ ['=A9', '=A9', 0],
123
+ ['=SUM(A1:A10)', '=SUM(A1:A9)', 0],
124
+ ['=SUM(A10:A20)', '=SUM(A10:A19)', 0],
125
+ ['=SUM(A20:A10)', '=SUM(A19:A10)', 0],
126
+ ['=SUM(A10:B10)', '=SUM(#REF!)', 1],
127
+ ['=SUM(A5:A20)', '=SUM(A5:A19)', 0],
128
+ ['=SUM(C10:C)', '=SUM(C10:C)', 0],
129
+ ['=SUM(C11:C)', '=SUM(C10:C)', 0],
130
+ ['=@orders(A10, "total")', '=@orders(#REF!, "total")', 1],
131
+ ['=@orders("total") WHERE id = A10', '=@orders("total") WHERE id = #REF!', 1],
132
+ ['=IFERROR(A10, A12)', '=IFERROR(#REF!, A11)', 1],
133
+ ])('DELETE_ROW 10: %s -> %s', (input, expected, refErrorCount) => {
134
+ const result = rewrite(input, { index: 10, operation: 'DELETE_ROW' });
135
+
136
+ expect(result.text).toBe(expected);
137
+ expect(result.refErrorCount).toBe(refErrorCount);
138
+ expect(result.changed).toBe(input !== expected);
139
+ });
140
+
141
+ it.each([
142
+ ['=A1+B1+c1', '=A1+C1+d1'],
143
+ ['=SUM(A1:C1)', '=SUM(A1:D1)'],
144
+ ['=SUM(B3:B)', '=SUM(C3:C)'],
145
+ ['=SUM(A3:b)', '=SUM(A3:c)'],
146
+ ['=$Z$1', '=$AA$1'],
147
+ ['=hz9+ZZ9', '=ia9+ZZ9'],
148
+ ['=IV9', '=#REF!'],
149
+ ['=aB10', '=AC10'],
150
+ ])('INSERT_COLUMN_LEFT 2: %s -> %s', (input, expected) => {
151
+ expect(rewrite(input, { index: 2, operation: 'INSERT_COLUMN_LEFT' }).text).toBe(expected);
152
+ });
153
+
154
+ it.each([
155
+ ['=B1', '=#REF!'],
156
+ ['=C1', '=B1'],
157
+ ['=SUM(A1:C1)', '=SUM(A1:B1)'],
158
+ ['=SUM(B1:B)', '=SUM(#REF!)'],
159
+ ['=SUM(C1:D)', '=SUM(B1:C)'],
160
+ ['=AA1', '=Z1'],
161
+ ])('DELETE_COLUMN 2: %s -> %s', (input, expected) => {
162
+ expect(rewrite(input, { index: 2, operation: 'DELETE_COLUMN' }).text).toBe(expected);
163
+ });
164
+
165
+ it('rewrites references on other tabs only when they point at the edited tab', () => {
166
+ const edit: SheetStructureReferenceEdit = {
167
+ index: 5,
168
+ operation: 'INSERT_ROW_ABOVE',
169
+ };
170
+
171
+ expect(rewrite('=A10+main!A10', edit, { formulaTabId: 'T2' }).text).toBe('=A10+main!A11');
172
+ expect(rewrite("=SUM('My Tab'!A10:A12)", edit, { formulaTabId: 'T3' }).text).toBe("=SUM('My Tab'!A10:A12)");
173
+ expect(
174
+ rewriteSheetFormulaForStructureEdit("=SUM('My Tab'!A10:A12)+A1", {
175
+ edit,
176
+ editedSheetTabId: 'T3',
177
+ formulaSheetTabId: 'T1',
178
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
179
+ }).text,
180
+ ).toBe("=SUM('My Tab'!A11:A13)+A1");
181
+ });
182
+
183
+ it('turns references pushed past the grid cap into #REF! and clamps range ends', () => {
184
+ const rowEdit: SheetStructureReferenceEdit = {
185
+ index: 1,
186
+ operation: 'INSERT_ROW_ABOVE',
187
+ };
188
+ const rowOptions = { axisCountBefore: SHEET_MAX_ROW_COUNT };
189
+
190
+ expect(rewrite('=A500', rowEdit, rowOptions).text).toBe('=#REF!');
191
+ expect(rewrite('=A499', rowEdit, rowOptions).text).toBe('=A500');
192
+ expect(rewrite('=SUM(A2:A500)', rowEdit, rowOptions).text).toBe('=SUM(A3:A500)');
193
+ expect(rewrite('=SUM(A500:B500)', rowEdit, rowOptions).text).toBe('=SUM(#REF!)');
194
+ expect(rewrite('=SUM(A1:A1000)+A600', rowEdit, rowOptions).text).toBe('=SUM(A2:A1000)+A600');
195
+ expect(rewrite('=IV1+SUM(A1:IV1)', { index: 1, operation: 'INSERT_COLUMN_LEFT' }).text).toBe('=#REF!+SUM(B1:IV1)');
196
+ });
197
+
198
+ it('reports lossy spans an undo restores exactly, and only those', () => {
199
+ const edit: SheetStructureReferenceEdit = {
200
+ index: 10,
201
+ operation: 'DELETE_ROW',
202
+ };
203
+ const input = '=A10+SUM(A1:A10)+A20+SUM(A5:A30)';
204
+ const forward = rewrite(input, edit);
205
+
206
+ expect(forward.text).toBe('=#REF!+SUM(A1:A9)+A19+SUM(A5:A29)');
207
+ expect(forward.lossyTokens).toEqual([
208
+ { expected: '#REF!', length: 5, start: 1, text: 'A10' },
209
+ { expected: 'A1:A9', length: 5, start: 11, text: 'A1:A10' },
210
+ ]);
211
+ expect(undo(forward.text, forward, edit, 400).text).toBe(input);
212
+ });
213
+
214
+ it('collects lossy tokens whose text did not change (critic C2)', () => {
215
+ const insertAtCap: SheetStructureReferenceEdit = {
216
+ index: 1,
217
+ operation: 'INSERT_ROW_ABOVE',
218
+ };
219
+ const clamped = rewrite('=SUM(A2:A499)+SUM(A2:A500)', insertAtCap, {
220
+ axisCountBefore: SHEET_MAX_ROW_COUNT,
221
+ });
222
+
223
+ // A2:A500 reads A3:A500 after the insert; the re-appending undo keeps
224
+ // the end on the last line, so only the range that grew into it is lossy
225
+ expect(clamped.text).toBe('=SUM(A3:A500)+SUM(A3:A500)');
226
+ expect(clamped.lossyTokens).toEqual([{ expected: 'A3:A500', length: 7, start: 5, text: 'A2:A499' }]);
227
+
228
+ const openEnd = rewrite('=SUM(C3:C)', {
229
+ index: 3,
230
+ operation: 'DELETE_ROW',
231
+ });
232
+ expect(openEnd.text).toBe('=SUM(C3:C)');
233
+ expect(openEnd.lossyTokens).toEqual([{ expected: 'C3:C', length: 4, start: 5, text: 'C3:C' }]);
234
+ expect(openEnd.changed).toBe(false);
235
+ });
236
+
237
+ it('undoes the insert at the cap without restores when nothing was lost', () => {
238
+ const edit: SheetStructureReferenceEdit = {
239
+ index: 1,
240
+ operation: 'INSERT_ROW_ABOVE',
241
+ };
242
+ const input = '=SUM(A1:A500)+A10';
243
+ const forward = rewrite(input, edit, {
244
+ axisCountBefore: SHEET_MAX_ROW_COUNT,
245
+ });
246
+
247
+ expect(forward.text).toBe('=SUM(A2:A500)+A11');
248
+ expect(forward.lossyTokens).toEqual([]);
249
+ expect(undo(forward.text, forward, edit, SHEET_MAX_ROW_COUNT).text).toBe(input);
250
+ });
251
+
252
+ it('undo then redo reproduces both sides with fresh restores (critic C1)', () => {
253
+ const edit: SheetStructureReferenceEdit = {
254
+ index: 10,
255
+ operation: 'DELETE_ROW',
256
+ };
257
+ const input = '=A10*2+SUM(A10:A12)';
258
+ const forward = rewrite(input, edit);
259
+ const undone = undo(forward.text, forward, edit, 400);
260
+ const redone = rewriteSheetFormulaForStructureEdit(undone.text, {
261
+ edit,
262
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
263
+ formulaSheetTabId: FILE_CONSTANTS.editedTabId,
264
+ inverseEdit: getSheetStructureReferenceInverseEdit(edit, 400),
265
+ overrides: undone.lossyTokens,
266
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
267
+ });
268
+
269
+ expect(forward.text).toBe('=#REF!*2+SUM(A10:A11)');
270
+ expect(forward.refErrorCount).toBe(1);
271
+ expect(forward.inverseRefErrorCount).toBe(0);
272
+ expect(undone.text).toBe(input);
273
+ expect(undone.lossyTokens).toEqual([]);
274
+ // The redo's #REF! is expected: the undo reports it for its other side
275
+ expect(undone.refErrorCount).toBe(0);
276
+ expect(undone.inverseRefErrorCount).toBe(1);
277
+ expect(redone.text).toBe(forward.text);
278
+ expect(redone.refErrorCount).toBe(1);
279
+ expect(redone.lossyTokens).toEqual(forward.lossyTokens);
280
+ });
281
+
282
+ it('an undo that would create a #REF! nobody expected reports it', () => {
283
+ const edit: SheetStructureReferenceEdit = {
284
+ index: 5,
285
+ operation: 'INSERT_ROW_ABOVE',
286
+ };
287
+ // Written after the insert: it points at the inserted row
288
+ const undone = rewriteSheetFormulaForStructureEdit('=A5+A6', {
289
+ edit: getSheetStructureReferenceInverseEdit(edit, 400),
290
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
291
+ formulaSheetTabId: FILE_CONSTANTS.editedTabId,
292
+ inverseEdit: edit,
293
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
294
+ });
295
+
296
+ expect(undone.text).toBe('=#REF!+A5');
297
+ expect(undone.refErrorCount).toBe(1);
298
+ expect(undone.lossyTokens).toEqual([{ expected: '#REF!', length: 5, start: 1, text: 'A5' }]);
299
+ });
300
+
301
+ it('restores a garbage formula whose tokenization the rewrite changes', () => {
302
+ const edit: SheetStructureReferenceEdit = {
303
+ index: 5,
304
+ operation: 'DELETE_ROW',
305
+ };
306
+ // #REF! followed by $B$5 reads as one REF!$B$5 reference afterwards
307
+ const input = '=A5$B$6';
308
+ const forward = rewrite(input, edit);
309
+
310
+ expect(forward.text).toBe('=#REF!$B$5');
311
+ expect(forward.lossyTokens).toEqual([
312
+ { expected: '#REF!', length: 5, start: 1, text: 'A5' },
313
+ { expected: 'B$5', length: 3, start: 7, text: 'B$6' },
314
+ ]);
315
+ expect(undo(forward.text, forward, edit, 400).text).toBe(input);
316
+ });
317
+
318
+ it('rejects overrides whose guard text no longer matches and uses plain math', () => {
319
+ const result = rewriteSheetFormulaForStructureEdit('=A10+A20', {
320
+ edit: { index: 10, operation: 'INSERT_ROW_ABOVE' },
321
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
322
+ formulaSheetTabId: FILE_CONSTANTS.editedTabId,
323
+ overrides: [{ expected: '#REF!', length: 3, start: 1, text: 'A10' }],
324
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
325
+ });
326
+
327
+ expect(result.overridesRejected).toBe(true);
328
+ expect(result.text).toBe('=A11+A21');
329
+ });
330
+ });
331
+
332
+ /*
333
+ * Return a deterministic pseudo-random generator (mulberry32).
334
+ */
335
+ function getRandom(seed: number) {
336
+ let state = seed >>> 0;
337
+
338
+ return () => {
339
+ state = (state + 0x6d2b79f5) >>> 0;
340
+ let value = state;
341
+ value = Math.imul(value ^ (value >>> 15), value | 1);
342
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
343
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
344
+ };
345
+ }
346
+
347
+ /*
348
+ * Return one random integer in [min, max].
349
+ */
350
+ function randomInt(random: () => number, min: number, max: number) {
351
+ return min + Math.floor(random() * (max - min + 1));
352
+ }
353
+
354
+ /*
355
+ * Return one random element of a list.
356
+ */
357
+ function pick<T>(random: () => number, items: readonly T[]) {
358
+ return items[Math.floor(random() * items.length)];
359
+ }
360
+
361
+ /*
362
+ * Return a random line index that often lands on the interesting edges.
363
+ */
364
+ function randomLine(random: () => number, max: number) {
365
+ return random() < 0.3 ? pick(random, [1, 2, 9, 10, 11, max - 1, max, max + 1]) : randomInt(random, 1, max + 5);
366
+ }
367
+
368
+ /*
369
+ * Return one random coordinate text with random $ markers and case.
370
+ */
371
+ function randomCoordinate(random: () => number) {
372
+ const label = getSheetFormulaColumnLabel(randomLine(random, SHEET_MAX_COLUMN_COUNT));
373
+ const text = `${random() < 0.2 ? '$' : ''}${label}${random() < 0.2 ? '$' : ''}${randomLine(random, SHEET_MAX_ROW_COUNT)}`;
374
+
375
+ return random() < 0.2 ? text.toLowerCase() : text;
376
+ }
377
+
378
+ /*
379
+ * Return one random reference, range or formula fragment.
380
+ */
381
+ function randomFragment(random: () => number): string {
382
+ const qualifier = pick(random, ['', '', '', 'main!', "'Main'!", 'other!', 'missing!', "'My Tab'!"]);
383
+ const roll = random();
384
+ if (roll < 0.3) {
385
+ return `${qualifier}${randomCoordinate(random)}`;
386
+ }
387
+ if (roll < 0.55) {
388
+ const end = random() < 0.2 ? getSheetFormulaColumnLabel(randomInt(random, 1, 30)) : randomCoordinate(random);
389
+ return `${qualifier}${randomCoordinate(random)}${pick(random, [':', ' : '])}${end}`;
390
+ }
391
+ if (roll < 0.65) {
392
+ return `@orders(${randomCoordinate(random)}, "total")`;
393
+ }
394
+ if (roll < 0.72) {
395
+ return `@orders("total") WHERE id = ${randomCoordinate(random)} AND name = "x"`;
396
+ }
397
+ if (roll < 0.78) {
398
+ return `SUM(${randomFragment(random)}, ${randomFragment(random)})`;
399
+ }
400
+ if (roll < 0.83) {
401
+ return `LOG10(${randomCoordinate(random)})`;
402
+ }
403
+ return pick(random, ['"A5"', '12', '#REF!', 'TRUE', '(', ')', ',']);
404
+ }
405
+
406
+ /*
407
+ * Return one random formula made of fragments.
408
+ */
409
+ function randomFormula(random: () => number) {
410
+ const parts = Array.from({ length: randomInt(random, 1, 5) }, () => randomFragment(random));
411
+
412
+ return `=${parts.join(pick(random, ['+', ' - ', '*', ', ', '&']))}`;
413
+ }
414
+
415
+ /*
416
+ * Return one random structure edit, sometimes with protected bounds.
417
+ */
418
+ function randomEdit(random: () => number): {
419
+ axisCountBefore: number;
420
+ edit: SheetStructureReferenceEdit;
421
+ } {
422
+ const operation = pick(random, FILE_CONSTANTS.operations);
423
+ const max = isRowOperation(operation) ? SHEET_MAX_ROW_COUNT : SHEET_MAX_COLUMN_COUNT;
424
+ const axisCountBefore = random() < 0.5 ? max : randomInt(random, 1, max);
425
+
426
+ return {
427
+ axisCountBefore,
428
+ edit: {
429
+ index: random() < 0.3 ? pick(random, [1, 2, 10, max]) : randomLine(random, max),
430
+ operation,
431
+ },
432
+ };
433
+ }
434
+
435
+ /*
436
+ * Property tests: the rules hold for random formulas, edits and regions.
437
+ */
438
+ describe('structure edit formula references (properties)', () => {
439
+ it('a single-cell reference lands where its cell goes', () => {
440
+ const random = getRandom(11);
441
+ for (let run = 0; run < 3000; run += 1) {
442
+ const { edit } = randomEdit(random);
443
+ const rowIndex = randomLine(random, SHEET_MAX_ROW_COUNT);
444
+ const columnIndex = randomLine(random, SHEET_MAX_COLUMN_COUNT);
445
+ const label = getSheetFormulaColumnLabel(columnIndex);
446
+ const max = isRowOperation(edit.operation) ? SHEET_MAX_ROW_COUNT : SHEET_MAX_COLUMN_COUNT;
447
+ const line = isRowOperation(edit.operation) ? rowIndex : columnIndex;
448
+ const coord = getSheetStructureCellCoordAfterEdit(rowIndex, columnIndex, edit.operation, edit.index);
449
+ const expected =
450
+ line > max
451
+ ? `=${label}${rowIndex}`
452
+ : !coord || (isRowOperation(edit.operation) ? coord.rowIndex : coord.columnIndex) > max
453
+ ? '=#REF!'
454
+ : `=${getSheetFormulaColumnLabel(coord.columnIndex)}${coord.rowIndex}`;
455
+
456
+ expect(rewrite(`=${label}${rowIndex}`, edit).text).toBe(expected);
457
+ }
458
+ });
459
+
460
+ it('undo with the lossy spans restores every formula exactly, and redo reproduces the edit', () => {
461
+ const random = getRandom(7);
462
+ for (let run = 0; run < 4000; run += 1) {
463
+ const input = randomFormula(random);
464
+ const { axisCountBefore, edit } = randomEdit(random);
465
+ const formulaTabId = random() < 0.8 ? 'T1' : 'T2';
466
+ const forward = rewrite(input, edit, { axisCountBefore, formulaTabId });
467
+ const undone = undo(forward.text, forward, edit, axisCountBefore, formulaTabId);
468
+ const redone = rewriteSheetFormulaForStructureEdit(undone.text, {
469
+ edit,
470
+ editedSheetTabId: FILE_CONSTANTS.editedTabId,
471
+ formulaSheetTabId: formulaTabId,
472
+ overrides: undone.lossyTokens,
473
+ sheetTabIdByNameKey: FILE_CONSTANTS.tabs,
474
+ });
475
+ const context = JSON.stringify({ edit, forward, input });
476
+
477
+ expect(undone.text, context).toBe(input);
478
+ expect(undone.overridesRejected, context).toBe(false);
479
+ expect(redone.text, context).toBe(forward.text);
480
+ // Every #REF! the redo brings back was announced by the undo
481
+ expect(redone.refErrorCount, context).toBe(undone.inverseRefErrorCount);
482
+ // Generated formulas never need the whole-text fallback
483
+ expect(
484
+ forward.lossyTokens.some((token) => token.start === 0),
485
+ context,
486
+ ).toBe(false);
487
+ }
488
+ });
489
+
490
+ it('only #REF! and deleted edges are lossy for plain edits below the cap', () => {
491
+ const random = getRandom(5);
492
+ for (let run = 0; run < 2000; run += 1) {
493
+ const operation = pick(random, FILE_CONSTANTS.operations);
494
+ const index = randomInt(random, 1, 60);
495
+ const start = randomInt(random, 1, 60);
496
+ const end = start + randomInt(random, 0, 10);
497
+ const input = isRowOperation(operation)
498
+ ? `=SUM(B${start}:C${end})+B${start}`
499
+ : `=SUM(${getSheetFormulaColumnLabel(start)}2:${getSheetFormulaColumnLabel(end)}3)+${getSheetFormulaColumnLabel(start)}2`;
500
+ const result = rewrite(input, { index, operation });
501
+ const deletes = operation === 'DELETE_ROW' || operation === 'DELETE_COLUMN';
502
+ const touchesEdge = deletes && (index === start || index === end);
503
+
504
+ expect(result.lossyTokens.length > 0, input).toBe(touchesEdge);
505
+ }
506
+ });
507
+
508
+ it('a valid formula stays valid, #REF! literals included', () => {
509
+ const random = getRandom(19);
510
+ for (let run = 0; run < 2000; run += 1) {
511
+ const cell = () => `${getSheetFormulaColumnLabel(randomInt(random, 1, 30))}${randomLine(random, SHEET_MAX_ROW_COUNT)}`;
512
+ const fragments = Array.from({ length: randomInt(random, 1, 4) }, () =>
513
+ pick(random, [
514
+ () => cell(),
515
+ () => `main!${cell()}`,
516
+ () => `SUM(${cell()}:${cell()})`,
517
+ () => `SUM(${cell()}:C)`,
518
+ () => `IFERROR(${cell()}, 0)`,
519
+ ])(),
520
+ );
521
+ const input = `=${fragments.join(' + ')}`;
522
+ const { axisCountBefore, edit } = randomEdit(random);
523
+ const result = rewrite(input, edit, { axisCountBefore });
524
+
525
+ expect(parseSheetFormulaExpression(getSheetFormulaExpression(input)), input).not.toBeNull();
526
+ expect(
527
+ parseSheetFormulaExpression(getSheetFormulaExpression(result.text)),
528
+ JSON.stringify({ edit, input, output: result.text }),
529
+ ).not.toBeNull();
530
+ }
531
+ });
532
+
533
+ it('a rewrite of a text without references is the identity', () => {
534
+ const random = getRandom(3);
535
+ for (let run = 0; run < 500; run += 1) {
536
+ const { edit } = randomEdit(random);
537
+ for (const input of ['=1+2', '="A5"&"B6"', '=SUM()', 'plain A5', '']) {
538
+ const result = rewrite(input, edit);
539
+ expect(result).toEqual({
540
+ changed: false,
541
+ inverseRefErrorCount: 0,
542
+ lossyTokens: [],
543
+ overridesRejected: false,
544
+ refErrorCount: 0,
545
+ text: input,
546
+ });
547
+ }
548
+ }
549
+ });
550
+
551
+ it('without regions a range follows the named-range and merge interval math', () => {
552
+ const random = getRandom(13);
553
+ for (let run = 0; run < 3000; run += 1) {
554
+ const operation = pick(random, FILE_CONSTANTS.operations);
555
+ const isRow = isRowOperation(operation);
556
+ const max = isRow ? SHEET_MAX_ROW_COUNT : SHEET_MAX_COLUMN_COUNT;
557
+ const index = randomLine(random, max);
558
+ const start = randomLine(random, max);
559
+ const end = Math.min(start + randomInt(random, 0, 12), max + 3);
560
+ const cross = randomInt(random, 1, 20);
561
+ const range = isRow
562
+ ? {
563
+ endColumnIndex: cross + 1,
564
+ endRowIndex: end,
565
+ startColumnIndex: cross,
566
+ startRowIndex: start,
567
+ }
568
+ : {
569
+ endColumnIndex: end,
570
+ endRowIndex: cross + 1,
571
+ startColumnIndex: start,
572
+ startRowIndex: cross,
573
+ };
574
+ const edit = { index, operation };
575
+ const reference = getSheetStructureRangeReferenceAfterEdit(range, edit);
576
+ const named = getSheetNamedRangeAfterStructureEdit({ ...range, name: 'n' } as SheetNamedRangeObj, edit);
577
+
578
+ expect(reference ? { ...reference.range, name: 'n' } : null).toEqual(named ? { ...named, name: 'n' } : null);
579
+
580
+ // Merges share the interval math below the cap (they also drop 1x1)
581
+ if (end < max && reference) {
582
+ const [merge] = shiftSheetMergedRangesForStructureEdit([range], operation, index);
583
+ if (merge) {
584
+ expect(reference.range).toEqual(merge);
585
+ }
586
+ }
587
+ }
588
+ });
589
+ });
@@ -0,0 +1,60 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import type { WorkflowData } from '../src/types/workflow.d.ts';
3
+ import { getWorkflowLifecycleStatus } from '../src/utils/workflow.ts';
4
+
5
+ /*
6
+ * Build a reminder row with only the fields getWorkflowLifecycleStatus reads.
7
+ */
8
+ function makeReminder(
9
+ overrides: Partial<Pick<WorkflowData, 'active' | 'nextAt' | 'values'>> = {},
10
+ ) {
11
+ return {
12
+ kind: 'REMINDER' as const,
13
+ active: true,
14
+ logTypes: null,
15
+ fieldDocId: null,
16
+ nextAt: null,
17
+ values: {},
18
+ ...overrides,
19
+ };
20
+ }
21
+
22
+ describe('reminder lifecycle status after a terminal transition', () => {
23
+ const reminderEnd = (outcome: 'COMPLETED' | 'CANCELED') => ({
24
+ outcome,
25
+ at: '2026-10-30T20:21:00.000Z',
26
+ by: { kind: 'INBOUND_REPLY' as const, workflowRunId: '3580', waitId: '47' },
27
+ });
28
+
29
+ it('reports COMPLETED for an inactive reminder whose terminal record is COMPLETED, without a latest run', () => {
30
+ const reminder = makeReminder({
31
+ active: false,
32
+ values: { reminderEnd: reminderEnd('COMPLETED') },
33
+ });
34
+ expect(getWorkflowLifecycleStatus(reminder)).toBe('COMPLETED');
35
+ expect(getWorkflowLifecycleStatus(reminder, null)).toBe('COMPLETED');
36
+ });
37
+
38
+ it('reports INACTIVE for canceled, paused and legacy inactive reminders', () => {
39
+ expect(
40
+ getWorkflowLifecycleStatus(
41
+ makeReminder({
42
+ active: false,
43
+ values: { reminderEnd: reminderEnd('CANCELED') },
44
+ }),
45
+ ),
46
+ ).toBe('INACTIVE');
47
+ expect(getWorkflowLifecycleStatus(makeReminder({ active: false }))).toBe(
48
+ 'INACTIVE',
49
+ );
50
+ });
51
+
52
+ it('ignores a stale COMPLETED record once the reminder is active again', () => {
53
+ const reactivated = makeReminder({
54
+ active: true,
55
+ nextAt: new Date('2026-11-01T17:00:00.000Z'),
56
+ values: { reminderEnd: reminderEnd('COMPLETED') },
57
+ });
58
+ expect(getWorkflowLifecycleStatus(reactivated)).toBe('SCHEDULED');
59
+ });
60
+ });