@jsb188/mday 1.1.11 → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -1,1259 +0,0 @@
1
- import { formatCalDateInTimeZone } from '@jsb188/app/utils/timeZone.ts';
2
- import type {
3
- DataTableDesignCellObj,
4
- DataTableFieldTypeEnum,
5
- DataTableRecordValue,
6
- } from '../types/dataTable.d.ts';
7
- import type {
8
- SheetRegionSourceFilterConditionObj,
9
- SheetRegionSourceFilterGroupObj,
10
- SheetRegionSourceFilterOperatorEnum,
11
- } from '../types/sheet.d.ts';
12
- import {
13
- isDataTableDateLikeFieldType,
14
- isDataTableNumberLikeFieldType,
15
- normalizeDataTableDateLikeValue,
16
- normalizeDataTableDateTimeValue,
17
- normalizeDataTableSelectOptionValue,
18
- } from './dataTable.ts';
19
-
20
- /* Comparison family a filter field type belongs to. */
21
- export type SheetRegionFilterFieldKind =
22
- | 'TEXT'
23
- | 'NUMBER'
24
- | 'DATE'
25
- | 'DATETIME'
26
- | 'BOOLEAN'
27
- | 'MULTI_SELECT';
28
-
29
- /* Typed in-memory value one row exposes for a filtered cell. */
30
- export type SheetRegionFilterComparableValue = {
31
- kind: SheetRegionFilterFieldKind;
32
- /* TEXT kind: stored textValue */
33
- text?: string | null;
34
- /* NUMBER kind, after regex-gated coercion (DV-8) */
35
- number?: number | null;
36
- /* DATE kind: 'YYYY-MM-DD' */
37
- date?: string | null;
38
- /* DATETIME kind: epoch ms */
39
- datetimeMs?: number | null;
40
- /* DATETIME kind: org-tz calendar day (for dateValue compares) */
41
- datetimeDate?: string | null;
42
- /* BOOLEAN kind */
43
- boolean?: boolean | null;
44
- /* MULTI_SELECT kind: jsonb array elements, verbatim case */
45
- elements?: string[] | null;
46
- /* Raw-storage non-emptiness keyed on the STORAGE field type, mirroring
47
- * getSheetRegionSourceNonEmptyRecordPredicate — the SQL IS_EMPTY meaning.
48
- * Never derived from the coerced comparison fields above. */
49
- storageNonEmpty?: boolean;
50
- /* True when the SQL coercion behind this comparable depends on the DB
51
- * session timezone (DV-9 text-timestamp casts) or on raw text prefixes the
52
- * coerced value cannot mirror; value comparisons must go to SQL (null). */
53
- sqlOnly?: boolean;
54
- };
55
-
56
- /* Typed storage columns of one filterable record (dataTable record shape). */
57
- export type SheetRegionFilterComparableRecord = {
58
- textValue?: string | null;
59
- numberValue?: number | string | null;
60
- booleanValue?: boolean | null;
61
- dateValue?: string | Date | null;
62
- datetimeValue?: string | Date | null;
63
- value?: unknown;
64
- };
65
-
66
- /* Filter condition with the server-attached field-type metadata. */
67
- export type SheetRegionFilterConditionWithFieldType =
68
- SheetRegionSourceFilterConditionObj & {
69
- fieldType?: DataTableFieldTypeEnum | null;
70
- sourceFieldType?: DataTableFieldTypeEnum | null;
71
- };
72
-
73
- /* Injection-safe named-parameter binder: stores the value, returns '$varKey'. */
74
- export type SheetRegionFilterSQLBinder = (value: unknown) => string;
75
-
76
- /* Pre-built, identifier-only SQL column expressions for one condition target. */
77
- export type SheetRegionFilterSQLColumnExprs = {
78
- /* Null-safe text expression (caller supplies any COALESCE(...) wrapper) */
79
- textExpr?: string | null;
80
- numberExpr?: string | null;
81
- /* Calendar-date comparison expression (::text day for dataTable records,
82
- * native date column for LOGS) */
83
- dateExpr?: string | null;
84
- /* timestamptz expression */
85
- datetimeExpr?: string | null;
86
- booleanExpr?: string | null;
87
- /* MULTI_SELECT jsonb value column */
88
- jsonbExpr?: string | null;
89
- /* Cast appended to the bound date parameter. The LOGS compiler compares
90
- * native date columns as `expr <op> $value::date`; dataTable records
91
- * compare day-text with no cast. */
92
- dateBindCast?: string | null;
93
- };
94
-
95
- /* Design-cell fields needed to normalize filter values. */
96
- export type SheetRegionFilterDesignCell = Pick<
97
- DataTableDesignCellObj,
98
- 'fieldType' | 'options'
99
- >;
100
-
101
- export interface SheetRegionFilterOperatorDef {
102
- key: SheetRegionSourceFilterOperatorEnum;
103
- /* Field kinds the operator can be used with; IS_EMPTY lists all six. */
104
- appliesTo: readonly SheetRegionFilterFieldKind[];
105
- valueArity: 'NONE' | 'ONE' | 'MANY';
106
- /* Human phrase for query-part explanations ("contains", "is one of", ...). */
107
- explanationText: string;
108
- /* Canonical filter-string token ("=", "CONTAINS", "IS EMPTY", ...). */
109
- canonicalQueryText: string;
110
- /* True when SQL needs server-only related-table lookups (ID EQUALS/IN). */
111
- requiresSQLForFieldType?: (
112
- fieldType: DataTableFieldTypeEnum | null | undefined,
113
- ) => boolean;
114
- /* Pure in-memory row test mirroring the SQL meaning exactly. */
115
- tsPredicate: (
116
- fieldValue: SheetRegionFilterComparableValue,
117
- condition: SheetRegionSourceFilterConditionObj,
118
- ) => boolean;
119
- /* Parameterized SQL comparison; NEVER interpolates values — only exprs +
120
- * bind() keys. */
121
- sqlPredicate: (
122
- exprs: SheetRegionFilterSQLColumnExprs,
123
- condition: SheetRegionSourceFilterConditionObj,
124
- kind: SheetRegionFilterFieldKind,
125
- bind: SheetRegionFilterSQLBinder,
126
- ) => string;
127
- }
128
-
129
- const FILE_CONSTANTS = {
130
- /* Operators that must NOT become bare keyword tokens in the query DSL
131
- * (IS EMPTY is parsed as a two-word phrase by the client parser). */
132
- keywordExcludedOperators: [
133
- 'IS_EMPTY',
134
- ] as SheetRegionSourceFilterOperatorEnum[],
135
- /* Numeric-text coercion gate; must stay identical to the SQL regex in
136
- * getSheetRegionSourceNumberValueExpression (DV-8). */
137
- numberTextPattern: /^[-+]?\d+(\.\d+)?$/,
138
- /* Explicit date-only literal shape shared by client + server normalize. */
139
- dateOnlyPattern: /^\d{4}-\d{2}-\d{2}$/,
140
- /* ISO-prefixed text treated as a timestamp by the SQL fallbacks (DV-9). */
141
- isoDatePrefixPattern: /^\d{4}-\d{2}-\d{2}/,
142
- /* Non-ISO date-like text shapes accepted by the SQL day fallback (DV-9). */
143
- dateLikeTextPatterns: [
144
- /^[A-Za-z]{3}\s+[A-Za-z]{3}\s+\d{1,2}\s+\d{4}/,
145
- /^[A-Za-z]{3,9}\s+\d{1,2},\s+\d{4}/,
146
- ],
147
- };
148
-
149
- /*
150
- * Return the user-facing dataTable field type that region filters validate against.
151
- */
152
- export function getSheetRegionFilterFieldType(
153
- cell: Pick<DataTableDesignCellObj, 'fieldType'>,
154
- ) {
155
- return cell.fieldType;
156
- }
157
-
158
- /*
159
- * Return whether a dataTable field type should be filtered as text.
160
- */
161
- export function isSheetRegionFilterTextFieldType(
162
- fieldType: DataTableFieldTypeEnum | null | undefined,
163
- ) {
164
- return (
165
- fieldType === 'TEXT' ||
166
- fieldType === 'ID' ||
167
- fieldType === 'ID_OR_TEXT' ||
168
- fieldType === 'SELECT' ||
169
- fieldType === 'SELECT_OR_TEXT'
170
- );
171
- }
172
-
173
- /*
174
- * Return the comparison family for one filter field type, or null when the
175
- * field type cannot be filtered.
176
- */
177
- export function getSheetRegionFilterFieldKind(
178
- fieldType: DataTableFieldTypeEnum | null | undefined,
179
- ): SheetRegionFilterFieldKind | null {
180
- if (isSheetRegionFilterTextFieldType(fieldType)) {
181
- return 'TEXT';
182
- }
183
-
184
- if (isDataTableNumberLikeFieldType(fieldType)) {
185
- return 'NUMBER';
186
- }
187
-
188
- if (isDataTableDateLikeFieldType(fieldType)) {
189
- return 'DATE';
190
- }
191
-
192
- if (fieldType === 'DATETIME') {
193
- return 'DATETIME';
194
- }
195
-
196
- if (fieldType === 'BOOLEAN') {
197
- return 'BOOLEAN';
198
- }
199
-
200
- if (fieldType === 'MULTI_SELECT') {
201
- return 'MULTI_SELECT';
202
- }
203
-
204
- return null;
205
- }
206
-
207
- /*
208
- * Return the LIKE pattern for one CONTAINS filter value.
209
- * DV-6: `\`, `%`, and `_` are escaped so CONTAINS means a literal substring;
210
- * the emitted comparison appends `ESCAPE '\'` to match.
211
- */
212
- export function getSheetRegionFilterContainsLikePattern(value: unknown) {
213
- const escapedValue = String(value || '')
214
- .toLowerCase()
215
- .replace(/\\/g, '\\\\')
216
- .replace(/%/g, '\\%')
217
- .replace(/_/g, '\\_');
218
-
219
- return `%${escapedValue}%`;
220
- }
221
-
222
- /*
223
- * Return a comparable number coerced from text storage using the exact SQL
224
- * regex gate (rejects '1e3', '.5', '1,000' just like the compiler; DV-8).
225
- */
226
- export function getSheetRegionFilterComparableNumberFromText(
227
- text: string | null | undefined,
228
- ) {
229
- const stringValue = String(text ?? '');
230
- if (!FILE_CONSTANTS.numberTextPattern.test(stringValue)) {
231
- return null;
232
- }
233
-
234
- const numberValue = Number(stringValue);
235
- return Number.isFinite(numberValue) ? numberValue : null;
236
- }
237
-
238
- /*
239
- * Return the epoch milliseconds for one stored date-like value, or null.
240
- */
241
- function getSheetRegionFilterInstantMs(
242
- value: string | Date | null | undefined,
243
- ) {
244
- if (value === null || value === undefined || value === '') {
245
- return null;
246
- }
247
-
248
- const ms =
249
- value instanceof Date ? value.getTime() : Date.parse(String(value));
250
- return Number.isFinite(ms) ? ms : null;
251
- }
252
-
253
- /*
254
- * Return the calendar day of one instant in a timezone ('UTC' when absent),
255
- * mirroring `(value AT TIME ZONE tz)::date` / `value::date` in SQL.
256
- */
257
- function getSheetRegionFilterTimeZoneDateKey(
258
- value: string | Date | null | undefined,
259
- timeZone?: string | null,
260
- ) {
261
- const ms = getSheetRegionFilterInstantMs(value);
262
- if (ms === null) {
263
- return null;
264
- }
265
-
266
- return formatCalDateInTimeZone(new Date(ms), timeZone || null);
267
- }
268
-
269
- /*
270
- * Return the 'YYYY-MM-DD' key of one stored dateValue column value.
271
- */
272
- function getSheetRegionFilterStoredDateKey(
273
- value: string | Date | null | undefined,
274
- ) {
275
- if (value === null || value === undefined || value === '') {
276
- return null;
277
- }
278
-
279
- return value instanceof Date
280
- ? value.toISOString().slice(0, 10)
281
- : String(value).split('T')[0];
282
- }
283
-
284
- /*
285
- * Return text with surrounding double quotes removed, mirroring the SQL
286
- * TRIM(BOTH '"' FROM ...) wrapper applied to text-stored timestamps.
287
- */
288
- function trimSheetRegionFilterTextQuotes(text: string) {
289
- return text.replace(/^"+/, '').replace(/"+$/, '');
290
- }
291
-
292
- /*
293
- * Return a comparable 'YYYY-MM-DD' day coerced from ISO-prefixed text storage,
294
- * mirroring the SQL LEFT(text, 10) fallback exactly (DV-9). Month-name text
295
- * shapes are NOT converted here: their SQL conversion (text::timestamptz)
296
- * anchors in the DB session timezone, which cannot be mirrored in memory —
297
- * see isSheetRegionFilterSQLOnlyDateLikeText.
298
- */
299
- export function getSheetRegionFilterComparableDateFromText(
300
- text: string | null | undefined,
301
- ) {
302
- const trimmed = trimSheetRegionFilterTextQuotes(String(text ?? ''));
303
- if (FILE_CONSTANTS.isoDatePrefixPattern.test(trimmed)) {
304
- return trimmed.slice(0, 10);
305
- }
306
-
307
- return null;
308
- }
309
-
310
- /*
311
- * Return whether text matches the non-ISO date-like SQL fallback shapes
312
- * ('Mon Jul 1 2026' / 'July 1, 2026') whose ::timestamptz conversion depends
313
- * on the DB session timezone. Comparables built from such text are SQL-only:
314
- * evaluating them in memory (e.g. via Date.parse, which anchors in the HOST
315
- * timezone) can produce a different calendar day than the compiled SQL (DV-9).
316
- */
317
- export function isSheetRegionFilterSQLOnlyDateLikeText(
318
- text: string | null | undefined,
319
- ) {
320
- const trimmed = trimSheetRegionFilterTextQuotes(String(text ?? ''));
321
-
322
- return FILE_CONSTANTS.dateLikeTextPatterns.some((pattern) =>
323
- pattern.test(trimmed),
324
- );
325
- }
326
-
327
- /*
328
- * Return whether one record has a non-empty stored value for its STORAGE
329
- * field type, mirroring getSheetRegionSourceNonEmptyRecordPredicate exactly:
330
- * the dataTable IS_EMPTY SQL decides emptiness from raw storage columns,
331
- * never from the coerced comparison value (a NUMBER filter over TEXT storage
332
- * is non-empty for unparseable text like 'abc').
333
- */
334
- export function isSheetRegionFilterRecordStorageNonEmpty(
335
- record: SheetRegionFilterComparableRecord | null | undefined,
336
- sourceFieldType?: DataTableFieldTypeEnum | null,
337
- ) {
338
- if (!record) {
339
- return false;
340
- }
341
-
342
- if (isDataTableNumberLikeFieldType(sourceFieldType)) {
343
- return record.numberValue !== null && record.numberValue !== undefined;
344
- }
345
-
346
- if (isDataTableDateLikeFieldType(sourceFieldType)) {
347
- return (
348
- record.dateValue !== null &&
349
- record.dateValue !== undefined &&
350
- record.dateValue !== ''
351
- );
352
- }
353
-
354
- if (sourceFieldType === 'DATETIME') {
355
- return (
356
- record.datetimeValue !== null &&
357
- record.datetimeValue !== undefined &&
358
- record.datetimeValue !== ''
359
- );
360
- }
361
-
362
- if (sourceFieldType === 'BOOLEAN') {
363
- return record.booleanValue !== null && record.booleanValue !== undefined;
364
- }
365
-
366
- if (sourceFieldType === 'MULTI_SELECT') {
367
- return Array.isArray(record.value) && record.value.length > 0;
368
- }
369
-
370
- return String(record.textValue ?? '') !== '';
371
- }
372
-
373
- /*
374
- * Return the typed in-memory comparable for one record's storage columns,
375
- * mirroring the SQL value expressions (including the DV-8/DV-9 text
376
- * coercion fallbacks) for one comparison kind.
377
- */
378
- export function getSheetRegionFilterComparableValueFromRecord(
379
- record: SheetRegionFilterComparableRecord | null | undefined,
380
- kind: SheetRegionFilterFieldKind,
381
- sourceFieldType?: DataTableFieldTypeEnum | null,
382
- timeZone?: string | null,
383
- ): SheetRegionFilterComparableValue {
384
- // IS_EMPTY mirrors the SQL raw-storage emptiness, keyed on the STORAGE
385
- // field type — computed for every kind, independent of the coerced value
386
- const storageNonEmpty = isSheetRegionFilterRecordStorageNonEmpty(
387
- record,
388
- sourceFieldType,
389
- );
390
-
391
- if (kind === 'NUMBER') {
392
- if (isDataTableNumberLikeFieldType(sourceFieldType)) {
393
- const numberValue =
394
- record?.numberValue === null || record?.numberValue === undefined
395
- ? null
396
- : Number(record.numberValue);
397
- return {
398
- kind,
399
- storageNonEmpty,
400
- number:
401
- numberValue !== null && Number.isFinite(numberValue)
402
- ? numberValue
403
- : null,
404
- };
405
- }
406
-
407
- return {
408
- kind,
409
- storageNonEmpty,
410
- number: getSheetRegionFilterComparableNumberFromText(record?.textValue),
411
- };
412
- }
413
-
414
- if (kind === 'DATE') {
415
- if (isDataTableDateLikeFieldType(sourceFieldType)) {
416
- return {
417
- kind,
418
- storageNonEmpty,
419
- date: getSheetRegionFilterStoredDateKey(record?.dateValue),
420
- };
421
- }
422
-
423
- if (sourceFieldType === 'DATETIME') {
424
- return {
425
- kind,
426
- storageNonEmpty,
427
- date: getSheetRegionFilterTimeZoneDateKey(
428
- record?.datetimeValue,
429
- timeZone,
430
- ),
431
- };
432
- }
433
-
434
- const storedDate = getSheetRegionFilterStoredDateKey(record?.dateValue);
435
- if (storedDate) {
436
- return { kind, storageNonEmpty, date: storedDate };
437
- }
438
-
439
- const datetimeDate = getSheetRegionFilterTimeZoneDateKey(
440
- record?.datetimeValue,
441
- timeZone,
442
- );
443
- if (datetimeDate) {
444
- return { kind, storageNonEmpty, date: datetimeDate };
445
- }
446
-
447
- const textDate = getSheetRegionFilterComparableDateFromText(
448
- record?.textValue,
449
- );
450
- if (textDate) {
451
- return { kind, storageNonEmpty, date: textDate };
452
- }
453
-
454
- // DV-9: month-name text converts via ::timestamptz in the DB SESSION
455
- // timezone — unmirrorable in memory, so value comparisons go to SQL
456
- if (isSheetRegionFilterSQLOnlyDateLikeText(record?.textValue)) {
457
- return { kind, storageNonEmpty, date: null, sqlOnly: true };
458
- }
459
-
460
- return { kind, storageNonEmpty, date: null };
461
- }
462
-
463
- if (kind === 'DATETIME') {
464
- if (sourceFieldType === 'DATETIME') {
465
- const datetimeMs = getSheetRegionFilterInstantMs(record?.datetimeValue);
466
-
467
- return {
468
- kind,
469
- storageNonEmpty,
470
- datetimeMs,
471
- datetimeDate:
472
- datetimeMs === null
473
- ? null
474
- : formatCalDateInTimeZone(new Date(datetimeMs), timeZone || null),
475
- };
476
- }
477
-
478
- // DV-9: text-stored timestamps cannot be mirrored in memory — naive text
479
- // anchors ::timestamptz in the DB SESSION timezone, and day-bucket
480
- // comparisons use the raw LEFT(text, 10) prefix rather than the org-tz
481
- // day of the parsed instant — so any date-like text is SQL-only
482
- const trimmedText = trimSheetRegionFilterTextQuotes(
483
- String(record?.textValue ?? ''),
484
- );
485
- const isDateLikeText =
486
- FILE_CONSTANTS.isoDatePrefixPattern.test(trimmedText) ||
487
- isSheetRegionFilterSQLOnlyDateLikeText(record?.textValue);
488
- if (isDateLikeText) {
489
- return {
490
- kind,
491
- storageNonEmpty,
492
- datetimeMs: null,
493
- datetimeDate: null,
494
- sqlOnly: true,
495
- };
496
- }
497
-
498
- return { kind, storageNonEmpty, datetimeMs: null, datetimeDate: null };
499
- }
500
-
501
- if (kind === 'BOOLEAN') {
502
- return { kind, storageNonEmpty, boolean: record?.booleanValue ?? null };
503
- }
504
-
505
- if (kind === 'MULTI_SELECT') {
506
- const recordValue = record?.value;
507
- const elements = Array.isArray(recordValue)
508
- ? recordValue.filter(
509
- (element): element is string => typeof element === 'string',
510
- )
511
- : null;
512
- return { kind, storageNonEmpty, elements };
513
- }
514
-
515
- return { kind: 'TEXT', storageNonEmpty, text: record?.textValue ?? null };
516
- }
517
-
518
- /*
519
- * Compare one temporal comparable against a condition using the SQL
520
- * dateValue-vs-datetimeValue split (day-bucket compare when a calendar date
521
- * literal is present; exact-instant compare otherwise).
522
- */
523
- function compareSheetRegionFilterTemporal(
524
- fieldValue: SheetRegionFilterComparableValue,
525
- condition: SheetRegionSourceFilterConditionObj,
526
- compare: (a: number | string, b: number | string) => boolean,
527
- ) {
528
- if (fieldValue.kind === 'DATE') {
529
- if (
530
- !fieldValue.date ||
531
- condition.dateValue === null ||
532
- condition.dateValue === undefined
533
- ) {
534
- return false;
535
- }
536
-
537
- return compare(fieldValue.date, String(condition.dateValue));
538
- }
539
-
540
- if (condition.dateValue !== null && condition.dateValue !== undefined) {
541
- if (!fieldValue.datetimeDate) {
542
- return false;
543
- }
544
-
545
- return compare(fieldValue.datetimeDate, String(condition.dateValue));
546
- }
547
-
548
- if (
549
- condition.datetimeValue === null ||
550
- condition.datetimeValue === undefined ||
551
- fieldValue.datetimeMs === null ||
552
- fieldValue.datetimeMs === undefined
553
- ) {
554
- return false;
555
- }
556
-
557
- const conditionMs = getSheetRegionFilterInstantMs(condition.datetimeValue);
558
- if (conditionMs === null) {
559
- return false;
560
- }
561
-
562
- return compare(fieldValue.datetimeMs, conditionMs);
563
- }
564
-
565
- /*
566
- * Return the parameterized SQL comparison for one temporal condition,
567
- * encoding the dateValue-vs-datetimeValue split once:
568
- * - DATE kind → dateExpr <op> $dateValue (plus the compiler's dateBindCast)
569
- * - DATETIME + dateValue (day bucket, needs dateExpr) → dateExpr <op> $dateValue
570
- * - DATETIME + datetimeValue → datetimeExpr <op> $datetimeValue::timestamptz
571
- */
572
- export function getSheetRegionFilterTemporalSQL(
573
- exprs: SheetRegionFilterSQLColumnExprs,
574
- condition: SheetRegionSourceFilterConditionObj,
575
- kind: SheetRegionFilterFieldKind,
576
- bind: SheetRegionFilterSQLBinder,
577
- operatorSQL: string,
578
- ) {
579
- const dateBindCast = exprs.dateBindCast || '';
580
-
581
- if (kind === 'DATE') {
582
- if (!exprs.dateExpr) {
583
- throw new Error('20077');
584
- }
585
-
586
- return `${exprs.dateExpr} ${operatorSQL} ${bind(condition.dateValue)}${dateBindCast}`;
587
- }
588
-
589
- if (
590
- condition.dateValue !== null &&
591
- condition.dateValue !== undefined &&
592
- exprs.dateExpr
593
- ) {
594
- return `${exprs.dateExpr} ${operatorSQL} ${bind(condition.dateValue)}${dateBindCast}`;
595
- }
596
-
597
- if (!exprs.datetimeExpr) {
598
- throw new Error('20077');
599
- }
600
-
601
- return `${exprs.datetimeExpr} ${operatorSQL} ${bind(condition.datetimeValue)}::timestamptz`;
602
- }
603
-
604
- /*
605
- * Return the parameterized SQL comparison for one text condition (lowercase
606
- * equality; the value is lowered at bind time exactly like the compilers).
607
- */
608
- function getSheetRegionFilterTextEqualsSQL(
609
- exprs: SheetRegionFilterSQLColumnExprs,
610
- condition: SheetRegionSourceFilterConditionObj,
611
- bind: SheetRegionFilterSQLBinder,
612
- ) {
613
- if (!exprs.textExpr) {
614
- throw new Error('20077');
615
- }
616
-
617
- return `LOWER(${exprs.textExpr}) = ${bind(String(condition.textValue || '').toLowerCase())}`;
618
- }
619
-
620
- /*
621
- * Return the parameterized SQL comparison for one MULTI_SELECT single-element
622
- * containment condition (case-sensitive exact jsonb element match).
623
- */
624
- function getSheetRegionFilterJsonbContainsSQL(
625
- exprs: SheetRegionFilterSQLColumnExprs,
626
- condition: SheetRegionSourceFilterConditionObj,
627
- bind: SheetRegionFilterSQLBinder,
628
- ) {
629
- if (!exprs.jsonbExpr) {
630
- throw new Error('20077');
631
- }
632
-
633
- return `${exprs.jsonbExpr} ? ${bind(condition.textValue)}`;
634
- }
635
-
636
- /*
637
- * Return the parameterized SQL comparison for one numeric condition.
638
- */
639
- function getSheetRegionFilterNumberSQL(
640
- exprs: SheetRegionFilterSQLColumnExprs,
641
- condition: SheetRegionSourceFilterConditionObj,
642
- bind: SheetRegionFilterSQLBinder,
643
- operatorSQL: string,
644
- ) {
645
- if (!exprs.numberExpr) {
646
- throw new Error('20077');
647
- }
648
-
649
- return `${exprs.numberExpr} ${operatorSQL} ${bind(condition.numberValue)}`;
650
- }
651
-
652
- /*
653
- * Return whether one numeric comparable pair is present and passes a compare.
654
- */
655
- function compareSheetRegionFilterNumbers(
656
- fieldValue: SheetRegionFilterComparableValue,
657
- condition: SheetRegionSourceFilterConditionObj,
658
- compare: (a: number, b: number) => boolean,
659
- ) {
660
- return (
661
- fieldValue.number !== null &&
662
- fieldValue.number !== undefined &&
663
- condition.numberValue !== null &&
664
- condition.numberValue !== undefined &&
665
- compare(fieldValue.number, condition.numberValue)
666
- );
667
- }
668
-
669
- /*
670
- * Return the shared EQUALS comparison SQL for one condition kind.
671
- */
672
- function getSheetRegionFilterEqualsSQL(
673
- exprs: SheetRegionFilterSQLColumnExprs,
674
- condition: SheetRegionSourceFilterConditionObj,
675
- kind: SheetRegionFilterFieldKind,
676
- bind: SheetRegionFilterSQLBinder,
677
- ) {
678
- if (kind === 'NUMBER') {
679
- return getSheetRegionFilterNumberSQL(exprs, condition, bind, '=');
680
- }
681
-
682
- if (kind === 'DATE' || kind === 'DATETIME') {
683
- return getSheetRegionFilterTemporalSQL(exprs, condition, kind, bind, '=');
684
- }
685
-
686
- if (kind === 'BOOLEAN') {
687
- if (!exprs.booleanExpr) {
688
- throw new Error('20077');
689
- }
690
-
691
- return `${exprs.booleanExpr} = ${bind(condition.booleanValue)}`;
692
- }
693
-
694
- if (kind === 'MULTI_SELECT') {
695
- return getSheetRegionFilterJsonbContainsSQL(exprs, condition, bind);
696
- }
697
-
698
- return getSheetRegionFilterTextEqualsSQL(exprs, condition, bind);
699
- }
700
-
701
- export const SHEET_REGION_FILTER_OPERATOR_DEFS: Record<
702
- SheetRegionSourceFilterOperatorEnum,
703
- SheetRegionFilterOperatorDef
704
- > = {
705
- CONTAINS: {
706
- key: 'CONTAINS',
707
- appliesTo: ['TEXT', 'MULTI_SELECT'],
708
- valueArity: 'ONE',
709
- explanationText: 'contains',
710
- canonicalQueryText: 'CONTAINS',
711
- // MULTI_SELECT keeps exact, case-sensitive element semantics (DV-3);
712
- // text CONTAINS is a case-insensitive LITERAL substring — the SQL side
713
- // escapes LIKE metacharacters and appends ESCAPE to match (DV-6).
714
- tsPredicate: (fieldValue, condition) =>
715
- fieldValue.kind === 'MULTI_SELECT'
716
- ? condition.textValue !== null &&
717
- condition.textValue !== undefined &&
718
- (fieldValue.elements || []).includes(String(condition.textValue))
719
- : String(fieldValue.text ?? '')
720
- .toLowerCase()
721
- .includes(String(condition.textValue || '').toLowerCase()),
722
- sqlPredicate: (exprs, condition, kind, bind) => {
723
- if (kind === 'MULTI_SELECT') {
724
- return getSheetRegionFilterJsonbContainsSQL(exprs, condition, bind);
725
- }
726
-
727
- if (!exprs.textExpr) {
728
- throw new Error('20077');
729
- }
730
-
731
- // DV-6: ESCAPE pairs with the escaped pattern for literal substrings
732
- return `LOWER(${exprs.textExpr}) LIKE ${bind(getSheetRegionFilterContainsLikePattern(condition.textValue))} ESCAPE '\\'`;
733
- },
734
- },
735
- EQUALS: {
736
- key: 'EQUALS',
737
- appliesTo: ['TEXT', 'NUMBER', 'DATE', 'DATETIME', 'BOOLEAN'],
738
- valueArity: 'ONE',
739
- explanationText: 'equals',
740
- canonicalQueryText: '=',
741
- requiresSQLForFieldType: (fieldType) => fieldType === 'ID',
742
- tsPredicate: (fieldValue, condition) => {
743
- if (fieldValue.kind === 'NUMBER') {
744
- return compareSheetRegionFilterNumbers(
745
- fieldValue,
746
- condition,
747
- (a, b) => a === b,
748
- );
749
- }
750
-
751
- if (fieldValue.kind === 'DATE' || fieldValue.kind === 'DATETIME') {
752
- return compareSheetRegionFilterTemporal(
753
- fieldValue,
754
- condition,
755
- (a, b) => a === b,
756
- );
757
- }
758
-
759
- if (fieldValue.kind === 'BOOLEAN') {
760
- return (
761
- fieldValue.boolean !== null &&
762
- fieldValue.boolean !== undefined &&
763
- condition.booleanValue !== null &&
764
- condition.booleanValue !== undefined &&
765
- fieldValue.boolean === condition.booleanValue
766
- );
767
- }
768
-
769
- if (fieldValue.kind === 'MULTI_SELECT') {
770
- return (
771
- condition.textValue !== null &&
772
- condition.textValue !== undefined &&
773
- (fieldValue.elements || []).includes(String(condition.textValue))
774
- );
775
- }
776
-
777
- return (
778
- String(fieldValue.text ?? '').toLowerCase() ===
779
- String(condition.textValue || '').toLowerCase()
780
- );
781
- },
782
- sqlPredicate: getSheetRegionFilterEqualsSQL,
783
- },
784
- IN: {
785
- key: 'IN',
786
- appliesTo: ['TEXT'],
787
- valueArity: 'MANY',
788
- explanationText: 'is one of',
789
- canonicalQueryText: 'IN',
790
- requiresSQLForFieldType: (fieldType) => fieldType === 'ID',
791
- tsPredicate: (fieldValue, condition) =>
792
- (condition.textValues || [])
793
- .map((value) => String(value).toLowerCase())
794
- .includes(String(fieldValue.text ?? '').toLowerCase()),
795
- sqlPredicate: (exprs, condition, _kind, bind) => {
796
- if (!exprs.textExpr) {
797
- throw new Error('20077');
798
- }
799
-
800
- return `LOWER(${exprs.textExpr}) = ANY(${bind((condition.textValues || []).map((value) => String(value).toLowerCase()))})`;
801
- },
802
- },
803
- IS_EMPTY: {
804
- key: 'IS_EMPTY',
805
- appliesTo: [
806
- 'TEXT',
807
- 'NUMBER',
808
- 'DATE',
809
- 'DATETIME',
810
- 'BOOLEAN',
811
- 'MULTI_SELECT',
812
- ],
813
- valueArity: 'NONE',
814
- explanationText: 'is empty',
815
- canonicalQueryText: 'IS EMPTY',
816
- tsPredicate: (fieldValue) => {
817
- // The SQL decides emptiness from RAW storage columns keyed on the
818
- // STORAGE field type (getSheetRegionSourceNonEmptyRecordPredicate) —
819
- // never from the coerced comparison value, which nulls out when the
820
- // filter kind differs from the storage kind (e.g. a NUMBER filter over
821
- // TEXT storage holding 'abc' is NON-empty). Comparables built by
822
- // getSheetRegionFilterComparableValueFromRecord always carry the flag.
823
- if (typeof fieldValue.storageNonEmpty === 'boolean') {
824
- return !fieldValue.storageNonEmpty;
825
- }
826
-
827
- // Fallback for hand-built comparables (kind assumed = storage kind,
828
- // where coerced-value emptiness equals raw-storage emptiness)
829
- if (fieldValue.kind === 'NUMBER') {
830
- return fieldValue.number === null || fieldValue.number === undefined;
831
- }
832
-
833
- if (fieldValue.kind === 'DATE') {
834
- return !fieldValue.date;
835
- }
836
-
837
- if (fieldValue.kind === 'DATETIME') {
838
- return (
839
- fieldValue.datetimeMs === null || fieldValue.datetimeMs === undefined
840
- );
841
- }
842
-
843
- if (fieldValue.kind === 'BOOLEAN') {
844
- return fieldValue.boolean === null || fieldValue.boolean === undefined;
845
- }
846
-
847
- if (fieldValue.kind === 'MULTI_SELECT') {
848
- return !fieldValue.elements?.length;
849
- }
850
-
851
- return !fieldValue.text;
852
- },
853
- // Value-level emptiness in the LOGS shape; both compilers keep their own
854
- // row-level scaffolding (NOT-EXISTS-non-empty for dataTable records) and
855
- // do not call this. Captured here so parity suites lock the semantics.
856
- sqlPredicate: (exprs, _condition, kind) => {
857
- const expression =
858
- kind === 'NUMBER'
859
- ? exprs.numberExpr
860
- : kind === 'DATE'
861
- ? exprs.dateExpr
862
- : kind === 'DATETIME'
863
- ? exprs.datetimeExpr
864
- : kind === 'BOOLEAN'
865
- ? exprs.booleanExpr
866
- : kind === 'MULTI_SELECT'
867
- ? exprs.jsonbExpr
868
- : exprs.textExpr;
869
- if (!expression) {
870
- throw new Error('20077');
871
- }
872
-
873
- return kind === 'TEXT'
874
- ? `(${expression} IS NULL OR ${expression} = '')`
875
- : `${expression} IS NULL`;
876
- },
877
- },
878
- GT: {
879
- key: 'GT',
880
- appliesTo: ['NUMBER'],
881
- valueArity: 'ONE',
882
- explanationText: 'is greater than',
883
- canonicalQueryText: '>',
884
- tsPredicate: (fieldValue, condition) =>
885
- compareSheetRegionFilterNumbers(fieldValue, condition, (a, b) => a > b),
886
- sqlPredicate: (exprs, condition, _kind, bind) =>
887
- getSheetRegionFilterNumberSQL(exprs, condition, bind, '>'),
888
- },
889
- GTE: {
890
- key: 'GTE',
891
- appliesTo: ['NUMBER'],
892
- valueArity: 'ONE',
893
- explanationText: 'is greater than or equal to',
894
- canonicalQueryText: '>=',
895
- tsPredicate: (fieldValue, condition) =>
896
- compareSheetRegionFilterNumbers(fieldValue, condition, (a, b) => a >= b),
897
- sqlPredicate: (exprs, condition, _kind, bind) =>
898
- getSheetRegionFilterNumberSQL(exprs, condition, bind, '>='),
899
- },
900
- LT: {
901
- key: 'LT',
902
- appliesTo: ['NUMBER'],
903
- valueArity: 'ONE',
904
- explanationText: 'is less than',
905
- canonicalQueryText: '<',
906
- tsPredicate: (fieldValue, condition) =>
907
- compareSheetRegionFilterNumbers(fieldValue, condition, (a, b) => a < b),
908
- sqlPredicate: (exprs, condition, _kind, bind) =>
909
- getSheetRegionFilterNumberSQL(exprs, condition, bind, '<'),
910
- },
911
- LTE: {
912
- key: 'LTE',
913
- appliesTo: ['NUMBER'],
914
- valueArity: 'ONE',
915
- explanationText: 'is less than or equal to',
916
- canonicalQueryText: '<=',
917
- tsPredicate: (fieldValue, condition) =>
918
- compareSheetRegionFilterNumbers(fieldValue, condition, (a, b) => a <= b),
919
- sqlPredicate: (exprs, condition, _kind, bind) =>
920
- getSheetRegionFilterNumberSQL(exprs, condition, bind, '<='),
921
- },
922
- BEFORE: {
923
- key: 'BEFORE',
924
- appliesTo: ['DATE', 'DATETIME'],
925
- valueArity: 'ONE',
926
- explanationText: 'is before',
927
- canonicalQueryText: 'BEFORE',
928
- tsPredicate: (fieldValue, condition) =>
929
- compareSheetRegionFilterTemporal(fieldValue, condition, (a, b) => a < b),
930
- sqlPredicate: (exprs, condition, kind, bind) =>
931
- getSheetRegionFilterTemporalSQL(exprs, condition, kind, bind, '<'),
932
- },
933
- AFTER: {
934
- key: 'AFTER',
935
- appliesTo: ['DATE', 'DATETIME'],
936
- valueArity: 'ONE',
937
- explanationText: 'is after',
938
- canonicalQueryText: 'AFTER',
939
- tsPredicate: (fieldValue, condition) =>
940
- compareSheetRegionFilterTemporal(fieldValue, condition, (a, b) => a > b),
941
- sqlPredicate: (exprs, condition, kind, bind) =>
942
- getSheetRegionFilterTemporalSQL(exprs, condition, kind, bind, '>'),
943
- },
944
- ON_OR_BEFORE: {
945
- key: 'ON_OR_BEFORE',
946
- appliesTo: ['DATE', 'DATETIME'],
947
- valueArity: 'ONE',
948
- explanationText: 'is on or before',
949
- canonicalQueryText: '<=',
950
- tsPredicate: (fieldValue, condition) =>
951
- compareSheetRegionFilterTemporal(fieldValue, condition, (a, b) => a <= b),
952
- sqlPredicate: (exprs, condition, kind, bind) =>
953
- getSheetRegionFilterTemporalSQL(exprs, condition, kind, bind, '<='),
954
- },
955
- ON_OR_AFTER: {
956
- key: 'ON_OR_AFTER',
957
- appliesTo: ['DATE', 'DATETIME'],
958
- valueArity: 'ONE',
959
- explanationText: 'is on or after',
960
- canonicalQueryText: '>=',
961
- tsPredicate: (fieldValue, condition) =>
962
- compareSheetRegionFilterTemporal(fieldValue, condition, (a, b) => a >= b),
963
- sqlPredicate: (exprs, condition, kind, bind) =>
964
- getSheetRegionFilterTemporalSQL(exprs, condition, kind, bind, '>='),
965
- },
966
- CONTAINS_ANY: {
967
- key: 'CONTAINS_ANY',
968
- appliesTo: ['MULTI_SELECT'],
969
- valueArity: 'MANY',
970
- explanationText: 'contains any of',
971
- canonicalQueryText: 'CONTAINS_ANY',
972
- tsPredicate: (fieldValue, condition) =>
973
- (condition.textValues || []).some((value) =>
974
- (fieldValue.elements || []).includes(String(value)),
975
- ),
976
- sqlPredicate: (exprs, condition, _kind, bind) => {
977
- if (!exprs.jsonbExpr) {
978
- throw new Error('20077');
979
- }
980
-
981
- return `${exprs.jsonbExpr} ?| ${bind(condition.textValues || [])}::text[]`;
982
- },
983
- },
984
- };
985
-
986
- /*
987
- * Return whether a filter operator is compatible with one dataTable field type.
988
- * Reproduces the exact historical truth table (IS_EMPTY is unconditionally
989
- * allowed, even for unknown field types).
990
- */
991
- export function isSheetRegionFilterOperatorCompatible(
992
- operator: SheetRegionSourceFilterOperatorEnum,
993
- fieldType: DataTableFieldTypeEnum | null | undefined,
994
- ) {
995
- if (operator === 'IS_EMPTY') {
996
- return true;
997
- }
998
-
999
- const def = SHEET_REGION_FILTER_OPERATOR_DEFS[operator];
1000
- const kind = getSheetRegionFilterFieldKind(fieldType);
1001
- if (!def || !kind) {
1002
- return false;
1003
- }
1004
-
1005
- return def.appliesTo.includes(kind);
1006
- }
1007
-
1008
- /*
1009
- * Return the operator names accepted as bare keyword tokens by the filter
1010
- * query DSL (def-table keys MINUS the explicit exclusion set; IS EMPTY is a
1011
- * two-word phrase, never a keyword token).
1012
- */
1013
- export function getSheetRegionFilterOperatorKeywords() {
1014
- return (
1015
- Object.keys(
1016
- SHEET_REGION_FILTER_OPERATOR_DEFS,
1017
- ) as SheetRegionSourceFilterOperatorEnum[]
1018
- ).filter(
1019
- (operator) => !FILE_CONSTANTS.keywordExcludedOperators.includes(operator),
1020
- );
1021
- }
1022
-
1023
- /*
1024
- * Return the keyword-token → operator lookup for the filter query DSL parser.
1025
- */
1026
- export function getSheetRegionFilterOperatorByKeyword() {
1027
- const operatorByKeyword: Record<
1028
- string,
1029
- SheetRegionSourceFilterOperatorEnum | undefined
1030
- > = {};
1031
- getSheetRegionFilterOperatorKeywords().forEach((operator) => {
1032
- operatorByKeyword[operator] = operator;
1033
- });
1034
-
1035
- return operatorByKeyword;
1036
- }
1037
-
1038
- /*
1039
- * Return one string filter value normalized against dataTable option labels
1040
- * when possible (server semantics: any cell with options maps a value/label
1041
- * match to the canonical option value; resolves DV-4), or null when empty.
1042
- */
1043
- export function normalizeSheetRegionFilterTextValue(
1044
- cell: SheetRegionFilterDesignCell,
1045
- value: unknown,
1046
- ) {
1047
- const optionMatch = (cell.options || []).find((option) => {
1048
- const normalizedValue = String(value ?? '').toLowerCase();
1049
- return (
1050
- String(option.value).toLowerCase() === normalizedValue ||
1051
- String(option.label).toLowerCase() === normalizedValue
1052
- );
1053
- });
1054
- const normalizedValue = optionMatch
1055
- ? optionMatch.value
1056
- : normalizeDataTableSelectOptionValue(
1057
- cell as DataTableDesignCellObj,
1058
- value as DataTableRecordValue,
1059
- );
1060
- const text = String(normalizedValue ?? '').trim();
1061
-
1062
- return text || null;
1063
- }
1064
-
1065
- /*
1066
- * Return a non-empty list of normalized string filter values, or null when
1067
- * the input is not a non-empty list of normalizable values.
1068
- */
1069
- export function normalizeSheetRegionFilterTextValues(
1070
- cell: SheetRegionFilterDesignCell,
1071
- values: unknown,
1072
- ) {
1073
- if (!Array.isArray(values) || !values.length) {
1074
- return null;
1075
- }
1076
-
1077
- const normalizedValues = values.map((value) =>
1078
- normalizeSheetRegionFilterTextValue(cell, value),
1079
- );
1080
- if (normalizedValues.some((value) => value === null)) {
1081
- return null;
1082
- }
1083
-
1084
- return normalizedValues as string[];
1085
- }
1086
-
1087
- /*
1088
- * Return one finite number filter value, or null.
1089
- */
1090
- export function normalizeSheetRegionFilterNumberValue(value: unknown) {
1091
- const numberValue = Number(value);
1092
-
1093
- return Number.isFinite(numberValue) ? numberValue : null;
1094
- }
1095
-
1096
- /*
1097
- * Return one normalized date filter value for a date-like field, or null.
1098
- */
1099
- export function normalizeSheetRegionFilterDateValue(
1100
- fieldType: DataTableFieldTypeEnum,
1101
- value: unknown,
1102
- timeZone?: string | null,
1103
- ) {
1104
- try {
1105
- return (
1106
- normalizeDataTableDateLikeValue(
1107
- value as DataTableRecordValue,
1108
- fieldType,
1109
- timeZone,
1110
- ) || null
1111
- );
1112
- } catch (_error) {
1113
- return null;
1114
- }
1115
- }
1116
-
1117
- /*
1118
- * Return one normalized ISO datetime filter value, or null.
1119
- */
1120
- export function normalizeSheetRegionFilterDateTimeValue(
1121
- value: unknown,
1122
- timeZone?: string | null,
1123
- ) {
1124
- try {
1125
- return (
1126
- normalizeDataTableDateTimeValue(
1127
- value as DataTableRecordValue,
1128
- timeZone,
1129
- ) || null
1130
- );
1131
- } catch (_error) {
1132
- return null;
1133
- }
1134
- }
1135
-
1136
- /*
1137
- * Return whether one filter value is an explicit date-only literal.
1138
- */
1139
- export function isSheetRegionFilterDateOnlyValue(value: unknown) {
1140
- return (
1141
- typeof value === 'string' &&
1142
- FILE_CONSTANTS.dateOnlyPattern.test(value.trim())
1143
- );
1144
- }
1145
-
1146
- /*
1147
- * Return one boolean filter value, or null.
1148
- */
1149
- export function normalizeSheetRegionFilterBooleanValue(value: unknown) {
1150
- return typeof value === 'boolean' ? value : null;
1151
- }
1152
-
1153
- /*
1154
- * Evaluate one filter condition against a typed comparable in memory.
1155
- * Returns null when the condition cannot be evaluated without SQL (unknown
1156
- * operator, ID conditions that need related-table lookups, or SQL-only
1157
- * comparables whose text-timestamp coercion depends on the DB session
1158
- * timezone — DV-9).
1159
- */
1160
- export function evaluateSheetRegionSourceFilterCondition(
1161
- condition: SheetRegionSourceFilterConditionObj,
1162
- fieldValue: SheetRegionFilterComparableValue | null | undefined,
1163
- ): boolean | null {
1164
- const def = SHEET_REGION_FILTER_OPERATOR_DEFS[condition.operator];
1165
- if (!def || !fieldValue) {
1166
- return null;
1167
- }
1168
-
1169
- const conditionFieldType =
1170
- (condition as SheetRegionFilterConditionWithFieldType).fieldType || null;
1171
- if (def.requiresSQLForFieldType?.(conditionFieldType)) {
1172
- return null;
1173
- }
1174
-
1175
- // DV-9: comparables whose SQL coercion depends on the DB session timezone
1176
- // cannot be mirrored in memory. Only IS_EMPTY (valueArity NONE) stays
1177
- // decidable — it reads raw storage emptiness — and only when the storage
1178
- // flag is present.
1179
- if (
1180
- fieldValue.sqlOnly &&
1181
- (def.valueArity !== 'NONE' ||
1182
- typeof fieldValue.storageNonEmpty !== 'boolean')
1183
- ) {
1184
- return null;
1185
- }
1186
-
1187
- return def.tsPredicate(fieldValue, condition);
1188
- }
1189
-
1190
- /*
1191
- * Evaluate one filter group tree in memory with three-valued results
1192
- * (null = cannot decide without SQL) mirroring the SQL group recursion:
1193
- * empty groups impose no constraint and are skipped entirely.
1194
- */
1195
- function evaluateSheetRegionSourceFilterGroupInternal(
1196
- filter: SheetRegionSourceFilterGroupObj,
1197
- getComparable: (
1198
- condition: SheetRegionSourceFilterConditionObj,
1199
- ) => SheetRegionFilterComparableValue | null,
1200
- ): boolean | null | undefined {
1201
- const results: Array<boolean | null> = (filter.conditions || []).map(
1202
- (condition) =>
1203
- evaluateSheetRegionSourceFilterCondition(
1204
- condition,
1205
- getComparable(condition),
1206
- ),
1207
- );
1208
-
1209
- (filter.groups || []).forEach((childGroup) => {
1210
- const childResult = evaluateSheetRegionSourceFilterGroupInternal(
1211
- childGroup,
1212
- getComparable,
1213
- );
1214
- if (childResult !== undefined) {
1215
- results.push(childResult);
1216
- }
1217
- });
1218
-
1219
- if (!results.length) {
1220
- return undefined;
1221
- }
1222
-
1223
- if (filter.combinator === 'OR') {
1224
- if (results.some((result) => result === true)) {
1225
- return true;
1226
- }
1227
-
1228
- return results.some((result) => result === null) ? null : false;
1229
- }
1230
-
1231
- if (results.some((result) => result === false)) {
1232
- return false;
1233
- }
1234
-
1235
- return results.some((result) => result === null) ? null : true;
1236
- }
1237
-
1238
- /*
1239
- * Evaluate one region source filter in memory. Returns true for a match,
1240
- * false for a definite non-match, and null when the filter needs SQL
1241
- * (three-valued: never treat null as false — it means "cannot decide here").
1242
- */
1243
- export function evaluateSheetRegionSourceFilterGroup(
1244
- filter: SheetRegionSourceFilterGroupObj | null | undefined,
1245
- getComparable: (
1246
- condition: SheetRegionSourceFilterConditionObj,
1247
- ) => SheetRegionFilterComparableValue | null,
1248
- ): boolean | null {
1249
- if (!filter) {
1250
- return true;
1251
- }
1252
-
1253
- const result = evaluateSheetRegionSourceFilterGroupInternal(
1254
- filter,
1255
- getComparable,
1256
- );
1257
-
1258
- return result === undefined ? true : result;
1259
- }