@jsb188/mday 1.1.10 → 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 +140 -54
  2. package/src/constants/agentMemory.ts +123 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +21 -21
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +125 -7
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/integration.ts +8 -9
  17. package/src/constants/log.ts +14 -408
  18. package/src/constants/logDisplay/README.md +88 -0
  19. package/src/constants/logDisplay/defaults.ts +39 -0
  20. package/src/constants/logDisplay/index.ts +27 -0
  21. package/src/constants/logDisplay/operations/arable.ts +16 -0
  22. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  23. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  24. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  25. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  26. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  27. package/src/constants/logTaxonomy.generated.ts +2207 -0
  28. package/src/constants/noteDoc.ts +77 -0
  29. package/src/constants/organization.ts +18 -21
  30. package/src/constants/pageRoute.ts +23 -0
  31. package/src/constants/qrCode.ts +30 -0
  32. package/src/constants/sheet.ts +126 -14
  33. package/src/constants/sms.ts +18 -0
  34. package/src/constants/square.ts +6 -6
  35. package/src/constants/storage.ts +80 -7
  36. package/src/constants/usage.ts +82 -0
  37. package/src/constants/workflowSteps.ts +60 -0
  38. package/src/schemas/editLogEntry.ts +836 -780
  39. package/src/schemas/inboundContact.ts +60 -55
  40. package/src/schemas/logsQuery.ts +55 -49
  41. package/src/types/account.d.ts +4 -1
  42. package/src/types/agentMemory.d.ts +98 -0
  43. package/src/types/agentNote.d.ts +443 -0
  44. package/src/types/billing.d.ts +537 -0
  45. package/src/types/campaign.d.ts +1533 -0
  46. package/src/types/contact.d.ts +15 -0
  47. package/src/types/csvExport.d.ts +213 -0
  48. package/src/types/dataAnalysis.d.ts +44 -0
  49. package/src/types/dataTable.d.ts +115 -403
  50. package/src/types/definitionElement.d.ts +35 -0
  51. package/src/types/docAccess.d.ts +96 -0
  52. package/src/types/dt.d.ts +257 -0
  53. package/src/types/email.d.ts +184 -24
  54. package/src/types/emailReplyReport.d.ts +76 -0
  55. package/src/types/fieldDoc.d.ts +702 -0
  56. package/src/types/fieldDocContract.d.ts +90 -0
  57. package/src/types/inboundContact.d.ts +10 -1
  58. package/src/types/log.d.ts +254 -295
  59. package/src/types/logDisplay.types.ts +85 -0
  60. package/src/types/organization.d.ts +91 -43
  61. package/src/types/pageRoute.d.ts +48 -0
  62. package/src/types/qrCode.d.ts +96 -0
  63. package/src/types/richText.d.ts +81 -0
  64. package/src/types/sheet.d.ts +678 -129
  65. package/src/types/sms.d.ts +38 -0
  66. package/src/types/storage.d.ts +449 -129
  67. package/src/types/usage.d.ts +106 -0
  68. package/src/types/workflow.d.ts +315 -54
  69. package/src/utils/agentMemory.ts +15 -0
  70. package/src/utils/agentNote.ts +850 -0
  71. package/src/utils/aiChat.ts +43 -0
  72. package/src/utils/aiChatWork.ts +64 -0
  73. package/src/utils/billing.ts +37 -0
  74. package/src/utils/campaign.ts +1174 -0
  75. package/src/utils/campaignAI.ts +72 -0
  76. package/src/utils/campaignAccess.ts +239 -0
  77. package/src/utils/campaignEmail.ts +601 -0
  78. package/src/utils/campaignEmailCompiler.ts +372 -0
  79. package/src/utils/campaignEmailImages.ts +60 -0
  80. package/src/utils/campaignEmailStyles.ts +544 -0
  81. package/src/utils/campaignLifecycle.ts +104 -0
  82. package/src/utils/campaignPreview.ts +285 -0
  83. package/src/utils/contact.ts +50 -0
  84. package/src/utils/csvExport.ts +19 -0
  85. package/src/utils/dataTable.ts +95 -618
  86. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  87. package/src/utils/dataTableRelativeDate.ts +447 -0
  88. package/src/utils/definitionElement.ts +84 -0
  89. package/src/utils/docAccess.ts +383 -0
  90. package/src/utils/documentName.ts +53 -0
  91. package/src/utils/email.ts +317 -51
  92. package/src/utils/emailReplyReport.test.ts +187 -0
  93. package/src/utils/emailReplyReport.ts +143 -0
  94. package/src/utils/fieldDoc.ts +157 -0
  95. package/src/utils/fieldDocAnswers.ts +128 -0
  96. package/src/utils/fieldDocDefaults.ts +36 -0
  97. package/src/utils/fieldDocProgram.ts +36 -0
  98. package/src/utils/fieldDocSummary.ts +30 -0
  99. package/src/utils/log.ts +276 -192
  100. package/src/utils/logDisplay.helpers.ts +177 -0
  101. package/src/utils/logDisplay.ts +87 -0
  102. package/src/utils/logRegistryValue.ts +90 -0
  103. package/src/utils/logStoreRead.ts +262 -0
  104. package/src/utils/logTaxonomy.helpers.ts +17 -0
  105. package/src/utils/logTaxonomy.ts +76 -0
  106. package/src/utils/logTaxonomyDisplay.ts +395 -0
  107. package/src/utils/noteDoc.ts +609 -0
  108. package/src/utils/organization.ts +337 -84
  109. package/src/utils/pageRoute.ts +71 -0
  110. package/src/utils/qrCode.helpers.ts +189 -0
  111. package/src/utils/qrCode.test.ts +519 -0
  112. package/src/utils/qrCode.ts +273 -0
  113. package/src/utils/richTextHTML.ts +385 -0
  114. package/src/utils/sheet.ts +199 -107
  115. package/src/utils/sheetAxisMove.ts +616 -0
  116. package/src/utils/sheetBootstrap.ts +1402 -0
  117. package/src/utils/sheetCellLiteral.ts +101 -0
  118. package/src/utils/sheetCommand.ts +358 -0
  119. package/src/utils/sheetDesign.ts +705 -0
  120. package/src/utils/sheetExport.ts +186 -0
  121. package/src/utils/sheetFeatureReference.ts +183 -0
  122. package/src/utils/sheetFormulaArgs.ts +168 -0
  123. package/src/utils/sheetFormulaCompile.ts +475 -0
  124. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  125. package/src/utils/sheetFormulaCriteria.ts +656 -0
  126. package/src/utils/sheetFormulaDate.ts +444 -0
  127. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  128. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  129. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  130. package/src/utils/sheetFormulaLogical.ts +116 -0
  131. package/src/utils/sheetFormulaLookup.ts +488 -0
  132. package/src/utils/sheetFormulaMath.ts +48 -0
  133. package/src/utils/sheetFormulaParser.ts +729 -0
  134. package/src/utils/sheetFormulaRange.ts +330 -0
  135. package/src/utils/sheetFormulaReference.ts +703 -0
  136. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  137. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  138. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  139. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  140. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  141. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  142. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  143. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  144. package/src/utils/sheetFormulaText.ts +430 -0
  145. package/src/utils/sheetJournal.ts +200 -0
  146. package/src/utils/sheetNumberFormat.ts +1012 -0
  147. package/src/utils/sheetPreview.ts +68 -0
  148. package/src/utils/sheetSequence.ts +118 -0
  149. package/src/utils/sheetSnapshot.ts +739 -0
  150. package/src/utils/sheetStructureEdit.ts +914 -0
  151. package/src/utils/sheetStructureReferences.ts +389 -0
  152. package/src/utils/square.ts +22 -12
  153. package/src/utils/storage.ts +198 -0
  154. package/src/utils/table-route.ts +127 -11
  155. package/src/utils/time.ts +12 -0
  156. package/src/utils/workflow.ts +334 -40
  157. package/src/utils/workflowLogFingerprint.ts +302 -0
  158. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  159. package/src/utils/workflowProgress.ts +280 -0
  160. package/src/utils/workflowTriggers.ts +61 -0
  161. package/tests/agentNote.test.ts +395 -0
  162. package/tests/campaignAI.test.ts +119 -0
  163. package/tests/campaignAccess.test.ts +239 -0
  164. package/tests/campaignEmail.test.ts +441 -0
  165. package/tests/campaignLifecycle.test.ts +134 -0
  166. package/tests/campaignPublication.test.ts +309 -0
  167. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  168. package/tests/dataTableRelativeDate.test.ts +412 -0
  169. package/tests/docAccess.test.ts +525 -0
  170. package/tests/editLogEntry.test.ts +112 -0
  171. package/tests/email.test.ts +39 -0
  172. package/tests/fieldDocProgram.test.ts +114 -0
  173. package/tests/logDisplay.fixtures.ts +67 -0
  174. package/tests/logDisplay.test.ts +227 -0
  175. package/tests/noteDoc.test.ts +514 -0
  176. package/tests/richTextHTML.test.ts +185 -0
  177. package/tests/sheetAxisMove.test.ts +352 -0
  178. package/tests/sheetBootstrap.test.ts +1967 -0
  179. package/tests/sheetFeatureReference.test.ts +22 -0
  180. package/tests/sheetFormulaCriteria.test.ts +269 -0
  181. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  182. package/tests/sheetFormulaFunctions.test.ts +538 -0
  183. package/tests/sheetFormulaLanguage.test.ts +361 -0
  184. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  185. package/tests/sheetFormulaParity.test.ts +188 -0
  186. package/tests/sheetFormulaRange.test.ts +167 -0
  187. package/tests/sheetFormulaReference.test.ts +78 -0
  188. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  189. package/tests/sheetFormulaTextDate.test.ts +512 -0
  190. package/tests/sheetSequence.test.ts +22 -0
  191. package/tests/sheetSnapshot.test.ts +134 -0
  192. package/tests/sheetStructureEdit.test.ts +537 -0
  193. package/tests/sheetStructureReferences.test.ts +589 -0
  194. package/tests/workflowLifecycleStatus.test.ts +60 -0
  195. package/tests/workflowLogFingerprint.test.ts +203 -0
  196. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  197. package/tests/workflowProgress.test.ts +180 -0
  198. package/tests/workflowTriggers.test.ts +29 -0
  199. package/tsconfig.json +10 -10
  200. package/vitest.config.ts +8 -0
  201. package/src/constants/log-activityTexts.ts +0 -235
  202. package/src/constants/product.ts +0 -42
  203. package/src/constants/report.ts +0 -44
  204. package/src/schemas/organization.ts +0 -65
  205. package/src/schemas/productsQuery.ts +0 -53
  206. package/src/schemas/reportsQuery.ts +0 -20
  207. package/src/types/product.d.ts +0 -84
  208. package/src/types/report.d.ts +0 -290
  209. package/src/utils/product-calEvent.ts +0 -455
  210. package/src/utils/report.ts +0 -158
