rez_core 5.0.155 → 5.0.157

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 (88) hide show
  1. package/dist/config/bull.config.js +4 -4
  2. package/dist/config/bull.config.js.map +1 -1
  3. package/dist/config/database.config.js +1 -1
  4. package/dist/config/database.config.js.map +1 -1
  5. package/dist/core.module.js +5 -2
  6. package/dist/core.module.js.map +1 -1
  7. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.d.ts +6 -0
  8. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js +32 -0
  9. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js.map +1 -0
  10. package/dist/module/entity_json/controller/entity_json.controller.d.ts +2 -9
  11. package/dist/module/entity_json/entity/entityJson.entity.d.ts +2 -1
  12. package/dist/module/entity_json/entity/entityJson.entity.js +5 -1
  13. package/dist/module/entity_json/entity/entityJson.entity.js.map +1 -1
  14. package/dist/module/entity_json/entity_json.module.js +7 -2
  15. package/dist/module/entity_json/entity_json.module.js.map +1 -1
  16. package/dist/module/entity_json/service/entity_json.service.d.ts +2 -10
  17. package/dist/module/entity_json/service/entity_json.service.js +54 -4
  18. package/dist/module/entity_json/service/entity_json.service.js.map +1 -1
  19. package/dist/module/filter/controller/filter.controller.d.ts +12 -0
  20. package/dist/module/filter/controller/filter.controller.js +1 -1
  21. package/dist/module/filter/controller/filter.controller.js.map +1 -1
  22. package/dist/module/filter/entity/saved-filter-master.entity.d.ts +1 -2
  23. package/dist/module/filter/entity/saved-filter-master.entity.js +2 -6
  24. package/dist/module/filter/entity/saved-filter-master.entity.js.map +1 -1
  25. package/dist/module/filter/filter.module.js +11 -2
  26. package/dist/module/filter/filter.module.js.map +1 -1
  27. package/dist/module/filter/repository/saved-filter.repository.d.ts +5 -1
  28. package/dist/module/filter/repository/saved-filter.repository.js +5 -1
  29. package/dist/module/filter/repository/saved-filter.repository.js.map +1 -1
  30. package/dist/module/filter/service/filter.service.d.ts +37 -1
  31. package/dist/module/filter/service/filter.service.js +31 -43
  32. package/dist/module/filter/service/filter.service.js.map +1 -1
  33. package/dist/module/filter/service/flatjson-filter.service.d.ts +32 -0
  34. package/dist/module/filter/service/flatjson-filter.service.js +626 -0
  35. package/dist/module/filter/service/flatjson-filter.service.js.map +1 -0
  36. package/dist/module/integration/service/wrapper.service.d.ts +1 -3
  37. package/dist/module/integration/service/wrapper.service.js +2 -24
  38. package/dist/module/integration/service/wrapper.service.js.map +1 -1
  39. package/dist/module/linked_attributes/controller/linked_attributes.controller.d.ts +19 -0
  40. package/dist/module/linked_attributes/controller/linked_attributes.controller.js +77 -0
  41. package/dist/module/linked_attributes/controller/linked_attributes.controller.js.map +1 -1
  42. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.d.ts +13 -0
  43. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js +64 -0
  44. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js.map +1 -0
  45. package/dist/module/linked_attributes/linked_attributes.module.js +8 -1
  46. package/dist/module/linked_attributes/linked_attributes.module.js.map +1 -1
  47. package/dist/module/linked_attributes/service/linked_attributes.service.d.ts +41 -1
  48. package/dist/module/linked_attributes/service/linked_attributes.service.js +266 -2
  49. package/dist/module/linked_attributes/service/linked_attributes.service.js.map +1 -1
  50. package/dist/module/meta/dto/entity-table.dto.d.ts +4 -1
  51. package/dist/module/meta/dto/entity-table.dto.js.map +1 -1
  52. package/dist/module/meta/service/media-data.service.js +5 -18
  53. package/dist/module/meta/service/media-data.service.js.map +1 -1
  54. package/dist/module/workflow/service/action.service.js +10 -2
  55. package/dist/module/workflow/service/action.service.js.map +1 -1
  56. package/dist/module/workflow/service/task.service.js +5 -4
  57. package/dist/module/workflow/service/task.service.js.map +1 -1
  58. package/dist/table.config.d.ts +3 -1
  59. package/dist/table.config.js +2 -0
  60. package/dist/table.config.js.map +1 -1
  61. package/dist/tsconfig.build.tsbuildinfo +1 -1
  62. package/package.json +1 -1
  63. package/src/config/bull.config.ts +4 -4
  64. package/src/config/database.config.ts +1 -1
  65. package/src/core.module.ts +5 -2
  66. package/src/migrations/1732612800000-AddEntityJsonGinIndex.ts +41 -0
  67. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2804 -0
  68. package/src/module/entity_json/entity/entityJson.entity.ts +4 -1
  69. package/src/module/entity_json/entity_json.module.ts +8 -3
  70. package/src/module/entity_json/service/entity_json.service.ts +139 -32
  71. package/src/module/filter/controller/filter.controller.ts +1 -3
  72. package/src/module/filter/entity/saved-filter-master.entity.ts +2 -5
  73. package/src/module/filter/filter.module.ts +11 -2
  74. package/src/module/filter/repository/saved-filter.repository.ts +5 -9
  75. package/src/module/filter/service/filter.service.ts +115 -67
  76. package/src/module/filter/service/flatjson-filter.service.ts +902 -0
  77. package/src/module/filter/test/flatjson-filter.service.spec.ts +415 -0
  78. package/src/module/integration/service/wrapper.service.ts +0 -37
  79. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +86 -0
  80. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -0
  81. package/src/module/linked_attributes/linked_attributes.module.ts +9 -2
  82. package/src/module/linked_attributes/service/linked_attributes.service.ts +548 -3
  83. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -0
  84. package/src/module/meta/dto/entity-table.dto.ts +1 -3
  85. package/src/module/meta/service/media-data.service.ts +9 -27
  86. package/src/module/workflow/service/action.service.ts +10 -6
  87. package/src/module/workflow/service/task.service.ts +13 -14
  88. package/src/table.config.ts +2 -0
