@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,444 @@
1
+ import type { DateTime } from 'luxon';
2
+ import {
3
+ flattenSheetFormulaArgValues,
4
+ getSheetFormulaDateArg,
5
+ getSheetFormulaIntegerArg,
6
+ getSheetFormulaTextArg,
7
+ type SheetFormulaArgResult,
8
+ } from './sheetFormulaArgs.ts';
9
+ import {
10
+ formatSheetFormulaDateValue,
11
+ getSheetFormulaPureErrorResult,
12
+ isSheetFormulaBlankValue,
13
+ type SheetFormulaPureEvaluationResult,
14
+ } from './sheetFormulaEvaluation.ts';
15
+ import { getSheetDateTimeFromSerial, getSheetSerialFromDateTime } from './sheetNumberFormat.ts';
16
+
17
+ /**
18
+ * Types
19
+ */
20
+
21
+ /* Sorted, deduplicated weekday holiday serials for NETWORKDAYS/WORKDAY. */
22
+ type SheetFormulaHolidaySerials = number[];
23
+
24
+ const FILE_CONSTANTS = {
25
+ // ISO date text needs a four-digit year
26
+ maxYear: 9999,
27
+ minYear: 1,
28
+ // Beyond these offsets every result falls outside years 1-9999
29
+ maxMonthOffset: 120_000,
30
+ maxWorkdayOffset: 3_000_000,
31
+ weekdayTypes: new Set([1, 2, 3, 11, 12, 13, 14, 15, 16, 17]),
32
+ weekNumberTypes: new Set([1, 2, 11, 12, 13, 14, 15, 16, 17, 21]),
33
+ dateDifferenceUnits: new Set(['D', 'M', 'Y', 'MD', 'YM', 'YD']),
34
+ };
35
+
36
+ /*
37
+ * Return the INVALID_NUMBER (#NUM!) result for one date function.
38
+ */
39
+ function getSheetFormulaDateNumberError(message: string) {
40
+ return getSheetFormulaPureErrorResult('INVALID_NUMBER', message);
41
+ }
42
+
43
+ /*
44
+ * Return one date result as yyyy-MM-dd, or INVALID_NUMBER when it falls
45
+ * outside years 1-9999.
46
+ */
47
+ function getSheetFormulaDateResult(name: string, dateTime: DateTime): SheetFormulaPureEvaluationResult {
48
+ return dateTime.isValid && dateTime.year >= FILE_CONSTANTS.minYear && dateTime.year <= FILE_CONSTANTS.maxYear
49
+ ? { value: formatSheetFormulaDateValue(dateTime) }
50
+ : getSheetFormulaDateNumberError(`${name} result is outside the supported date range.`);
51
+ }
52
+
53
+ /*
54
+ * Return the whole-day serial of one calendar date (days since 1899-12-30).
55
+ */
56
+ function getSheetFormulaDaySerial(dateTime: DateTime) {
57
+ return Math.round(getSheetSerialFromDateTime(dateTime.startOf('day')));
58
+ }
59
+
60
+ /*
61
+ * Return the ISO weekday (1 = Monday ... 7 = Sunday) of one day serial.
62
+ * Serial 0 (1899-12-30) was a Saturday.
63
+ */
64
+ function getSheetFormulaSerialWeekday(serial: number) {
65
+ return ((((serial + 5) % 7) + 7) % 7) + 1;
66
+ }
67
+
68
+ /*
69
+ * Return whether one day serial falls on Monday through Friday.
70
+ */
71
+ function isSheetFormulaWorkdaySerial(serial: number) {
72
+ return getSheetFormulaSerialWeekday(serial) <= 5;
73
+ }
74
+
75
+ /*
76
+ * Return the two date arguments of a date-pair builtin, stopping at the first
77
+ * invalid one.
78
+ */
79
+ function getSheetFormulaDatePairArgs(
80
+ name: string,
81
+ values: unknown[],
82
+ labels: [string, string],
83
+ timeZone: string,
84
+ ): SheetFormulaArgResult<[DateTime, DateTime]> {
85
+ const first = getSheetFormulaDateArg(name, values[0], labels[0], timeZone);
86
+ if (!first.ok) {
87
+ return first;
88
+ }
89
+
90
+ const second = getSheetFormulaDateArg(name, values[1], labels[1], timeZone);
91
+ return second.ok ? { ok: true, value: [first.value, second.value] } : second;
92
+ }
93
+
94
+ /*
95
+ * Return the months argument of EDATE/EOMONTH (truncated to a whole number).
96
+ */
97
+ function getSheetFormulaMonthOffsetArg(name: string, value: unknown) {
98
+ const months = getSheetFormulaIntegerArg(name, value, 'months');
99
+ return months.ok && Math.abs(months.value) > FILE_CONSTANTS.maxMonthOffset
100
+ ? {
101
+ ok: false as const,
102
+ result: getSheetFormulaDateNumberError(`${name} result is outside the supported date range.`),
103
+ }
104
+ : months;
105
+ }
106
+
107
+ /*
108
+ * Evaluate EDATE(start_date, months) or EOMONTH(start_date, months): the date
109
+ * the given number of months away (clamped to the month's last day, so
110
+ * EDATE("2026-01-31", 1) is 2026-02-28), or that month's last day for EOMONTH.
111
+ */
112
+ export function evaluateSheetFormulaMonthShiftFunction(
113
+ name: 'EDATE' | 'EOMONTH',
114
+ values: unknown[],
115
+ timeZone: string,
116
+ ): SheetFormulaPureEvaluationResult {
117
+ const start = getSheetFormulaDateArg(name, values[0], 'start_date', timeZone);
118
+ if (!start.ok) {
119
+ return start.result;
120
+ }
121
+
122
+ const months = getSheetFormulaMonthOffsetArg(name, values[1]);
123
+ if (!months.ok) {
124
+ return months.result;
125
+ }
126
+
127
+ const shifted = start.value.plus({ months: months.value });
128
+ return getSheetFormulaDateResult(name, name === 'EOMONTH' ? shifted.endOf('month') : shifted);
129
+ }
130
+
131
+ /*
132
+ * Return the optional numeric type argument of WEEKDAY/WEEKNUM when it is one
133
+ * of the supported types, otherwise INVALID_NUMBER.
134
+ */
135
+ function getSheetFormulaWeekTypeArg(name: string, values: unknown[], supported: Set<number>): SheetFormulaArgResult<number> {
136
+ if (values.length < 2) {
137
+ return { ok: true, value: 1 };
138
+ }
139
+
140
+ const type = getSheetFormulaIntegerArg(name, values[1], 'type');
141
+ if (!type.ok || supported.has(type.value)) {
142
+ return type;
143
+ }
144
+
145
+ return {
146
+ ok: false,
147
+ result: getSheetFormulaDateNumberError(`${name} type ${type.value} is not supported.`),
148
+ };
149
+ }
150
+
151
+ /*
152
+ * Return the ISO weekday (1 = Monday ... 7 = Sunday) a WEEKDAY/WEEKNUM type
153
+ * starts its week on: 1 and 17 Sunday, 2 and 11 Monday, 12-16 Tuesday to
154
+ * Saturday.
155
+ */
156
+ function getSheetFormulaWeekStartDay(type: number) {
157
+ if (type === 1 || type === 17) {
158
+ return 7;
159
+ }
160
+
161
+ return type === 2 || type === 3 ? 1 : type - 10;
162
+ }
163
+
164
+ /*
165
+ * Evaluate WEEKDAY(date, [type=1]): the day of the week as a number. Type 1
166
+ * counts Sunday = 1 to Saturday = 7, type 2 Monday = 1 to Sunday = 7, type 3
167
+ * Monday = 0 to Sunday = 6, and types 11-17 start the count on Monday to
168
+ * Sunday.
169
+ */
170
+ export function evaluateSheetFormulaWeekdayFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
171
+ const date = getSheetFormulaDateArg('WEEKDAY', values[0], 'date', timeZone);
172
+ if (!date.ok) {
173
+ return date.result;
174
+ }
175
+
176
+ const type = getSheetFormulaWeekTypeArg('WEEKDAY', values, FILE_CONSTANTS.weekdayTypes);
177
+ if (!type.ok) {
178
+ return type.result;
179
+ }
180
+
181
+ const startDay = getSheetFormulaWeekStartDay(type.value);
182
+ const dayNumber = ((date.value.weekday - startDay + 7) % 7) + 1;
183
+ return { value: type.value === 3 ? dayNumber - 1 : dayNumber };
184
+ }
185
+
186
+ /*
187
+ * Evaluate WEEKNUM(date, [type=1]): the week of the year. Types 1, 2 and
188
+ * 11-17 use Excel system 1 (the week containing January 1 is week 1, weeks
189
+ * starting on the type's day); type 21 is the ISO 8601 week number.
190
+ */
191
+ export function evaluateSheetFormulaWeekNumberFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
192
+ const date = getSheetFormulaDateArg('WEEKNUM', values[0], 'date', timeZone);
193
+ if (!date.ok) {
194
+ return date.result;
195
+ }
196
+
197
+ const type = getSheetFormulaWeekTypeArg('WEEKNUM', values, FILE_CONSTANTS.weekNumberTypes);
198
+ if (!type.ok) {
199
+ return type.result;
200
+ }
201
+
202
+ if (type.value === 21) {
203
+ return { value: date.value.weekNumber };
204
+ }
205
+
206
+ const startDay = getSheetFormulaWeekStartDay(type.value);
207
+ const januaryFirstOffset = (date.value.startOf('year').weekday - startDay + 7) % 7;
208
+ return {
209
+ value: Math.floor((date.value.ordinal - 1 + januaryFirstOffset) / 7) + 1,
210
+ };
211
+ }
212
+
213
+ /*
214
+ * Evaluate DAYS(end_date, start_date): the number of calendar days from the
215
+ * start date to the end date (negative when the end is earlier).
216
+ */
217
+ export function evaluateSheetFormulaDaysFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
218
+ const dates = getSheetFormulaDatePairArgs('DAYS', values, ['end_date', 'start_date'], timeZone);
219
+ if (!dates.ok) {
220
+ return dates.result;
221
+ }
222
+
223
+ const [end, start] = dates.value;
224
+ return {
225
+ value: getSheetFormulaDaySerial(end) - getSheetFormulaDaySerial(start),
226
+ };
227
+ }
228
+
229
+ /*
230
+ * Return the number of whole months from start to end (a month counts once
231
+ * its day of month is reached).
232
+ */
233
+ function getSheetFormulaWholeMonthCount(start: DateTime, end: DateTime) {
234
+ const months = (end.year - start.year) * 12 + (end.month - start.month);
235
+ return end.day < start.day ? months - 1 : months;
236
+ }
237
+
238
+ /*
239
+ * Evaluate DATEDIF(start_date, end_date, unit): whole years (Y), months (M)
240
+ * or days (D) between two dates, or the remainder days after whole months
241
+ * (MD), months after whole years (YM) or days after whole years (YD). MD and
242
+ * YD count days from the start date moved forward by the whole months or
243
+ * years (month ends clamp), not Excel's inconsistent MD. start_date after
244
+ * end_date, or another unit, is INVALID_NUMBER.
245
+ */
246
+ export function evaluateSheetFormulaDateDifferenceFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
247
+ const dates = getSheetFormulaDatePairArgs('DATEDIF', values, ['start_date', 'end_date'], timeZone);
248
+ if (!dates.ok) {
249
+ return dates.result;
250
+ }
251
+
252
+ const unitArg = getSheetFormulaTextArg('DATEDIF', values[2], 'unit');
253
+ if (!unitArg.ok) {
254
+ return unitArg.result;
255
+ }
256
+
257
+ const unit = unitArg.value.trim().toUpperCase();
258
+ const [start, end] = dates.value;
259
+ const days = getSheetFormulaDaySerial(end) - getSheetFormulaDaySerial(start);
260
+ if (days < 0 || !FILE_CONSTANTS.dateDifferenceUnits.has(unit)) {
261
+ return getSheetFormulaDateNumberError(
262
+ days < 0 ? 'DATEDIF start_date must not be after end_date.' : 'DATEDIF unit must be Y, M, D, MD, YM or YD.',
263
+ );
264
+ }
265
+
266
+ const months = getSheetFormulaWholeMonthCount(start, end);
267
+ switch (unit) {
268
+ case 'D':
269
+ return { value: days };
270
+ case 'M':
271
+ return { value: months };
272
+ case 'Y':
273
+ return { value: Math.floor(months / 12) };
274
+ case 'YM':
275
+ return { value: months % 12 };
276
+ case 'MD':
277
+ return {
278
+ value: getSheetFormulaDaySerial(end) - getSheetFormulaDaySerial(start.plus({ months })),
279
+ };
280
+ default:
281
+ return {
282
+ value: getSheetFormulaDaySerial(end) - getSheetFormulaDaySerial(start.plus({ years: Math.floor(months / 12) })),
283
+ };
284
+ }
285
+ }
286
+
287
+ /*
288
+ * Return the sorted, deduplicated weekday serials of a holidays argument
289
+ * (one ISO date, or a range/array of them; blanks skipped, weekend dates
290
+ * dropped because they never count).
291
+ */
292
+ function getSheetFormulaHolidaySerials(
293
+ name: string,
294
+ value: unknown,
295
+ timeZone: string,
296
+ ): SheetFormulaArgResult<SheetFormulaHolidaySerials> {
297
+ const serials = new Set<number>();
298
+ for (const entry of flattenSheetFormulaArgValues([value])) {
299
+ if (isSheetFormulaBlankValue(entry)) {
300
+ continue;
301
+ }
302
+
303
+ const holiday = getSheetFormulaDateArg(name, entry, 'holidays', timeZone);
304
+ if (!holiday.ok) {
305
+ return holiday;
306
+ }
307
+
308
+ const serial = getSheetFormulaDaySerial(holiday.value);
309
+ if (isSheetFormulaWorkdaySerial(serial)) {
310
+ serials.add(serial);
311
+ }
312
+ }
313
+
314
+ return { ok: true, value: [...serials].sort((a, b) => a - b) };
315
+ }
316
+
317
+ /*
318
+ * Return the index of the first sorted serial that is >= the target (binary
319
+ * search).
320
+ */
321
+ function getSheetFormulaSerialLowerBound(serials: SheetFormulaHolidaySerials, target: number) {
322
+ let low = 0;
323
+ let high = serials.length;
324
+ while (low < high) {
325
+ const middle = (low + high) >>> 1;
326
+ if (serials[middle] < target) {
327
+ low = middle + 1;
328
+ } else {
329
+ high = middle;
330
+ }
331
+ }
332
+
333
+ return low;
334
+ }
335
+
336
+ /*
337
+ * Return how many sorted holiday serials fall in the inclusive range.
338
+ */
339
+ function countSheetFormulaHolidaysBetween(holidays: SheetFormulaHolidaySerials, low: number, high: number) {
340
+ return getSheetFormulaSerialLowerBound(holidays, high + 1) - getSheetFormulaSerialLowerBound(holidays, low);
341
+ }
342
+
343
+ /*
344
+ * Return the number of Monday-Friday days in an inclusive serial range,
345
+ * computed per whole week instead of day by day.
346
+ */
347
+ function countSheetFormulaWeekdaysBetween(low: number, high: number) {
348
+ const total = high - low + 1;
349
+ const wholeWeeks = Math.floor(total / 7);
350
+ let count = wholeWeeks * 5;
351
+ for (let serial = low + wholeWeeks * 7; serial <= high; serial++) {
352
+ if (isSheetFormulaWorkdaySerial(serial)) {
353
+ count++;
354
+ }
355
+ }
356
+
357
+ return count;
358
+ }
359
+
360
+ /*
361
+ * Evaluate NETWORKDAYS(start_date, end_date, [holidays]): the Monday-Friday
362
+ * days from start to end inclusive, minus holidays; negative when end_date
363
+ * is before start_date.
364
+ */
365
+ export function evaluateSheetFormulaNetworkDaysFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
366
+ const dates = getSheetFormulaDatePairArgs('NETWORKDAYS', values, ['start_date', 'end_date'], timeZone);
367
+ if (!dates.ok) {
368
+ return dates.result;
369
+ }
370
+
371
+ const holidays = getSheetFormulaHolidaySerials('NETWORKDAYS', values.length > 2 ? values[2] : null, timeZone);
372
+ if (!holidays.ok) {
373
+ return holidays.result;
374
+ }
375
+
376
+ const start = getSheetFormulaDaySerial(dates.value[0]);
377
+ const end = getSheetFormulaDaySerial(dates.value[1]);
378
+ const low = Math.min(start, end);
379
+ const high = Math.max(start, end);
380
+ const count = countSheetFormulaWeekdaysBetween(low, high) - countSheetFormulaHolidaysBetween(holidays.value, low, high);
381
+ return { value: end < start ? -count : count };
382
+ }
383
+
384
+ /*
385
+ * Return the serial of the nth Monday-Friday day after (direction 1) or
386
+ * before (direction -1) one serial, ignoring holidays. Jumps whole weeks, so
387
+ * the cost does not grow with n.
388
+ */
389
+ function addSheetFormulaWeekdays(serial: number, count: number, direction: 1 | -1) {
390
+ if (count <= 0) {
391
+ return serial;
392
+ }
393
+
394
+ const wholeWeeks = Math.floor((count - 1) / 5);
395
+ let current = serial + direction * wholeWeeks * 7;
396
+ let remaining = count - wholeWeeks * 5;
397
+ while (remaining > 0) {
398
+ current += direction;
399
+ if (isSheetFormulaWorkdaySerial(current)) {
400
+ remaining--;
401
+ }
402
+ }
403
+
404
+ return current;
405
+ }
406
+
407
+ /*
408
+ * Evaluate WORKDAY(start_date, days, [holidays]): the date that many
409
+ * Monday-Friday days after (or, for negative days, before) the start date,
410
+ * skipping holidays. The start date itself never counts.
411
+ */
412
+ export function evaluateSheetFormulaWorkdayFunction(values: unknown[], timeZone: string): SheetFormulaPureEvaluationResult {
413
+ const start = getSheetFormulaDateArg('WORKDAY', values[0], 'start_date', timeZone);
414
+ if (!start.ok) {
415
+ return start.result;
416
+ }
417
+
418
+ const days = getSheetFormulaIntegerArg('WORKDAY', values[1], 'num_days');
419
+ if (!days.ok) {
420
+ return days.result;
421
+ }
422
+
423
+ if (Math.abs(days.value) > FILE_CONSTANTS.maxWorkdayOffset) {
424
+ return getSheetFormulaDateNumberError('WORKDAY result is outside the supported date range.');
425
+ }
426
+
427
+ const holidays = getSheetFormulaHolidaySerials('WORKDAY', values.length > 2 ? values[2] : null, timeZone);
428
+ if (!holidays.ok) {
429
+ return holidays.result;
430
+ }
431
+
432
+ const direction = days.value < 0 ? -1 : 1;
433
+ let from = getSheetFormulaDaySerial(start.value);
434
+ let pending = Math.abs(days.value);
435
+ // Each pass skips the holidays inside the span it just covered, so the
436
+ // loop runs at most once per holiday
437
+ while (pending > 0) {
438
+ const to = addSheetFormulaWeekdays(from, pending, direction);
439
+ pending = countSheetFormulaHolidaysBetween(holidays.value, Math.min(from + direction, to), Math.max(from + direction, to));
440
+ from = to;
441
+ }
442
+
443
+ return getSheetFormulaDateResult('WORKDAY', getSheetDateTimeFromSerial(from));
444
+ }