@@ -0,0 +1,106 @@
1
+ import { DATA_TABLE_FIELD_TYPE_ENUMS } from '../constants/dataTable.ts';
2
+
3
+ /* Closed, code-owned semantics vocabulary a data_table_field_types row may
4
+ * bind to. Each key names a behavior family implemented by code
5
+ * (utils/dataTable.ts helpers + the storage/filter compilers); adding a
6
+ * semantics key is a code change, adding a column TYPE is a registry row. */
7
+ export const DATA_TABLE_FIELD_TYPE_SEMANTICS_KEY_ENUMS = [
8
+ 'TEXT',
9
+ 'ID',
10
+ 'ID_OR_TEXT',
11
+ 'NUMBER',
12
+ 'BOOLEAN',
13
+ 'DATE',
14
+ 'WEEK',
15
+ 'DATETIME',
16
+ 'SELECT',
17
+ 'SELECT_OR_TEXT',
18
+ 'MULTI_SELECT',
19
+ 'JSON',
20
+ 'REFERENCE',
21
+ ] as const;
22
+
23
+ export type DataTableFieldTypeSemanticsKey =
24
+ (typeof DATA_TABLE_FIELD_TYPE_SEMANTICS_KEY_ENUMS)[number];
25
+
26
+ /* One dataTable column-type registry row facade: identity + the code-owned
27
+ * semantics family it binds to. Everything else about a type IS its semantics
28
+ * and stays code. */
29
+ export type DataTableFieldTypeDescriptor = {
30
+ key: string;
31
+ semanticsKey: DataTableFieldTypeSemanticsKey;
32
+ ordinal: number;
33
+ };
34
+
35
+ const FILE_CONSTANTS = {
36
+ keyRegex: /^[A-Z][A-Z0-9_]{0,19}$/,
37
+
38
+ /* Type keys whose semantics family differs from their own key; every other
39
+ * type key maps onto the identically-named semantics key. This mapping is
40
+ * the seed source of truth until the registry flips. */
41
+ semanticsOverridesByKey: {
42
+ PRICE: 'NUMBER',
43
+ WEEK_OF_MON: 'WEEK',
44
+ WEEK_OF_SUN: 'WEEK',
45
+ } as Record<string, DataTableFieldTypeSemanticsKey>,
46
+ };
47
+
48
+ /*
49
+ * Derive the registry field-type descriptors from the current hand-maintained
50
+ * enum + the code-side semantics overrides above. This is the seed source of
51
+ * truth until the registry flips; the contract checker compares it against
52
+ * the live database rows and the committed generated module.
53
+ */
54
+ export function buildDataTableFieldTypeDescriptorsFromConstants(): DataTableFieldTypeDescriptor[] {
55
+ return DATA_TABLE_FIELD_TYPE_ENUMS.map((key, index) => ({
56
+ key,
57
+ semanticsKey:
58
+ FILE_CONSTANTS.semanticsOverridesByKey[key] ||
59
+ (key as DataTableFieldTypeSemanticsKey),
60
+ ordinal: index,
61
+ }));
62
+ }
63
+
64
+ /*
65
+ * Validate one descriptor set: key shape, unique keys/ordinals, and semantics
66
+ * vocabulary membership. Returns human-readable issues; an empty array means
67
+ * the set is valid.
68
+ */
69
+ export function collectDataTableFieldTypeDescriptorIssues(
70
+ descriptors: DataTableFieldTypeDescriptor[],
71
+ ): string[] {
72
+ const issues: string[] = [];
73
+ const keys = new Set<string>();
74
+ const ordinals = new Set<number>();
75
+
76
+ if (!descriptors.length) {
77
+ issues.push('registry has no field type rows');
78
+ }
79
+
80
+ descriptors.forEach((descriptor) => {
81
+ if (keys.has(descriptor.key)) {
82
+ issues.push(`duplicate field type key ${descriptor.key}`);
83
+ }
84
+ keys.add(descriptor.key);
85
+
86
+ if (ordinals.has(descriptor.ordinal)) {
87
+ issues.push(`${descriptor.key}: duplicate ordinal ${descriptor.ordinal}`);
88
+ }
89
+ ordinals.add(descriptor.ordinal);
90
+
91
+ if (!FILE_CONSTANTS.keyRegex.test(descriptor.key)) {
92
+ issues.push(`${descriptor.key}: invalid field type key`);
93
+ }
94
+ if (
95
+ !DATA_TABLE_FIELD_TYPE_SEMANTICS_KEY_ENUMS.includes(
96
+ descriptor.semanticsKey,
97
+ )
98
+ ) {
99
+ issues.push(
100
+ `${descriptor.key}: unknown semanticsKey ${descriptor.semanticsKey}`,
101
+ );
102
+ }
103
+ });
104
+
105
+ return issues;
106
+ }
@@ -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
+ }