@@ -0,0 +1,902 @@
1
+ import { Injectable, BadRequestException, Inject, forwardRef } from '@nestjs/common';
2
+ import { EntityManager, SelectQueryBuilder } from 'typeorm';
3
+ import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
4
+ import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
5
+ import { ResolverService } from 'src/module/meta/service/resolver.service';
6
+ import { LoggingService } from 'src/utils/service/loggingUtil.service';
7
+ import { ConfigService } from '@nestjs/config';
8
+ import {
9
+ FilterRequestDto,
10
+ FilterCondition,
11
+ SortConfig,
12
+ } from '../dto/filter-request.dto';
13
+ import { EntityJson } from 'src/module/entity_json/entity/entityJson.entity';
14
+ import { SavedFilterRepositoryService } from '../repository/saved-filter.repository';
15
+ import { EntityJSONService } from 'src/module/entity_json/service/entity_json.service';
16
+
17
+ /**
18
+ * JSONB query condition structure
19
+ */
20
+ interface JsonbCondition {
21
+ query: string;
22
+ params: Record<string, any>;
23
+ }
24
+
25
+ @Injectable()
26
+ export class FlatjsonFilterService {
27
+ constructor(
28
+ private readonly entityManager: EntityManager,
29
+ private readonly entityMasterService: EntityMasterService,
30
+ private readonly attributeMasterService: AttributeMasterService,
31
+ private readonly resolverService: ResolverService,
32
+ private readonly loggingService: LoggingService,
33
+ private readonly configService: ConfigService,
34
+ private readonly savedFilterRepositoryService: SavedFilterRepositoryService,
35
+ @Inject(forwardRef(() => EntityJSONService))
36
+ private readonly entityJsonService: EntityJSONService,
37
+ ) {}
38
+
39
+ /**
40
+ * Main filtering method - queries frm_entity_json table
41
+ */
42
+ async applyFlatjsonFilter(dto: FilterRequestDto): Promise<any> {
43
+ const {
44
+ entity_type,
45
+ quickFilter = [],
46
+ savedFilterCode,
47
+ attributeFilter = [],
48
+ sortby = [],
49
+ tabs,
50
+ page = 1,
51
+ size = 20,
52
+ loggedInUser,
53
+ } = dto;
54
+
55
+ await this.loggingService.log(
56
+ 'info',
57
+ 'FlatjsonFilterService',
58
+ 'applyFlatjsonFilter',
59
+ `Filtering entity: ${entity_type}`,
60
+ );
61
+
62
+ // Step 1: Load attribute metadata for this entity
63
+ let attributes =
64
+ await this.entityJsonService.getAttributeForFlatJSON(
65
+ entity_type,
66
+ loggedInUser,
67
+ 'filter_attribute',
68
+ );
69
+
70
+ if (!attributes?.length) {
71
+ attributes =
72
+ await this.attributeMasterService.findAttributesByMappedEntityType(
73
+ entity_type,
74
+ loggedInUser,
75
+ );
76
+ }
77
+
78
+ attributes = attributes ?? [];
79
+
80
+ const attributeMetaMap: Record<string, any> = {};
81
+ attributes.forEach((attr) => {
82
+ attributeMetaMap[attr.flat_json_key] = attr;
83
+ });
84
+
85
+ await this.loggingService.log(
86
+ 'debug',
87
+ 'FlatjsonFilterService',
88
+ 'applyFlatjsonFilter',
89
+ `Loaded ${attributes.length} attributes`,
90
+ );
91
+
92
+ // Step 2: Merge filters (quickFilter + savedFilter + attributeFilter)
93
+ let allFilters: FilterCondition[] = [...quickFilter, ...attributeFilter];
94
+
95
+ if (savedFilterCode) {
96
+ const savedFilterDetails =
97
+ await this.savedFilterRepositoryService.getDetailsByCode(
98
+ savedFilterCode,
99
+ );
100
+ allFilters = [...allFilters, ...savedFilterDetails];
101
+ }
102
+
103
+ await this.loggingService.log(
104
+ 'debug',
105
+ 'FlatjsonFilterService',
106
+ 'applyFlatjsonFilter',
107
+ `Total filters: ${allFilters.length}`,
108
+ );
109
+
110
+ // Step 3: Build JSONB conditions
111
+ const jsonbConditions = this.buildJsonbConditions(
112
+ allFilters,
113
+ attributeMetaMap,
114
+ );
115
+
116
+ // Step 4: Build base query
117
+ const qb = this.entityManager
118
+ .getRepository(EntityJson)
119
+ .createQueryBuilder('ej')
120
+ .where('ej.entity_type = :entity_type', { entity_type })
121
+ .andWhere('ej.organization_id = :orgId', {
122
+ orgId: loggedInUser.organization_id,
123
+ });
124
+
125
+ // Step 5: Apply JSONB conditions
126
+ jsonbConditions.forEach((condition, index) => {
127
+ qb.andWhere(condition.query, condition.params);
128
+ });
129
+
130
+ // Step 6: Apply tab filter if provided
131
+ if (tabs?.columnName && tabs?.value) {
132
+ const tabMeta = attributeMetaMap[tabs.columnName];
133
+ if (tabMeta) {
134
+ const flatJsonKey =
135
+ tabMeta.flat_json_key ||
136
+ `${entity_type}__${tabs.columnName}`;
137
+ qb.andWhere(`json_data->>'${flatJsonKey}' = :tabValue`, {
138
+ tabValue: tabs.value,
139
+ });
140
+ }
141
+ }
142
+
143
+ // Step 7: Get tab counts if needed (before pagination)
144
+ let tabCounts: any[] = [];
145
+ if (tabs?.columnName && !tabs?.value) {
146
+ const tabMeta = attributeMetaMap[tabs.columnName];
147
+ if (tabMeta) {
148
+ const flatJsonKey =
149
+ tabMeta.flat_json_key ||
150
+ `${entity_type}__${tabs.columnName}`;
151
+ tabCounts = await this.getJsonbTabCounts(
152
+ entity_type,
153
+ flatJsonKey,
154
+ jsonbConditions,
155
+ );
156
+ }
157
+ }
158
+
159
+ // Step 8: Apply sorting
160
+ if (sortby && sortby.length > 0) {
161
+ this.applyJsonbSorting(qb, sortby, attributeMetaMap);
162
+ } else {
163
+ // Default sort by created_date DESC
164
+ qb.orderBy('ej.created_at', 'DESC');
165
+ }
166
+
167
+ // Step 9: Get total count (before pagination)
168
+ const totalCount = await qb.getCount();
169
+
170
+ // Step 10: Apply pagination
171
+ if (page && size) {
172
+ const skip = (page - 1) * size;
173
+ qb.skip(skip).take(size);
174
+ }
175
+
176
+ // Step 11: Execute query
177
+ const results = await qb.getMany();
178
+
179
+ await this.loggingService.log(
180
+ 'info',
181
+ 'FlatjsonFilterService',
182
+ 'applyFlatjsonFilter',
183
+ `Found ${totalCount} total, returning ${results.length} records`,
184
+ );
185
+
186
+ // // Step 12: Resolve entity IDs to full entity data
187
+ // const resolvedData = await this.resolveEntityData(
188
+ // results,
189
+ // entity_type,
190
+ // loggedInUser,
191
+ // );
192
+
193
+ return {
194
+ data: results,
195
+ total: totalCount,
196
+ page: page || 1,
197
+ size: size || 20,
198
+ totalPages: size ? Math.ceil(totalCount / size) : 1,
199
+ tabCounts: tabCounts.length > 0 ? tabCounts : undefined,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Build JSONB where clauses from filter conditions
205
+ */
206
+ private buildJsonbConditions(
207
+ filters: FilterCondition[],
208
+ attributeMetaMap: Record<string, any>,
209
+ ): JsonbCondition[] {
210
+ const conditions: JsonbCondition[] = [];
211
+
212
+ for (const filter of filters) {
213
+ const meta = attributeMetaMap[filter.filter_attribute];
214
+ const condition = this.buildJsonbCondition(filter, meta);
215
+
216
+ if (condition) {
217
+ conditions.push(condition);
218
+ } else {
219
+ console.warn(
220
+ `Could not build condition for filter: ${filter.filter_attribute}`,
221
+ );
222
+ }
223
+ }
224
+
225
+ return conditions;
226
+ }
227
+
228
+ /**
229
+ * Resolve entity IDs to full entity data
230
+ */
231
+ private async resolveEntityData(
232
+ entityJsonRecords: EntityJson[],
233
+ entity_type: string,
234
+ loggedInUser: any,
235
+ ): Promise<any[]> {
236
+ if (entityJsonRecords.length === 0) return [];
237
+
238
+ const entityIds = entityJsonRecords.map((ej) => ej.entity_id);
239
+
240
+ try {
241
+ // Use resolver service to get full entity data
242
+ const fullEntities = await this.resolverService.getResolvedData(
243
+ entity_type,
244
+ entityIds,
245
+ loggedInUser,
246
+ );
247
+
248
+ // Return with json_data merged
249
+ return entityJsonRecords.map((ej) => {
250
+ const fullEntity = fullEntities.find((e) => e.id === ej.entity_id);
251
+ return {
252
+ ...fullEntity,
253
+ _flatjson: ej.json_data, // Include flatjson for debugging
254
+ };
255
+ });
256
+ } catch (error) {
257
+ console.error('Error resolving entity data:', error);
258
+ // Fallback: return just the entity IDs with json_data
259
+ return entityJsonRecords.map((ej) => ({
260
+ id: ej.entity_id,
261
+ entity_type: ej.entity_type,
262
+ ...ej.json_data,
263
+ }));
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Build a single JSONB condition based on data type
269
+ */
270
+ private buildJsonbCondition(
271
+ filter: FilterCondition,
272
+ meta: any,
273
+ ): JsonbCondition | null {
274
+ if (!meta) return null;
275
+
276
+ const flatJsonKey =
277
+ meta.flat_json_key ||
278
+ `${meta.mapped_entity_type}__${filter.filter_attribute}`;
279
+ const op = filter.filter_operator;
280
+ const val = filter.filter_value;
281
+ const key = `param_${filter.filter_attribute}_${Math.random().toString(36).substring(2, 8)}`;
282
+
283
+ switch (meta.data_type) {
284
+ case 'text':
285
+ return this.buildTextCondition(flatJsonKey, op, val, key);
286
+ case 'number':
287
+ return this.buildNumberCondition(flatJsonKey, op, val, key);
288
+ case 'date':
289
+ return this.buildDateCondition(flatJsonKey, op, val, key);
290
+ case 'select':
291
+ case 'radio':
292
+ return this.buildSelectCondition(flatJsonKey, op, val, key);
293
+ case 'multiselect':
294
+ case 'checkbox':
295
+ return this.buildMultiSelectCondition(flatJsonKey, op, val, key);
296
+ case 'year':
297
+ return this.buildYearCondition(flatJsonKey, op, val, key);
298
+ default:
299
+ return null;
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Build text condition (JSONB ->> operator)
305
+ */
306
+ private buildTextCondition(
307
+ flatJsonKey: string,
308
+ operator: string,
309
+ value: any,
310
+ paramKey: string,
311
+ ): JsonbCondition | null {
312
+ // Text is already stored lowercase in flatjson
313
+ const lowerValue = value ? String(value).toLowerCase() : '';
314
+
315
+ switch (operator) {
316
+ case 'equal':
317
+ return {
318
+ query: `json_data->>'${flatJsonKey}' = :${paramKey}`,
319
+ params: { [paramKey]: lowerValue },
320
+ };
321
+
322
+ case 'not_equal':
323
+ return {
324
+ query: `json_data->>'${flatJsonKey}' != :${paramKey}`,
325
+ params: { [paramKey]: lowerValue },
326
+ };
327
+
328
+ case 'contains':
329
+ return {
330
+ query: `json_data->>'${flatJsonKey}' LIKE :${paramKey}`,
331
+ params: { [paramKey]: `%${lowerValue}%` },
332
+ };
333
+
334
+ case 'not_contains':
335
+ return {
336
+ query: `json_data->>'${flatJsonKey}' NOT LIKE :${paramKey}`,
337
+ params: { [paramKey]: `%${lowerValue}%` },
338
+ };
339
+
340
+ case 'starts_with':
341
+ return {
342
+ query: `json_data->>'${flatJsonKey}' LIKE :${paramKey}`,
343
+ params: { [paramKey]: `${lowerValue}%` },
344
+ };
345
+
346
+ case 'ends_with':
347
+ return {
348
+ query: `json_data->>'${flatJsonKey}' LIKE :${paramKey}`,
349
+ params: { [paramKey]: `%${lowerValue}` },
350
+ };
351
+
352
+ case 'empty':
353
+ return {
354
+ query: `(json_data->>'${flatJsonKey}' IS NULL OR json_data->>'${flatJsonKey}' = '')`,
355
+ params: {},
356
+ };
357
+
358
+ case 'not_empty':
359
+ return {
360
+ query: `(json_data->>'${flatJsonKey}' IS NOT NULL AND json_data->>'${flatJsonKey}' != '')`,
361
+ params: {},
362
+ };
363
+
364
+ default:
365
+ console.warn(`Unsupported text operator: ${operator}`);
366
+ return null;
367
+ }
368
+ }
369
+
370
+ /**
371
+ * Build number condition (JSONB ->> with ::numeric cast)
372
+ */
373
+ private buildNumberCondition(
374
+ flatJsonKey: string,
375
+ operator: string,
376
+ value: any,
377
+ paramKey: string,
378
+ ): JsonbCondition | null {
379
+ // Cast JSONB text to numeric for comparison
380
+ const jsonbField = `(json_data->>'${flatJsonKey}')::numeric`;
381
+
382
+ switch (operator) {
383
+ case 'equal':
384
+ return {
385
+ query: `${jsonbField} = :${paramKey}`,
386
+ params: { [paramKey]: Number(value) },
387
+ };
388
+
389
+ case 'not_equal':
390
+ return {
391
+ query: `${jsonbField} != :${paramKey}`,
392
+ params: { [paramKey]: Number(value) },
393
+ };
394
+
395
+ case 'greater_than':
396
+ return {
397
+ query: `${jsonbField} > :${paramKey}`,
398
+ params: { [paramKey]: Number(value) },
399
+ };
400
+
401
+ case 'less_than':
402
+ return {
403
+ query: `${jsonbField} < :${paramKey}`,
404
+ params: { [paramKey]: Number(value) },
405
+ };
406
+
407
+ case 'greater_than_equal_to':
408
+ return {
409
+ query: `${jsonbField} >= :${paramKey}`,
410
+ params: { [paramKey]: Number(value) },
411
+ };
412
+
413
+ case 'less_than_equal_to':
414
+ return {
415
+ query: `${jsonbField} <= :${paramKey}`,
416
+ params: { [paramKey]: Number(value) },
417
+ };
418
+
419
+ case 'between': {
420
+ // Value should be array [min, max] or string "min,max"
421
+ let range: number[];
422
+ if (typeof value === 'string') {
423
+ range = value.split(',').map((v) => Number(v.trim()));
424
+ } else if (Array.isArray(value)) {
425
+ range = value.map((v) => Number(v));
426
+ } else {
427
+ return null;
428
+ }
429
+
430
+ if (range.length !== 2) return null;
431
+
432
+ return {
433
+ query: `${jsonbField} BETWEEN :${paramKey}_min AND :${paramKey}_max`,
434
+ params: {
435
+ [`${paramKey}_min`]: range[0],
436
+ [`${paramKey}_max`]: range[1],
437
+ },
438
+ };
439
+ }
440
+
441
+ case 'empty':
442
+ return {
443
+ query: `json_data->>'${flatJsonKey}' IS NULL`,
444
+ params: {},
445
+ };
446
+
447
+ case 'not_empty':
448
+ return {
449
+ query: `json_data->>'${flatJsonKey}' IS NOT NULL`,
450
+ params: {},
451
+ };
452
+
453
+ default:
454
+ console.warn(`Unsupported number operator: ${operator}`);
455
+ return null;
456
+ }
457
+ }
458
+
459
+ /**
460
+ * Build date condition (JSONB ->> with ::bigint cast for epoch ms)
461
+ */
462
+ private buildDateCondition(
463
+ flatJsonKey: string,
464
+ operator: string,
465
+ value: any,
466
+ paramKey: string,
467
+ ): JsonbCondition | null {
468
+ // Dates stored as epoch milliseconds (bigint)
469
+ const jsonbField = `(json_data->>'${flatJsonKey}')::bigint`;
470
+
471
+ // Helper: Convert date string to epoch ms
472
+ const toEpochMs = (dateStr: string): number => {
473
+ return new Date(dateStr).getTime();
474
+ };
475
+
476
+ // Helper: Get date N days ago
477
+ const daysAgo = (days: number): number => {
478
+ const d = new Date();
479
+ d.setDate(d.getDate() - days);
480
+ return d.getTime();
481
+ };
482
+
483
+ // Helper: Get date N days from now
484
+ const daysFromNow = (days: number): number => {
485
+ const d = new Date();
486
+ d.setDate(d.getDate() + days);
487
+ return d.getTime();
488
+ };
489
+
490
+ // Helper: Subtract business days (skip weekends)
491
+ const subtractBusinessDays = (days: number): number => {
492
+ let d = new Date();
493
+ let count = 0;
494
+
495
+ while (count < days) {
496
+ d.setDate(d.getDate() - 1);
497
+ const day = d.getDay(); // 0=Sun, 6=Sat
498
+ if (day !== 0 && day !== 6) {
499
+ count++;
500
+ }
501
+ }
502
+
503
+ return d.getTime();
504
+ };
505
+
506
+ const numVal = Number(value);
507
+
508
+ switch (operator) {
509
+ // Basic comparisons
510
+ case 'equal':
511
+ case 'is':
512
+ return {
513
+ query: `${jsonbField} = :${paramKey}`,
514
+ params: { [paramKey]: toEpochMs(value) },
515
+ };
516
+
517
+ case 'before':
518
+ case 'is_before':
519
+ return {
520
+ query: `${jsonbField} < :${paramKey}`,
521
+ params: { [paramKey]: toEpochMs(value) },
522
+ };
523
+
524
+ case 'after':
525
+ case 'is_after':
526
+ return {
527
+ query: `${jsonbField} > :${paramKey}`,
528
+ params: { [paramKey]: toEpochMs(value) },
529
+ };
530
+
531
+ case 'is_on_or_before':
532
+ return {
533
+ query: `${jsonbField} <= :${paramKey}`,
534
+ params: { [paramKey]: toEpochMs(value) },
535
+ };
536
+
537
+ case 'is_on_or_after':
538
+ return {
539
+ query: `${jsonbField} >= :${paramKey}`,
540
+ params: { [paramKey]: toEpochMs(value) },
541
+ };
542
+
543
+ // Day offset logic
544
+ case 'is_day_before':
545
+ if (isNaN(numVal)) return null;
546
+ return {
547
+ query: `${jsonbField} <= :${paramKey}`,
548
+ params: { [paramKey]: daysAgo(numVal) },
549
+ };
550
+
551
+ case 'is_day_after':
552
+ if (isNaN(numVal)) return null;
553
+ return {
554
+ query: `${jsonbField} >= :${paramKey}`,
555
+ params: { [paramKey]: daysFromNow(numVal) },
556
+ };
557
+
558
+ // Business days (skip weekends)
559
+ case 'is_before_business_days':
560
+ if (isNaN(numVal)) return null;
561
+ return {
562
+ query: `${jsonbField} <= :${paramKey}`,
563
+ params: { [paramKey]: subtractBusinessDays(numVal) },
564
+ };
565
+
566
+ // Range operators
567
+ case 'between': {
568
+ let range: string[];
569
+ if (typeof value === 'string') {
570
+ range = value.split(',').map((v) => v.trim());
571
+ } else if (Array.isArray(value)) {
572
+ range = value;
573
+ } else {
574
+ return null;
575
+ }
576
+
577
+ if (range.length !== 2) return null;
578
+
579
+ return {
580
+ query: `${jsonbField} BETWEEN :${paramKey}_start AND :${paramKey}_end`,
581
+ params: {
582
+ [`${paramKey}_start`]: toEpochMs(range[0]),
583
+ [`${paramKey}_end`]: toEpochMs(range[1]),
584
+ },
585
+ };
586
+ }
587
+
588
+ case 'in_last_day':
589
+ if (isNaN(numVal)) return null;
590
+ return {
591
+ query: `${jsonbField} BETWEEN :${paramKey}_start AND :${paramKey}_end`,
592
+ params: {
593
+ [`${paramKey}_start`]: daysAgo(numVal),
594
+ [`${paramKey}_end`]: Date.now(),
595
+ },
596
+ };
597
+
598
+ case 'in_next_day':
599
+ if (isNaN(numVal)) return null;
600
+ return {
601
+ query: `${jsonbField} BETWEEN :${paramKey}_start AND :${paramKey}_end`,
602
+ params: {
603
+ [`${paramKey}_start`]: Date.now(),
604
+ [`${paramKey}_end`]: daysFromNow(numVal),
605
+ },
606
+ };
607
+
608
+ // Special cases
609
+ case 'today': {
610
+ const todayStart = new Date().setHours(0, 0, 0, 0);
611
+ const todayEnd = new Date().setHours(23, 59, 59, 999);
612
+ return {
613
+ query: `${jsonbField} BETWEEN :${paramKey}_start AND :${paramKey}_end`,
614
+ params: {
615
+ [`${paramKey}_start`]: todayStart,
616
+ [`${paramKey}_end`]: todayEnd,
617
+ },
618
+ };
619
+ }
620
+
621
+ case 'empty':
622
+ return {
623
+ query: `json_data->>'${flatJsonKey}' IS NULL`,
624
+ params: {},
625
+ };
626
+
627
+ case 'not_empty':
628
+ return {
629
+ query: `json_data->>'${flatJsonKey}' IS NOT NULL`,
630
+ params: {},
631
+ };
632
+
633
+ default:
634
+ console.warn(`Unsupported date operator: ${operator}`);
635
+ return null;
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Build select condition (single value)
641
+ */
642
+ private buildSelectCondition(
643
+ flatJsonKey: string,
644
+ operator: string,
645
+ value: any,
646
+ paramKey: string,
647
+ ): JsonbCondition | null {
648
+ switch (operator) {
649
+ case 'equal':
650
+ if (Array.isArray(value)) {
651
+ // IN operator for multiple values
652
+ return {
653
+ query: `json_data->>'${flatJsonKey}' = ANY(:${paramKey})`,
654
+ params: { [paramKey]: value.map(String) },
655
+ };
656
+ }
657
+ return {
658
+ query: `json_data->>'${flatJsonKey}' = :${paramKey}`,
659
+ params: { [paramKey]: String(value) },
660
+ };
661
+
662
+ case 'not_equal':
663
+ if (Array.isArray(value)) {
664
+ // NOT IN operator
665
+ return {
666
+ query: `json_data->>'${flatJsonKey}' != ALL(:${paramKey})`,
667
+ params: { [paramKey]: value.map(String) },
668
+ };
669
+ }
670
+ return {
671
+ query: `json_data->>'${flatJsonKey}' != :${paramKey}`,
672
+ params: { [paramKey]: String(value) },
673
+ };
674
+
675
+ case 'in': {
676
+ const inValues = Array.isArray(value) ? value : [value];
677
+ return {
678
+ query: `json_data->>'${flatJsonKey}' = ANY(:${paramKey})`,
679
+ params: { [paramKey]: inValues.map(String) },
680
+ };
681
+ }
682
+
683
+ case 'not_in': {
684
+ const notInValues = Array.isArray(value) ? value : [value];
685
+ return {
686
+ query: `json_data->>'${flatJsonKey}' != ALL(:${paramKey})`,
687
+ params: { [paramKey]: notInValues.map(String) },
688
+ };
689
+ }
690
+
691
+ case 'empty':
692
+ return {
693
+ query: `json_data->>'${flatJsonKey}' IS NULL`,
694
+ params: {},
695
+ };
696
+
697
+ case 'not_empty':
698
+ return {
699
+ query: `json_data->>'${flatJsonKey}' IS NOT NULL`,
700
+ params: {},
701
+ };
702
+
703
+ default:
704
+ console.warn(`Unsupported select operator: ${operator}`);
705
+ return null;
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Build multiselect condition (JSONB -> with ? operators for arrays)
711
+ */
712
+ private buildMultiSelectCondition(
713
+ flatJsonKey: string,
714
+ operator: string,
715
+ value: any,
716
+ paramKey: string,
717
+ ): JsonbCondition | null {
718
+ // Convert value to array if not already
719
+ let arr: string[];
720
+ if (Array.isArray(value)) {
721
+ arr = value.map(String);
722
+ } else if (typeof value === 'string') {
723
+ arr = value.split(',').map((v) => v.trim());
724
+ } else {
725
+ arr = [String(value)];
726
+ }
727
+
728
+ if (arr.length === 0) {
729
+ return { query: '1=1', params: {} }; // Always true for empty array
730
+ }
731
+
732
+ switch (operator) {
733
+ case 'contains':
734
+ case 'has':
735
+ // Check if JSON array contains this element
736
+ // json_data->'LEAD__languages' ? 'hindi'
737
+ if (arr.length === 1) {
738
+ return {
739
+ query: `json_data->'${flatJsonKey}' ? :${paramKey}`,
740
+ params: { [paramKey]: arr[0] },
741
+ };
742
+ }
743
+ // For multiple values, check if contains ANY
744
+ return {
745
+ query: `json_data->'${flatJsonKey}' ?| ARRAY[:...${paramKey}]::text[]`,
746
+ params: { [paramKey]: arr },
747
+ };
748
+
749
+ case 'contains_all':
750
+ // Check if JSON array contains ALL elements
751
+ // json_data->'LEAD__languages' ?& ARRAY['hindi', 'english']
752
+ return {
753
+ query: `json_data->'${flatJsonKey}' ?& ARRAY[:...${paramKey}]::text[]`,
754
+ params: { [paramKey]: arr },
755
+ };
756
+
757
+ case 'contains_any':
758
+ // Check if JSON array contains ANY element
759
+ // json_data->'LEAD__languages' ?| ARRAY['hindi', 'english']
760
+ return {
761
+ query: `json_data->'${flatJsonKey}' ?| ARRAY[:...${paramKey}]::text[]`,
762
+ params: { [paramKey]: arr },
763
+ };
764
+
765
+ case 'not_contains':
766
+ // Check if JSON array does NOT contain element
767
+ if (arr.length === 1) {
768
+ return {
769
+ query: `NOT (json_data->'${flatJsonKey}' ? :${paramKey})`,
770
+ params: { [paramKey]: arr[0] },
771
+ };
772
+ }
773
+ return {
774
+ query: `NOT (json_data->'${flatJsonKey}' ?| ARRAY[:...${paramKey}]::text[])`,
775
+ params: { [paramKey]: arr },
776
+ };
777
+
778
+ case 'equal':
779
+ // Exact array match (order matters in PostgreSQL)
780
+ return {
781
+ query: `json_data->'${flatJsonKey}'::jsonb = :${paramKey}::jsonb`,
782
+ params: { [paramKey]: JSON.stringify(arr) },
783
+ };
784
+
785
+ case 'empty':
786
+ return {
787
+ query: `(json_data->>'${flatJsonKey}' IS NULL OR json_data->'${flatJsonKey}' = '[]'::jsonb)`,
788
+ params: {},
789
+ };
790
+
791
+ case 'not_empty':
792
+ return {
793
+ query: `(json_data->>'${flatJsonKey}' IS NOT NULL AND json_data->'${flatJsonKey}' != '[]'::jsonb)`,
794
+ params: {},
795
+ };
796
+
797
+ default:
798
+ console.warn(`Unsupported multiselect operator: ${operator}`);
799
+ return null;
800
+ }
801
+ }
802
+
803
+ /**
804
+ * Build year condition
805
+ */
806
+ private buildYearCondition(
807
+ flatJsonKey: string,
808
+ operator: string,
809
+ value: any,
810
+ paramKey: string,
811
+ ): JsonbCondition | null {
812
+ // Similar to number condition
813
+ return this.buildNumberCondition(flatJsonKey, operator, value, paramKey);
814
+ }
815
+
816
+ /**
817
+ * Get tab aggregation counts from JSONB
818
+ */
819
+ private async getJsonbTabCounts(
820
+ entity_type: string,
821
+ flatJsonKey: string,
822
+ whereClauses: JsonbCondition[],
823
+ ): Promise<Array<{ tab_value: string; tab_value_count: number }>> {
824
+ // Build a query that groups by the tab field
825
+ const qb = this.entityManager
826
+ .getRepository(EntityJson)
827
+ .createQueryBuilder('ej')
828
+ .select(`json_data->>'${flatJsonKey}'`, 'tab_value')
829
+ .addSelect('COUNT(*)', 'tab_value_count')
830
+ .where('ej.entity_type = :entity_type', { entity_type })
831
+ .groupBy(`json_data->>'${flatJsonKey}'`);
832
+
833
+ // Apply the same filter conditions (but not the tab filter itself)
834
+ whereClauses.forEach((condition) => {
835
+ qb.andWhere(condition.query, condition.params);
836
+ });
837
+
838
+ const results = await qb.getRawMany();
839
+
840
+ // Filter out NULL/undefined tab values and convert count to number
841
+ return results
842
+ .filter((r) => r.tab_value != null && r.tab_value !== '')
843
+ .map((r) => ({
844
+ tab_value: r.tab_value,
845
+ tab_value_count: parseInt(r.tab_value_count, 10),
846
+ }))
847
+ .sort((a, b) => b.tab_value_count - a.tab_value_count); // Sort by count DESC
848
+ }
849
+
850
+ /**
851
+ * Apply sorting on JSONB fields
852
+ */
853
+ private applyJsonbSorting(
854
+ qb: SelectQueryBuilder<EntityJson>,
855
+ sortby: SortConfig[],
856
+ attributeMetaMap: Record<string, any>,
857
+ ): void {
858
+ sortby.forEach((sort, index) => {
859
+ const meta = attributeMetaMap[sort.sortColum];
860
+
861
+ if (!meta) {
862
+ console.warn(`No metadata found for sort column: ${sort.sortColum}`);
863
+ return;
864
+ }
865
+
866
+ const flatJsonKey =
867
+ meta.flat_json_key || `${meta.mapped_entity_type}__${sort.sortColum}`;
868
+ const direction = sort.sortType === 'ASC' ? 'ASC' : 'DESC';
869
+
870
+ // Apply type-specific casting for proper sorting
871
+ let sortExpression: string;
872
+
873
+ switch (meta.data_type) {
874
+ case 'number':
875
+ case 'year':
876
+ // Cast to numeric for number sorting
877
+ sortExpression = `(json_data->>'${flatJsonKey}')::numeric`;
878
+ break;
879
+
880
+ case 'date':
881
+ // Cast to bigint for date sorting (epoch ms)
882
+ sortExpression = `(json_data->>'${flatJsonKey}')::bigint`;
883
+ break;
884
+
885
+ case 'text':
886
+ case 'select':
887
+ case 'radio':
888
+ default:
889
+ // Text sorting (already lowercase)
890
+ sortExpression = `json_data->>'${flatJsonKey}'`;
891
+ break;
892
+ }
893
+
894
+ // Add to ORDER BY clause
895
+ if (index === 0) {
896
+ qb.orderBy(sortExpression, direction);
897
+ } else {
898
+ qb.addOrderBy(sortExpression, direction);
899
+ }
900
+ });
901
+ }
902
+ }