@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,447 @@
1
+ /*
2
+ * Relative date filter values for agent data-table queries. A value
3
+ * { relative: { unit, offset, boundary } } is the START or END of the unit
4
+ * period that contains the organization-local today, shifted by offset units
5
+ * (ISO weeks start on Monday; on a Sunday-start week column, weeks start on
6
+ * Sunday so they match its stored week starts). Resolution is a pure
7
+ * function of one { timeZone, today } context, so every filter of one query
8
+ * (and every page bound to it) resolves against the same day.
9
+ *
10
+ * Data tables v2 (dt_* store) query specs use named windows instead
11
+ * ({ rel: TODAY | LAST_N_DAYS | CURRENT_* | PREVIOUS_*, n? }); they resolve to
12
+ * whole local days through the same period arithmetic.
13
+ */
14
+
15
+ import { DateTime } from 'luxon';
16
+ import {
17
+ DATA_TABLE_RELATIVE_DATE_BOUNDARY_ENUMS,
18
+ DATA_TABLE_RELATIVE_DATE_MAX_OFFSET,
19
+ DATA_TABLE_RELATIVE_DATE_OPERATOR_ENUMS,
20
+ DATA_TABLE_RELATIVE_DATE_UNIT_ENUMS,
21
+ } from '../constants/dataTable.ts';
22
+ import { DT_RELATIVE_DATE_ENUMS } from '../constants/dt.ts';
23
+ import type {
24
+ DataTableFieldTypeEnum,
25
+ DataTableRelativeDateBoundaryEnum,
26
+ DataTableRelativeDateContextObj,
27
+ DataTableRelativeDateObj,
28
+ DataTableRelativeDateOperatorEnum,
29
+ DataTableRelativeDateResolvedObj,
30
+ DataTableRelativeDateUnitEnum,
31
+ } from '../types/dataTable.d.ts';
32
+ import type { DtRelativeDate, DtRelativeDateEnum } from '../types/dt.d.ts';
33
+
34
+ type DataTableRelativeDateParseResult =
35
+ | { token: DataTableRelativeDateObj; error: null }
36
+ | { token: null; error: string };
37
+
38
+ type DtRelativeDateParseResult =
39
+ | { value: DtRelativeDate; error: null }
40
+ | { value: null; error: string };
41
+
42
+ /*
43
+ * The local days a v2 relative date window covers: "start" and "end" are
44
+ * inclusive YYYY-MM-DD days for date columns; "startAt" is the first instant
45
+ * of "start" and "endAt" the last microsecond of "end" (inclusive), both with
46
+ * the zone offset in force at that instant, for datetime columns.
47
+ */
48
+ export interface DtRelativeDateRange {
49
+ start: string;
50
+ end: string;
51
+ startAt: string;
52
+ endAt: string;
53
+ }
54
+
55
+ const FILE_CONSTANTS = {
56
+ tokenKeys: ['unit', 'offset', 'boundary'],
57
+ // Luxon period name of each unit (its duration key is the plural)
58
+ luxonUnits: {
59
+ DAY: 'day',
60
+ WEEK: 'week',
61
+ MONTH: 'month',
62
+ QUARTER: 'quarter',
63
+ YEAR: 'year',
64
+ } as const,
65
+ isoDatePattern: /^\d{4}-\d{2}-\d{2}$/,
66
+ // Luxon zone names that mean the host zone
67
+ hostZoneAliases: ['default', 'local', 'system'],
68
+ // Fractional seconds of a boundary instant: START is the period's first
69
+ // instant; END is its last microsecond (timestamptz precision), so an
70
+ // "on or before END" comparison covers every stored instant of the period
71
+ startFraction: '000',
72
+ endFraction: '999999',
73
+ minYear: 1,
74
+ maxYear: 9999,
75
+ dtRelativeDateKeys: ['rel', 'n'],
76
+ // Period unit of each v2 window, and how many units back it starts
77
+ dtWindows: {
78
+ TODAY: { unit: 'DAY', offset: 0 },
79
+ LAST_N_DAYS: { unit: 'DAY', offset: 0 },
80
+ CURRENT_WEEK: { unit: 'WEEK', offset: 0 },
81
+ CURRENT_MONTH: { unit: 'MONTH', offset: 0 },
82
+ CURRENT_YEAR: { unit: 'YEAR', offset: 0 },
83
+ PREVIOUS_WEEK: { unit: 'WEEK', offset: -1 },
84
+ PREVIOUS_MONTH: { unit: 'MONTH', offset: -1 },
85
+ PREVIOUS_YEAR: { unit: 'YEAR', offset: -1 },
86
+ } as Record<
87
+ DtRelativeDateEnum,
88
+ { unit: DataTableRelativeDateUnitEnum; offset: number }
89
+ >,
90
+ };
91
+
92
+ /*
93
+ * Return whether a value is a plain object (not null and not an array).
94
+ */
95
+ function isDataTableRelativeDatePlainObject(
96
+ value: unknown,
97
+ ): value is Record<string, unknown> {
98
+ return !!value && typeof value === 'object' && !Array.isArray(value);
99
+ }
100
+
101
+ /*
102
+ * Return whether a filter value has the shape of a relative date (an object
103
+ * with an own "relative" key). This only detects the shape; use
104
+ * parseDataTableRelativeDateFilterValue to validate it.
105
+ */
106
+ export function isDataTableRelativeDateFilterValue(
107
+ value: unknown,
108
+ ): value is { relative: unknown } {
109
+ return (
110
+ isDataTableRelativeDatePlainObject(value) &&
111
+ Object.hasOwn(value, 'relative')
112
+ );
113
+ }
114
+
115
+ /*
116
+ * Return whether a filter operator accepts a relative date value.
117
+ */
118
+ export function isDataTableRelativeDateOperator(
119
+ operator: unknown,
120
+ ): operator is DataTableRelativeDateOperatorEnum {
121
+ return (
122
+ DATA_TABLE_RELATIVE_DATE_OPERATOR_ENUMS as readonly unknown[]
123
+ ).includes(operator);
124
+ }
125
+
126
+ /*
127
+ * Validate one relative date filter value: exactly
128
+ * { relative: { unit, offset, boundary } } with a known unit and boundary and
129
+ * an integer offset within the maximum. Errors are model-facing text.
130
+ */
131
+ export function parseDataTableRelativeDateFilterValue(
132
+ value: unknown,
133
+ ): DataTableRelativeDateParseResult {
134
+ const maximum = DATA_TABLE_RELATIVE_DATE_MAX_OFFSET;
135
+ const relative =
136
+ isDataTableRelativeDatePlainObject(value) && Object.keys(value).length === 1
137
+ ? value.relative
138
+ : undefined;
139
+ if (
140
+ !isDataTableRelativeDatePlainObject(relative) ||
141
+ Object.keys(relative).some((key) => !FILE_CONSTANTS.tokenKeys.includes(key))
142
+ ) {
143
+ return {
144
+ token: null,
145
+ error:
146
+ 'A relative date must be exactly { relative: { unit, offset, boundary } }.',
147
+ };
148
+ }
149
+
150
+ const { unit, offset, boundary } = relative;
151
+ if (
152
+ !(DATA_TABLE_RELATIVE_DATE_UNIT_ENUMS as readonly unknown[]).includes(unit)
153
+ ) {
154
+ return {
155
+ token: null,
156
+ error: `relative.unit must be one of ${DATA_TABLE_RELATIVE_DATE_UNIT_ENUMS.join(', ')}.`,
157
+ };
158
+ }
159
+
160
+ if (
161
+ typeof offset !== 'number' ||
162
+ !Number.isInteger(offset) ||
163
+ Math.abs(offset) > maximum
164
+ ) {
165
+ return {
166
+ token: null,
167
+ error: `relative.offset must be an integer from -${maximum} to ${maximum}.`,
168
+ };
169
+ }
170
+
171
+ if (
172
+ !(DATA_TABLE_RELATIVE_DATE_BOUNDARY_ENUMS as readonly unknown[]).includes(
173
+ boundary,
174
+ )
175
+ ) {
176
+ return { token: null, error: 'relative.boundary must be START or END.' };
177
+ }
178
+
179
+ return {
180
+ token: {
181
+ unit: unit as DataTableRelativeDateUnitEnum,
182
+ // -0 is stored and printed as 0
183
+ offset: offset || 0,
184
+ boundary: boundary as DataTableRelativeDateBoundaryEnum,
185
+ },
186
+ error: null,
187
+ };
188
+ }
189
+
190
+ /*
191
+ * Return whether a time zone is one the organization settings accept (the
192
+ * same Luxon rule as isValidTimeZone). Empty names and the host-zone aliases
193
+ * are rejected, so a resolution never silently uses the server's zone.
194
+ */
195
+ function isDataTableRelativeDateTimeZone(
196
+ timeZone: unknown,
197
+ ): timeZone is string {
198
+ return (
199
+ typeof timeZone === 'string' &&
200
+ !!timeZone.trim() &&
201
+ !FILE_CONSTANTS.hostZoneAliases.includes(timeZone.trim().toLowerCase()) &&
202
+ DateTime.now().setZone(timeZone).isValid
203
+ );
204
+ }
205
+
206
+ /*
207
+ * Return the context one query resolves its relative dates against: the time
208
+ * zone and the local date of one instant there; null for an invalid zone or
209
+ * instant.
210
+ */
211
+ export function getDataTableRelativeDateContext(
212
+ now: Date,
213
+ timeZone: string,
214
+ ): DataTableRelativeDateContextObj | null {
215
+ if (!isDataTableRelativeDateTimeZone(timeZone)) {
216
+ return null;
217
+ }
218
+
219
+ const local = DateTime.fromJSDate(now, { zone: timeZone });
220
+ const today = local.isValid ? local.toISODate() : null;
221
+ return today ? { timeZone, today } : null;
222
+ }
223
+
224
+ /*
225
+ * Return the start of the context's local today, or null when the context is
226
+ * not a valid zone plus a real YYYY-MM-DD date.
227
+ */
228
+ function getDataTableRelativeDateContextDay(
229
+ context: DataTableRelativeDateContextObj | null | undefined,
230
+ ) {
231
+ if (
232
+ !context ||
233
+ typeof context.today !== 'string' ||
234
+ !FILE_CONSTANTS.isoDatePattern.test(context.today) ||
235
+ !isDataTableRelativeDateTimeZone(context.timeZone)
236
+ ) {
237
+ return null;
238
+ }
239
+
240
+ const today = DateTime.fromISO(context.today, { zone: context.timeZone });
241
+ return today.isValid && today.toISODate() === context.today
242
+ ? today.startOf('day')
243
+ : null;
244
+ }
245
+
246
+ /*
247
+ * Format one boundary as an ISO instant with its zone offset and the given
248
+ * fractional seconds.
249
+ */
250
+ function formatDataTableRelativeDateInstant(
251
+ dateTime: DateTime,
252
+ fraction: string,
253
+ ) {
254
+ return `${dateTime.toFormat("yyyy-MM-dd'T'HH:mm:ss")}.${fraction}${dateTime.toFormat('ZZ')}`;
255
+ }
256
+
257
+ /*
258
+ * Resolve one relative date against a context: the START or END of the unit
259
+ * period containing the context's today, shifted by offset units. Returns the
260
+ * boundary day (YYYY-MM-DD) for date columns and the boundary instant for
261
+ * datetime columns, or null for an invalid context or a year outside
262
+ * 1..9999. With weekStartsOnSunday, WEEK periods run Sunday to Saturday.
263
+ */
264
+ export function resolveDataTableRelativeDate(
265
+ token: DataTableRelativeDateObj,
266
+ context: DataTableRelativeDateContextObj | null | undefined,
267
+ options: { weekStartsOnSunday?: boolean } = {},
268
+ ): DataTableRelativeDateResolvedObj | null {
269
+ const today = getDataTableRelativeDateContextDay(context);
270
+ const unit = FILE_CONSTANTS.luxonUnits[token.unit];
271
+ if (!today || !unit) {
272
+ return null;
273
+ }
274
+
275
+ // The Sunday-start week holding a day is the ISO week holding the next
276
+ // day, one day earlier
277
+ const sundayWeek =
278
+ token.unit === 'WEEK' && options.weekStartsOnSunday === true;
279
+ const anchor = sundayWeek ? today.plus({ days: 1 }) : today;
280
+ // Calendar arithmetic in the zone; the second startOf restores midnight
281
+ // after a shift away from a day whose midnight a DST change skipped
282
+ const start = anchor
283
+ .startOf(unit)
284
+ .plus({ [`${unit}s`]: token.offset })
285
+ .startOf(unit);
286
+ const isoBoundary = token.boundary === 'END' ? start.endOf(unit) : start;
287
+ const boundary = sundayWeek ? isoBoundary.minus({ days: 1 }) : isoBoundary;
288
+ const date = boundary.isValid ? boundary.toISODate() : null;
289
+ if (
290
+ !date ||
291
+ boundary.year < FILE_CONSTANTS.minYear ||
292
+ boundary.year > FILE_CONSTANTS.maxYear
293
+ ) {
294
+ return null;
295
+ }
296
+
297
+ return {
298
+ date,
299
+ instant: formatDataTableRelativeDateInstant(
300
+ boundary,
301
+ token.boundary === 'END'
302
+ ? FILE_CONSTANTS.endFraction
303
+ : FILE_CONSTANTS.startFraction,
304
+ ),
305
+ };
306
+ }
307
+
308
+ /*
309
+ * Resolve one relative date for the column it filters: a Sunday-start week
310
+ * column stores each week by its Sunday, so its WEEK periods start on Sunday
311
+ * (every other column uses ISO Monday weeks).
312
+ */
313
+ export function resolveDataTableRelativeDateForFieldType(
314
+ token: DataTableRelativeDateObj,
315
+ fieldType: DataTableFieldTypeEnum | null | undefined,
316
+ context: DataTableRelativeDateContextObj | null | undefined,
317
+ ): DataTableRelativeDateResolvedObj | null {
318
+ return resolveDataTableRelativeDate(token, context, {
319
+ weekStartsOnSunday: fieldType === 'WEEK_OF_SUN',
320
+ });
321
+ }
322
+
323
+ /*
324
+ * Return whether a v2 query condition value has the shape of a relative date
325
+ * window (an object with an own "rel" key). This only detects the shape; use
326
+ * parseDtRelativeDate to validate it.
327
+ */
328
+ export function isDtRelativeDateValue(
329
+ value: unknown,
330
+ ): value is { rel: unknown } {
331
+ return (
332
+ isDataTableRelativeDatePlainObject(value) && Object.hasOwn(value, 'rel')
333
+ );
334
+ }
335
+
336
+ /*
337
+ * Validate one v2 relative date window: exactly { rel } with a known window,
338
+ * plus an integer day count "n" (1 to the maximum offset) for LAST_N_DAYS
339
+ * only. Errors are model-facing text.
340
+ */
341
+ export function parseDtRelativeDate(value: unknown): DtRelativeDateParseResult {
342
+ const maximum = DATA_TABLE_RELATIVE_DATE_MAX_OFFSET;
343
+ if (
344
+ !isDataTableRelativeDatePlainObject(value) ||
345
+ Object.keys(value).some(
346
+ (key) => !FILE_CONSTANTS.dtRelativeDateKeys.includes(key),
347
+ )
348
+ ) {
349
+ return {
350
+ value: null,
351
+ error: 'A relative date must be exactly { rel } or { rel, n }.',
352
+ };
353
+ }
354
+
355
+ const { rel, n } = value;
356
+ if (!(DT_RELATIVE_DATE_ENUMS as readonly unknown[]).includes(rel)) {
357
+ return {
358
+ value: null,
359
+ error: `rel must be one of ${DT_RELATIVE_DATE_ENUMS.join(', ')}.`,
360
+ };
361
+ }
362
+
363
+ if (rel !== 'LAST_N_DAYS') {
364
+ return Object.hasOwn(value, 'n')
365
+ ? { value: null, error: 'n is allowed only with rel LAST_N_DAYS.' }
366
+ : { value: { rel: rel as DtRelativeDateEnum }, error: null };
367
+ }
368
+
369
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1 || n > maximum) {
370
+ return {
371
+ value: null,
372
+ error: `LAST_N_DAYS needs n, an integer day count from 1 to ${maximum}.`,
373
+ };
374
+ }
375
+
376
+ return { value: { rel: 'LAST_N_DAYS', n }, error: null };
377
+ }
378
+
379
+ /*
380
+ * Return the v2 window's first and last period tokens: LAST_N_DAYS covers
381
+ * today and the n - 1 days before it; CURRENT_* the whole period holding
382
+ * today; PREVIOUS_* the whole period before it. Null for an invalid window.
383
+ */
384
+ function getDtRelativeDateTokens(rel: DtRelativeDate) {
385
+ const parsed = parseDtRelativeDate(rel).value;
386
+ const window = parsed ? FILE_CONSTANTS.dtWindows[parsed.rel] : null;
387
+ if (!parsed || !window) {
388
+ return null;
389
+ }
390
+
391
+ const firstOffset =
392
+ parsed.rel === 'LAST_N_DAYS' ? 1 - (parsed.n as number) : window.offset;
393
+ return {
394
+ first: { unit: window.unit, offset: firstOffset, boundary: 'START' },
395
+ last: { unit: window.unit, offset: window.offset, boundary: 'END' },
396
+ // The window moves when the period holding today ends
397
+ next: { unit: window.unit, offset: 1, boundary: 'START' },
398
+ } satisfies Record<string, DataTableRelativeDateObj>;
399
+ }
400
+
401
+ /*
402
+ * Resolve a v2 relative date window in the organization time zone at one
403
+ * instant: its first and last local days and their bounding instants. Null
404
+ * for an invalid window, zone or instant. With weekStartsOnSunday (for a
405
+ * Sunday-start week column), week windows run Sunday to Saturday.
406
+ */
407
+ export function getDtRelativeDateRange(
408
+ rel: DtRelativeDate,
409
+ timeZone: string,
410
+ now: Date,
411
+ options: { weekStartsOnSunday?: boolean } = {},
412
+ ): DtRelativeDateRange | null {
413
+ const tokens = getDtRelativeDateTokens(rel);
414
+ const context = getDataTableRelativeDateContext(now, timeZone);
415
+ const first =
416
+ tokens && resolveDataTableRelativeDate(tokens.first, context, options);
417
+ const last =
418
+ tokens && resolveDataTableRelativeDate(tokens.last, context, options);
419
+ if (!first || !last) {
420
+ return null;
421
+ }
422
+
423
+ return {
424
+ start: first.date,
425
+ end: last.date,
426
+ startAt: first.instant,
427
+ endAt: last.instant,
428
+ };
429
+ }
430
+
431
+ /*
432
+ * Return the next instant at which a v2 relative date window moves: the
433
+ * first instant of the next day (TODAY, LAST_N_DAYS), week, month or year in
434
+ * the organization time zone. Null for an invalid window, zone or instant.
435
+ */
436
+ export function getDtRelativeDateNextBoundary(
437
+ rel: DtRelativeDate,
438
+ timeZone: string,
439
+ now: Date,
440
+ options: { weekStartsOnSunday?: boolean } = {},
441
+ ): Date | null {
442
+ const tokens = getDtRelativeDateTokens(rel);
443
+ const context = getDataTableRelativeDateContext(now, timeZone);
444
+ const next =
445
+ tokens && resolveDataTableRelativeDate(tokens.next, context, options);
446
+ return next ? new Date(next.instant) : null;
447
+ }
@@ -0,0 +1,84 @@
1
+ import type { DefinitionSectionWithElementsObj } from '../types/definitionElement.d.ts';
2
+
3
+ /*
4
+ * Build the ordered section tree from one definition's flat element rows.
5
+ * Rows without a parent become sections, and every other row is placed under
6
+ * its parent section. Sections and children are both sorted by "order".
7
+ */
8
+ export function buildDefinitionSections<ElementObj extends { id: number | bigint; parentId?: number | bigint | null; order: number }>(
9
+ elements: ElementObj[] | null | undefined,
10
+ ): DefinitionSectionWithElementsObj<ElementObj>[] {
11
+ if (!elements?.length) {
12
+ return [];
13
+ }
14
+
15
+ const childrenByParentId = new Map<string, ElementObj[]>();
16
+ const sections: ElementObj[] = [];
17
+
18
+ for (const element of elements) {
19
+ if (element.parentId == null) {
20
+ sections.push(element);
21
+ } else {
22
+ const parentIdKey = String(element.parentId);
23
+ const children = childrenByParentId.get(parentIdKey) || [];
24
+ children.push(element);
25
+ childrenByParentId.set(parentIdKey, children);
26
+ }
27
+ }
28
+
29
+ const sortByOrder = (left: ElementObj, right: ElementObj) => left.order - right.order;
30
+
31
+ return sections.sort(sortByOrder).map((section) => ({
32
+ ...section,
33
+ elements: (childrenByParentId.get(String(section.id)) || []).sort(sortByOrder),
34
+ }));
35
+ }
36
+
37
+ /*
38
+ * Attach definition elements onto their owner rows (fieldDocs or campaign
39
+ * templates) with one batched fetch. Owners that already hold elements are
40
+ * skipped, duplicate owner rows share one elements array, and owners without
41
+ * elements receive an empty array.
42
+ */
43
+ export async function attachDefinitionElements<
44
+ OwnerObj extends { id?: number | bigint | null; elements?: ElementObj[] | null } | null | undefined,
45
+ ElementObj,
46
+ >(
47
+ owners: OwnerObj[],
48
+ fetchElements: (ownerIds: bigint[]) => Promise<ElementObj[]>,
49
+ getElementOwnerId: (element: ElementObj) => number | bigint,
50
+ ): Promise<OwnerObj[]> {
51
+ const uniqueOwners = new Map<string, { elements?: ElementObj[] | null }[]>();
52
+
53
+ for (const owner of owners) {
54
+ if (owner?.id && !owner.elements) {
55
+ const ownerIdKey = String(owner.id);
56
+ const ownersForId = uniqueOwners.get(ownerIdKey) || [];
57
+ ownersForId.push(owner);
58
+ uniqueOwners.set(ownerIdKey, ownersForId);
59
+ }
60
+ }
61
+
62
+ if (!uniqueOwners.size) {
63
+ return owners;
64
+ }
65
+
66
+ const elements = await fetchElements([...uniqueOwners.keys()].map((ownerIdKey) => BigInt(ownerIdKey)));
67
+
68
+ const elementsByOwnerId = new Map<string, ElementObj[]>();
69
+ for (const element of elements) {
70
+ const ownerIdKey = String(getElementOwnerId(element));
71
+ const ownerElements = elementsByOwnerId.get(ownerIdKey) || [];
72
+ ownerElements.push(element);
73
+ elementsByOwnerId.set(ownerIdKey, ownerElements);
74
+ }
75
+
76
+ for (const [ownerIdKey, ownersForId] of uniqueOwners) {
77
+ const ownerElements = elementsByOwnerId.get(ownerIdKey) || [];
78
+ for (const owner of ownersForId) {
79
+ owner.elements = ownerElements;
80
+ }
81
+ }
82
+
83
+ return owners;
84
+ }