rez_core 5.0.211 → 6.1.1

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 (458) hide show
  1. package/.prettierrc +3 -3
  2. package/README.md +99 -99
  3. package/dist/config/database.config.js +1 -1
  4. package/dist/config/database.config.js.map +1 -1
  5. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.d.ts +6 -0
  6. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js +32 -0
  7. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js.map +1 -0
  8. package/dist/module/auth/guards/role.guard.js +3 -3
  9. package/dist/module/entity_json/controller/entity_json.controller.d.ts +2 -9
  10. package/dist/module/entity_json/controller/entity_json.controller.js.map +1 -1
  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 +5 -12
  17. package/dist/module/entity_json/service/entity_json.service.js +111 -29
  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/filter.module.js +11 -2
  23. package/dist/module/filter/filter.module.js.map +1 -1
  24. package/dist/module/filter/service/filter.service.d.ts +38 -2
  25. package/dist/module/filter/service/filter.service.js +61 -68
  26. package/dist/module/filter/service/filter.service.js.map +1 -1
  27. package/dist/module/filter/service/flatjson-filter.service.d.ts +32 -0
  28. package/dist/module/filter/service/flatjson-filter.service.js +632 -0
  29. package/dist/module/filter/service/flatjson-filter.service.js.map +1 -0
  30. package/dist/module/filter/service/saved-filter.service.d.ts +3 -2
  31. package/dist/module/filter/service/saved-filter.service.js +14 -18
  32. package/dist/module/filter/service/saved-filter.service.js.map +1 -1
  33. package/dist/module/integration/examples/usage.example.js +9 -9
  34. package/dist/module/linked_attributes/controller/linked_attributes.controller.d.ts +19 -0
  35. package/dist/module/linked_attributes/controller/linked_attributes.controller.js +77 -0
  36. package/dist/module/linked_attributes/controller/linked_attributes.controller.js.map +1 -1
  37. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.d.ts +13 -0
  38. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js +64 -0
  39. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js.map +1 -0
  40. package/dist/module/linked_attributes/linked_attributes.module.js +4 -2
  41. package/dist/module/linked_attributes/linked_attributes.module.js.map +1 -1
  42. package/dist/module/linked_attributes/service/linked_attributes.service.d.ts +41 -1
  43. package/dist/module/linked_attributes/service/linked_attributes.service.js +265 -1
  44. package/dist/module/linked_attributes/service/linked_attributes.service.js.map +1 -1
  45. package/dist/module/meta/controller/attribute-master.controller.d.ts +3 -0
  46. package/dist/module/meta/controller/attribute-master.controller.js +12 -0
  47. package/dist/module/meta/controller/attribute-master.controller.js.map +1 -1
  48. package/dist/module/meta/entity.module.js +2 -2
  49. package/dist/module/meta/entity.module.js.map +1 -1
  50. package/dist/module/meta/repository/attribute-master.repository.js +8 -8
  51. package/dist/module/meta/service/attribute-master.service.d.ts +6 -1
  52. package/dist/module/meta/service/attribute-master.service.js +20 -2
  53. package/dist/module/meta/service/attribute-master.service.js.map +1 -1
  54. package/dist/module/meta/service/entity-dynamic.service.js +16 -16
  55. package/dist/module/meta/service/entity-master.service.js +1 -0
  56. package/dist/module/meta/service/entity-master.service.js.map +1 -1
  57. package/dist/module/meta/service/entity-relation.service.d.ts +4 -3
  58. package/dist/module/meta/service/entity-relation.service.js +10 -4
  59. package/dist/module/meta/service/entity-relation.service.js.map +1 -1
  60. package/dist/module/meta/service/entity-service-impl.service.d.ts +1 -1
  61. package/dist/module/meta/service/entity-service-impl.service.js +2 -2
  62. package/dist/module/meta/service/entity-service-impl.service.js.map +1 -1
  63. package/dist/module/meta/service/entity-table.service.d.ts +5 -4
  64. package/dist/module/meta/service/entity-table.service.js +45 -24
  65. package/dist/module/meta/service/entity-table.service.js.map +1 -1
  66. package/dist/module/meta/service/media-data.service.js +6 -6
  67. package/dist/module/meta/service/resolver.service.d.ts +1 -1
  68. package/dist/module/meta/service/resolver.service.js +11 -8
  69. package/dist/module/meta/service/resolver.service.js.map +1 -1
  70. package/dist/module/module/repository/menu.repository.js +4 -4
  71. package/dist/module/user/controller/login.controller.js +18 -18
  72. package/dist/module/workflow/repository/action.repository.js +2 -2
  73. package/dist/module/workflow/repository/stage.repository.js +8 -8
  74. package/dist/module/workflow/service/action-template-mapping.service.js +2 -2
  75. package/dist/module/workflow/service/action.service.js +5 -5
  76. package/dist/module/workflow/service/entity-modification.service.js +2 -2
  77. package/dist/module/workflow/service/task.service.js +8 -8
  78. package/dist/module/workflow-automation/service/schedule-handler.service.js +9 -9
  79. package/dist/module/workflow-automation/service/workflow-automation.service.js +2 -3
  80. package/dist/module/workflow-automation/service/workflow-automation.service.js.map +1 -1
  81. package/dist/table.config.d.ts +2 -1
  82. package/dist/table.config.js +2 -0
  83. package/dist/table.config.js.map +1 -1
  84. package/dist/tsconfig.build.tsbuildinfo +1 -1
  85. package/dist/utils/service/reflection-helper.service.js +2 -2
  86. package/docs/modules/event-driven-integration-design.md +91 -91
  87. package/docs/modules/integration.md +250 -250
  88. package/eslint.config.mjs +34 -34
  89. package/nest-cli.json +14 -14
  90. package/package.json +125 -125
  91. package/src/app.controller.ts +12 -12
  92. package/src/app.module.ts +68 -68
  93. package/src/app.service.ts +8 -8
  94. package/src/config/bull.config.ts +69 -69
  95. package/src/config/config.module.ts +17 -17
  96. package/src/config/database.config.ts +48 -48
  97. package/src/constant/global.constant.ts +67 -67
  98. package/src/core.module.ts +94 -94
  99. package/src/decorators/roles.decorator.ts +7 -7
  100. package/src/dtos/response.dto.ts +6 -6
  101. package/src/dtos/response.ts +5 -5
  102. package/src/index.ts +1 -1
  103. package/src/migrations/1732612800000-AddEntityJsonGinIndex.ts +41 -0
  104. package/src/module/auth/auth.module.ts +49 -49
  105. package/src/module/auth/controller/auth.controller.ts +28 -28
  106. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  107. package/src/module/auth/guards/jwt.guard.ts +22 -22
  108. package/src/module/auth/guards/role.guard.ts +68 -68
  109. package/src/module/auth/services/auth.service.ts +56 -56
  110. package/src/module/auth/services/jwt.service.ts +11 -11
  111. package/src/module/auth/strategies/google.strategy.ts +54 -54
  112. package/src/module/auth/strategies/jwt.strategy.ts +58 -58
  113. package/src/module/auth/strategies/local.strategy.ts +13 -13
  114. package/src/module/dashboard/controller/dashboard.controller.ts +38 -38
  115. package/src/module/dashboard/dashboard.module.ts +21 -21
  116. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +27 -27
  117. package/src/module/dashboard/entity/widget_master.entity.ts +18 -18
  118. package/src/module/dashboard/repository/dashboard.repository.ts +49 -49
  119. package/src/module/dashboard/service/dashboard.service.ts +72 -72
  120. package/src/module/enterprise/controller/organization.controller.ts +36 -36
  121. package/src/module/enterprise/enterprise.module.ts +45 -45
  122. package/src/module/enterprise/entity/enterprise.entity.ts +37 -37
  123. package/src/module/enterprise/entity/organization-app-mapping.entity.ts +13 -13
  124. package/src/module/enterprise/entity/organization.entity.ts +92 -92
  125. package/src/module/enterprise/repository/enterprise.repository.ts +31 -31
  126. package/src/module/enterprise/repository/organization.repository.ts +26 -26
  127. package/src/module/enterprise/repository/school.repository.ts +289 -289
  128. package/src/module/enterprise/service/brand.service.ts +5 -5
  129. package/src/module/enterprise/service/enterprise.service.ts +16 -16
  130. package/src/module/enterprise/service/organization-app-mapping.service.ts +4 -4
  131. package/src/module/enterprise/service/organization.service.ts +145 -145
  132. package/src/module/entity_json/controller/entity_json.controller.ts +60 -47
  133. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2804 -0
  134. package/src/module/entity_json/entity/entityJson.entity.ts +42 -39
  135. package/src/module/entity_json/entity_json.module.ts +22 -18
  136. package/src/module/entity_json/service/entityJson.repository.ts +37 -37
  137. package/src/module/entity_json/service/entity_json.service.ts +428 -241
  138. package/src/module/export/controller/export.controller.ts +83 -83
  139. package/src/module/export/export.module.ts +14 -14
  140. package/src/module/export/service/export.service.ts +105 -105
  141. package/src/module/filter/controller/filter.controller.ts +87 -87
  142. package/src/module/filter/dto/filter-request.dto.ts +39 -39
  143. package/src/module/filter/entity/saved-filter-detail.entity.ts +41 -41
  144. package/src/module/filter/entity/saved-filter-master.entity.ts +35 -35
  145. package/src/module/filter/filter.module.ts +42 -33
  146. package/src/module/filter/repository/saved-filter.repository.ts +247 -247
  147. package/src/module/filter/repository/saved.filter-detail.repository.ts +19 -19
  148. package/src/module/filter/service/filter-evaluator.service.ts +82 -82
  149. package/src/module/filter/service/filter.service.ts +1369 -1310
  150. package/src/module/filter/service/flatjson-filter.service.ts +903 -0
  151. package/src/module/filter/service/saved-filter.service.ts +154 -164
  152. package/src/module/filter/test/flatjson-filter.service.spec.ts +415 -0
  153. package/src/module/ics/controller/ics.controller.ts +21 -21
  154. package/src/module/ics/dto/ics.dto.ts +55 -55
  155. package/src/module/ics/ics.module.ts +13 -13
  156. package/src/module/ics/service/ics.service.ts +57 -57
  157. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  158. package/src/module/integration/controller/integration.controller.ts +662 -662
  159. package/src/module/integration/controller/wrapper.controller.ts +37 -37
  160. package/src/module/integration/dto/create-config.dto.ts +526 -526
  161. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  162. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  163. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  164. package/src/module/integration/entity/user-integration.entity.ts +71 -71
  165. package/src/module/integration/examples/usage.example.ts +338 -338
  166. package/src/module/integration/factories/base.factory.ts +7 -7
  167. package/src/module/integration/factories/email.factory.ts +49 -49
  168. package/src/module/integration/factories/integration.factory.ts +121 -121
  169. package/src/module/integration/factories/sms.factory.ts +51 -51
  170. package/src/module/integration/factories/telephone.factory.ts +41 -41
  171. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  172. package/src/module/integration/integration.module.ts +110 -110
  173. package/src/module/integration/service/calendar-event.service.ts +118 -118
  174. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  175. package/src/module/integration/service/integration-queue.service.ts +229 -229
  176. package/src/module/integration/service/integration.service.ts +2639 -2639
  177. package/src/module/integration/service/oauth.service.ts +224 -224
  178. package/src/module/integration/service/wrapper.service.ts +754 -754
  179. package/src/module/integration/strategies/email/gmail-api.strategy.ts +280 -280
  180. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  181. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  182. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +260 -260
  183. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  184. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  185. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  186. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  187. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  188. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  189. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  190. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -372
  191. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  192. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  193. package/src/module/layout/controller/layout.controller.ts +47 -47
  194. package/src/module/layout/entity/header-items.entity.ts +28 -28
  195. package/src/module/layout/entity/header-section.entity.ts +19 -19
  196. package/src/module/layout/layout.module.ts +21 -21
  197. package/src/module/layout/repository/header-items.repository.ts +18 -18
  198. package/src/module/layout/repository/header-section.repository.ts +22 -22
  199. package/src/module/layout/service/header-section.service.ts +25 -25
  200. package/src/module/layout_preference/controller/layout_preference.controller.ts +76 -76
  201. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  202. package/src/module/layout_preference/layout_preference.module.ts +22 -22
  203. package/src/module/layout_preference/repository/layout_preference.repository.ts +65 -65
  204. package/src/module/layout_preference/service/layout_preference.service.ts +191 -191
  205. package/src/module/lead/controller/lead.controller.ts +30 -30
  206. package/src/module/lead/lead.module.ts +14 -14
  207. package/src/module/lead/repository/lead.repository.ts +41 -41
  208. package/src/module/lead/service/lead.service.ts +54 -54
  209. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +137 -52
  210. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -0
  211. package/src/module/linked_attributes/entity/linked_attribute.entity.ts +51 -51
  212. package/src/module/linked_attributes/linked_attributes.module.ts +23 -21
  213. package/src/module/linked_attributes/repository/linked_attribute.repository.ts +12 -12
  214. package/src/module/linked_attributes/service/linked_attributes.service.ts +648 -105
  215. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -0
  216. package/src/module/listmaster/controller/list-master.controller.ts +230 -230
  217. package/src/module/listmaster/entity/list-master-items.entity.ts +43 -43
  218. package/src/module/listmaster/entity/list-master.entity.ts +33 -33
  219. package/src/module/listmaster/listmaster.module.ts +46 -46
  220. package/src/module/listmaster/repository/list-master-items.repository.ts +173 -173
  221. package/src/module/listmaster/repository/list-master.repository.ts +56 -56
  222. package/src/module/listmaster/service/list-master-engine.ts +19 -19
  223. package/src/module/listmaster/service/list-master-extension.interface.ts +4 -4
  224. package/src/module/listmaster/service/list-master-item.service.ts +280 -280
  225. package/src/module/listmaster/service/list-master-registry.ts +15 -15
  226. package/src/module/listmaster/service/list-master.service.ts +527 -527
  227. package/src/module/mapper/controller/field-mapper.controller.ts +76 -76
  228. package/src/module/mapper/controller/mapper.controller.ts +20 -20
  229. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  230. package/src/module/mapper/entity/field-lovs.entity.ts +19 -19
  231. package/src/module/mapper/entity/field-mapper.entity.ts +53 -53
  232. package/src/module/mapper/entity/mapper.entity.ts +16 -16
  233. package/src/module/mapper/mapper.module.ts +35 -35
  234. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  235. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  236. package/src/module/mapper/repository/mapper.repository.ts +32 -32
  237. package/src/module/mapper/service/field-mapper.service.ts +269 -269
  238. package/src/module/mapper/service/mapper.service.ts +80 -80
  239. package/src/module/master/controller/master.controller.ts +74 -74
  240. package/src/module/master/service/master.service.ts +484 -484
  241. package/src/module/meta/controller/app-master.controller.ts +38 -38
  242. package/src/module/meta/controller/attribute-master.controller.ts +96 -84
  243. package/src/module/meta/controller/entity-dynamic.controller.ts +125 -125
  244. package/src/module/meta/controller/entity-master.controller.ts +41 -41
  245. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  246. package/src/module/meta/controller/entity.controller.ts +308 -308
  247. package/src/module/meta/controller/entity.public.controller.ts +75 -75
  248. package/src/module/meta/controller/media.controller.ts +135 -135
  249. package/src/module/meta/controller/meta.controller.ts +101 -101
  250. package/src/module/meta/controller/view-master.controller.ts +79 -79
  251. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  252. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  253. package/src/module/meta/dto/entity-table.dto.ts +12 -12
  254. package/src/module/meta/entity/app-master.entity.ts +37 -37
  255. package/src/module/meta/entity/attribute-master.entity.ts +92 -92
  256. package/src/module/meta/entity/base-entity.entity.ts +75 -75
  257. package/src/module/meta/entity/entity-master.entity.ts +91 -91
  258. package/src/module/meta/entity/entity-relation-data.entity.ts +29 -29
  259. package/src/module/meta/entity/entity-relation.entity.ts +23 -23
  260. package/src/module/meta/entity/entity-table-column.entity.ts +61 -61
  261. package/src/module/meta/entity/entity-table.entity.ts +50 -50
  262. package/src/module/meta/entity/media-data.entity.ts +32 -32
  263. package/src/module/meta/entity/preference.entity.ts +62 -62
  264. package/src/module/meta/entity/view-master.entity.ts +41 -41
  265. package/src/module/meta/entity.module.ts +165 -165
  266. package/src/module/meta/repository/app-master.repository.ts +20 -20
  267. package/src/module/meta/repository/attribute-master.repository.ts +164 -164
  268. package/src/module/meta/repository/entity-attribute-update.repository.ts +48 -48
  269. package/src/module/meta/repository/entity-master.repository.ts +120 -120
  270. package/src/module/meta/repository/entity-relation.repository.ts +22 -22
  271. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  272. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  273. package/src/module/meta/repository/media-data.repository.ts +50 -50
  274. package/src/module/meta/repository/preference.repository.ts +20 -20
  275. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  276. package/src/module/meta/repository/view-master.repository.ts +42 -42
  277. package/src/module/meta/service/app-master.service.ts +37 -37
  278. package/src/module/meta/service/attribute-master.service.ts +160 -132
  279. package/src/module/meta/service/common.service.ts +9 -9
  280. package/src/module/meta/service/entity-attribute-update.service.ts +26 -26
  281. package/src/module/meta/service/entity-dynamic.service.ts +824 -824
  282. package/src/module/meta/service/entity-master.service.ts +172 -171
  283. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  284. package/src/module/meta/service/entity-relation.service.ts +78 -74
  285. package/src/module/meta/service/entity-service-impl.service.ts +389 -388
  286. package/src/module/meta/service/entity-table-column.service.ts +26 -26
  287. package/src/module/meta/service/entity-table.service.ts +171 -157
  288. package/src/module/meta/service/entity-validation.service.ts +188 -188
  289. package/src/module/meta/service/entity.service.ts +48 -49
  290. package/src/module/meta/service/field-group.service.ts +103 -103
  291. package/src/module/meta/service/media-data.service.ts +591 -591
  292. package/src/module/meta/service/populate-meta.service.ts +222 -222
  293. package/src/module/meta/service/preference.service.ts +16 -16
  294. package/src/module/meta/service/resolver.service.ts +319 -315
  295. package/src/module/meta/service/section-master.service.ts +104 -104
  296. package/src/module/meta/service/update-form-json.service.ts +22 -22
  297. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  298. package/src/module/meta/service/view-master.service.ts +127 -127
  299. package/src/module/microservice-client/microservice-clients.module.ts +13 -13
  300. package/src/module/microservice-client/service/microservice-client-factory.ts +37 -37
  301. package/src/module/microservice-client/service/microservice-clients.ts +4 -4
  302. package/src/module/module/controller/menu.controller.ts +15 -15
  303. package/src/module/module/controller/module-access.controller.ts +133 -133
  304. package/src/module/module/entity/menu.entity.ts +43 -43
  305. package/src/module/module/entity/module-access.entity.ts +25 -25
  306. package/src/module/module/entity/module-action.entity.ts +17 -17
  307. package/src/module/module/entity/module.entity.ts +52 -52
  308. package/src/module/module/module.module.ts +42 -42
  309. package/src/module/module/repository/menu.repository.ts +186 -186
  310. package/src/module/module/repository/module-access.repository.ts +344 -344
  311. package/src/module/module/service/menu.service.ts +82 -82
  312. package/src/module/module/service/module-access.service.ts +189 -189
  313. package/src/module/notification/controller/notification.controller.ts +58 -58
  314. package/src/module/notification/controller/otp.controller.ts +117 -117
  315. package/src/module/notification/entity/notification.entity.ts +26 -26
  316. package/src/module/notification/entity/otp.entity.ts +28 -28
  317. package/src/module/notification/firebase-admin.config.ts +22 -22
  318. package/src/module/notification/notification.module.ts +71 -71
  319. package/src/module/notification/repository/notification.repository.ts +33 -33
  320. package/src/module/notification/repository/otp.repository.ts +27 -27
  321. package/src/module/notification/service/email.service.ts +127 -127
  322. package/src/module/notification/service/notification.service.ts +146 -146
  323. package/src/module/notification/service/otp.service.ts +133 -133
  324. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  325. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  326. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  327. package/src/module/third-party-module/third-party.module.ts +12 -12
  328. package/src/module/user/controller/login.controller.ts +198 -198
  329. package/src/module/user/controller/user.controller.ts +40 -40
  330. package/src/module/user/dto/create-user.dto.ts +62 -62
  331. package/src/module/user/dto/update-user.dto.ts +4 -4
  332. package/src/module/user/entity/role.entity.ts +33 -33
  333. package/src/module/user/entity/user-role-mapping.entity.ts +38 -38
  334. package/src/module/user/entity/user-session.entity.ts +73 -73
  335. package/src/module/user/entity/user.entity.ts +62 -62
  336. package/src/module/user/repository/role.repository.ts +96 -96
  337. package/src/module/user/repository/user-role-mapping.repository.ts +126 -126
  338. package/src/module/user/repository/user.repository.ts +50 -50
  339. package/src/module/user/repository/userSession.repository.ts +33 -33
  340. package/src/module/user/service/login.service.ts +326 -326
  341. package/src/module/user/service/role.service.ts +197 -197
  342. package/src/module/user/service/user-role-mapping.service.ts +98 -98
  343. package/src/module/user/service/user-session.service.ts +200 -200
  344. package/src/module/user/service/user.service.ts +368 -368
  345. package/src/module/user/user.module.ts +65 -65
  346. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  347. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  348. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  349. package/src/module/workflow/controller/action.controller.ts +111 -111
  350. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  351. package/src/module/workflow/controller/comm-template.controller.ts +43 -43
  352. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  353. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  354. package/src/module/workflow/controller/stage-group.controller.ts +49 -49
  355. package/src/module/workflow/controller/stage.controller.ts +51 -51
  356. package/src/module/workflow/controller/task.controller.ts +77 -77
  357. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  358. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  359. package/src/module/workflow/controller/workflow.controller.ts +67 -67
  360. package/src/module/workflow/entity/action-category.entity.ts +38 -38
  361. package/src/module/workflow/entity/action-data.entity.ts +55 -55
  362. package/src/module/workflow/entity/action-resources-mapping.entity.ts +29 -29
  363. package/src/module/workflow/entity/action-template-mapping.entity.ts +17 -17
  364. package/src/module/workflow/entity/action.entity.ts +53 -53
  365. package/src/module/workflow/entity/activity-log.entity.ts +43 -43
  366. package/src/module/workflow/entity/comm-template.entity.ts +43 -43
  367. package/src/module/workflow/entity/entity-modification.entity.ts +38 -38
  368. package/src/module/workflow/entity/form.entity.ts +25 -25
  369. package/src/module/workflow/entity/stage-action-mapping.entity.ts +17 -17
  370. package/src/module/workflow/entity/stage-group.entity.ts +23 -23
  371. package/src/module/workflow/entity/stage-movement-data.entity.ts +38 -38
  372. package/src/module/workflow/entity/stage.entity.ts +20 -20
  373. package/src/module/workflow/entity/task-data.entity.ts +88 -88
  374. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  375. package/src/module/workflow/entity/workflow-data.entity.ts +11 -11
  376. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  377. package/src/module/workflow/entity/workflow.entity.ts +20 -20
  378. package/src/module/workflow/repository/action-category.repository.ts +79 -79
  379. package/src/module/workflow/repository/action-data.repository.ts +354 -354
  380. package/src/module/workflow/repository/action.repository.ts +339 -339
  381. package/src/module/workflow/repository/activity-log.repository.ts +148 -148
  382. package/src/module/workflow/repository/comm-template.repository.ts +157 -157
  383. package/src/module/workflow/repository/form-master.repository.ts +50 -50
  384. package/src/module/workflow/repository/stage-group.repository.ts +186 -186
  385. package/src/module/workflow/repository/stage-movement.repository.ts +217 -217
  386. package/src/module/workflow/repository/stage.repository.ts +160 -160
  387. package/src/module/workflow/repository/task.repository.ts +156 -156
  388. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  389. package/src/module/workflow/service/action-category.service.ts +33 -33
  390. package/src/module/workflow/service/action-data.service.ts +62 -62
  391. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  392. package/src/module/workflow/service/action-template-mapping.service.ts +137 -137
  393. package/src/module/workflow/service/action.service.ts +302 -302
  394. package/src/module/workflow/service/activity-log.service.ts +107 -107
  395. package/src/module/workflow/service/comm-template.service.ts +181 -181
  396. package/src/module/workflow/service/entity-modification.service.ts +61 -61
  397. package/src/module/workflow/service/form-master.service.ts +35 -35
  398. package/src/module/workflow/service/populate-workflow.service.ts +320 -320
  399. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  400. package/src/module/workflow/service/stage-group.service.ts +325 -325
  401. package/src/module/workflow/service/stage.service.ts +197 -197
  402. package/src/module/workflow/service/task.service.ts +551 -551
  403. package/src/module/workflow/service/workflow-list-master.service.ts +68 -68
  404. package/src/module/workflow/service/workflow-meta.service.ts +640 -640
  405. package/src/module/workflow/service/workflow.service.ts +213 -213
  406. package/src/module/workflow/workflow.module.ts +180 -180
  407. package/src/module/workflow-automation/SCHEDULING_GUIDE.md +145 -145
  408. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +43 -43
  409. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  410. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +40 -40
  411. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  412. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  413. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  414. package/src/module/workflow-automation/service/schedule-handler.service.ts +168 -168
  415. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +219 -219
  416. package/src/module/workflow-automation/service/workflow-automation.service.ts +474 -476
  417. package/src/module/workflow-automation/workflow-automation.module.ts +54 -54
  418. package/src/module/workflow-schedule/INSTALLATION.md +244 -244
  419. package/src/module/workflow-schedule/MULTI_PROJECT_GUIDE.md +196 -196
  420. package/src/module/workflow-schedule/README.md +422 -422
  421. package/src/module/workflow-schedule/constants/schedule.constants.ts +48 -48
  422. package/src/module/workflow-schedule/controller/workflow-schedule.controller.ts +253 -253
  423. package/src/module/workflow-schedule/docs/CLAUDE_CODE_GUIDE.md +510 -510
  424. package/src/module/workflow-schedule/docs/CLAUDE_CODE_PROMPT.md +362 -362
  425. package/src/module/workflow-schedule/docs/RUN_CLAUDE_CODE.sh +68 -68
  426. package/src/module/workflow-schedule/dto/create-schedule.dto.ts +147 -147
  427. package/src/module/workflow-schedule/dto/get-execution-logs.dto.ts +119 -119
  428. package/src/module/workflow-schedule/dto/update-schedule.dto.ts +96 -96
  429. package/src/module/workflow-schedule/entities/scheduled-workflow.entity.ts +148 -148
  430. package/src/module/workflow-schedule/entities/workflow-execution-log.entity.ts +154 -154
  431. package/src/module/workflow-schedule/interfaces/schedule-job-data.interface.ts +53 -53
  432. package/src/module/workflow-schedule/interfaces/workflow-schedule-options.interface.ts +12 -12
  433. package/src/module/workflow-schedule/processors/schedule.processor.ts +620 -620
  434. package/src/module/workflow-schedule/service/workflow-schedule.service.ts +597 -597
  435. package/src/module/workflow-schedule/workflow-schedule.module.ts +67 -67
  436. package/src/resources/dev.properties.yaml +31 -31
  437. package/src/resources/local.properties.yaml +27 -27
  438. package/src/resources/properties.module.ts +12 -12
  439. package/src/resources/properties.yaml.ts +11 -11
  440. package/src/resources/uat.properties.yaml +31 -31
  441. package/src/table.config.ts +135 -133
  442. package/src/utils/dto/excel-data.dto.ts +14 -14
  443. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  444. package/src/utils/service/base64util.service.ts +18 -18
  445. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  446. package/src/utils/service/codeGenerator.service.ts +22 -22
  447. package/src/utils/service/dateUtil.service.ts +17 -17
  448. package/src/utils/service/encryptUtil.service.ts +97 -97
  449. package/src/utils/service/excel-helper.service.ts +72 -72
  450. package/src/utils/service/excelUtil.service.ts +15 -15
  451. package/src/utils/service/file-util.service.ts +11 -11
  452. package/src/utils/service/json-util.service.ts +23 -23
  453. package/src/utils/service/loggingUtil.service.ts +88 -88
  454. package/src/utils/service/reflection-helper.service.ts +62 -62
  455. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  456. package/src/utils/utils.module.ts +27 -27
  457. package/tsconfig.build.json +4 -4
  458. package/tsconfig.json +24 -24
@@ -1,1310 +1,1369 @@
1
- import { BadRequestException, Inject, Injectable } from '@nestjs/common';
2
- import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
3
- import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
4
- import { FilterCondition, FilterRequestDto } from '../dto/filter-request.dto';
5
- import { SavedFilterService } from './saved-filter.service';
6
-
7
- import * as moment from 'moment';
8
- import { EntityRelationService } from 'src/module/meta/service/entity-relation.service';
9
- import { ResolverService } from 'src/module/meta/service/resolver.service';
10
- import { LoggingService } from 'src/utils/service/loggingUtil.service';
11
- import { ConfigService } from '@nestjs/config';
12
- import { ReflectionHelper } from '../../../utils/service/reflection-helper.service';
13
- import { EntityManager } from 'typeorm';
14
-
15
- @Injectable()
16
- export class FilterService {
17
- constructor(
18
- private entityManager: EntityManager,
19
- private readonly attributeMasterService: AttributeMasterService,
20
- private readonly entityMasterService: EntityMasterService,
21
- @Inject('SavedFilterService')
22
- private readonly savedFilterService: SavedFilterService,
23
- @Inject('EntityRelationService')
24
- private readonly entityRelationService: EntityRelationService,
25
- private readonly resolverService: ResolverService,
26
- @Inject() protected readonly loggingService: LoggingService,
27
- private readonly configService: ConfigService,
28
- private readonly reflectionHelper: ReflectionHelper,
29
- ) {}
30
-
31
- schema = this.configService.get('DB_SCHEMA');
32
-
33
- private async gettab_value_counts(
34
- tableName: string,
35
- column: string | undefined,
36
- whereClauses: { query: string; params: Record<string, any> }[],
37
- ) {
38
- if (!column) return [];
39
-
40
- let whereSQL = '';
41
- const values: any[] = [];
42
- let paramIndex = 1; // PostgreSQL placeholders start at $1
43
-
44
- if (whereClauses.length > 0) {
45
- const clauseParts = whereClauses.map((clause) => {
46
- let parsedQuery = clause.query.replace(/\be\./g, ''); // remove e.
47
-
48
- Object.entries(clause.params).forEach(([key, val]) => {
49
- if (Array.isArray(val)) {
50
- // Create ($1,$2,$3)
51
- const placeholders = val.map(() => `$${paramIndex++}`).join(', ');
52
-
53
- parsedQuery = parsedQuery.replace(
54
- new RegExp(`:${key}`, 'g'),
55
- `(${placeholders})`,
56
- );
57
-
58
- values.push(...val.map((v) => String(v)));
59
- } else {
60
- // Create $1
61
- const placeholder = `$${paramIndex++}`;
62
-
63
- parsedQuery = parsedQuery.replace(
64
- new RegExp(`:${key}`, 'g'),
65
- placeholder,
66
- );
67
-
68
- values.push(String(val));
69
- }
70
- });
71
-
72
- return parsedQuery;
73
- });
74
-
75
- whereSQL = `WHERE ${clauseParts.join(' AND ')}`;
76
- }
77
-
78
- const rawSQL = `
79
- SELECT ${column} AS tab_value, COUNT(*) AS tab_value_count
80
- FROM ${this.schema}.${tableName} ${whereSQL}
81
- GROUP BY ${column}
82
- `;
83
-
84
- const rows = await this.entityManager.query(rawSQL, values);
85
-
86
- const total = rows.reduce(
87
- (sum, r) => sum + parseInt(r.tab_value_count, 10),
88
- 0,
89
- );
90
-
91
- return [
92
- { tab_value: 'All', tab_value_count: total },
93
- ...rows.map((r) => ({
94
- tab_value: r.tab_value ?? 'BLANK',
95
- tab_value_count: parseInt(r.tab_value_count, 10),
96
- })),
97
- ];
98
- }
99
-
100
- async applyFilterWrapper(dto: FilterRequestDto) {
101
- const {
102
- entity_type,
103
- quickFilter = [],
104
- savedFilterCode,
105
- attributeFilter = [],
106
- loggedInUser,
107
- } = dto;
108
-
109
- // 🔹 Step 1: Collect all filters (from body + savedFilter)
110
- const savedFilters = await this.getSavedFilters(
111
- savedFilterCode ?? undefined,
112
- );
113
- const allFilters = [
114
- ...quickFilter,
115
- ...attributeFilter,
116
- ...savedFilters,
117
- ].filter((f) => f.filter_value !== '');
118
-
119
- // 🔹 Step 2: Group filters by filter_entity_type
120
- const grouped = allFilters.reduce(
121
- (acc, f) => {
122
- if (!acc[f.filter_entity_type]) acc[f.filter_entity_type] = [];
123
- acc[f.filter_entity_type].push(f);
124
- return acc;
125
- },
126
- {} as Record<string, any[]>,
127
- );
128
-
129
- console.log('🟠 [FilterService] Grouped filters by entity type:', grouped);
130
-
131
- // 🔹 Step 3: Handle sub-entities first
132
- let intersectionIds: number[] | null = null;
133
- for (const [subEntityType, filters] of Object.entries(grouped)) {
134
- if (subEntityType === entity_type) continue; // skip main entity for now
135
-
136
- let { queryParams, tabs, ...newDto } = dto;
137
-
138
- const subDto: FilterRequestDto = {
139
- ...newDto,
140
- entity_type: subEntityType,
141
- quickFilter: filters as FilterCondition[],
142
- savedFilterCode: null, // already merged
143
- attributeFilter: [],
144
- };
145
-
146
- const subResult = await this.applyFilter(subDto);
147
- const subEntityIds = subResult.data.entity_list.map((row) => row.id);
148
-
149
- console.log(
150
- `🧩 [FilterService] Sub-entity ${subEntityType} returned IDs:`,
151
- subEntityIds,
152
- );
153
-
154
- if (!subEntityIds.length) {
155
- console.log(
156
- `ℹ️ [FilterService] No records for sub-entity ${subEntityType}, returning empty result`,
157
- );
158
- return {
159
- success: true,
160
- data: { entity_tabs: [], entity_list: [], pagination: {} },
161
- };
162
- }
163
-
164
- const relatedIds = await this.entityRelationService.getRelatedEntityIds(
165
- entity_type,
166
- subEntityType,
167
- subEntityIds,
168
- dto.loggedInUser.enterprise_id,
169
- );
170
-
171
- intersectionIds =
172
- intersectionIds === null
173
- ? relatedIds
174
- : intersectionIds.filter((id) => relatedIds.includes(id));
175
-
176
- if (intersectionIds.length === 0) {
177
- console.log(
178
- '🚫 [FilterService] No intersection IDs left, returning empty result',
179
- );
180
- return {
181
- success: true,
182
- data: { entity_tabs: [], entity_list: [], pagination: {} },
183
- };
184
- }
185
- }
186
-
187
- // 🔹 Step 4: Call applyFilter for main entity
188
- const mainFilters = grouped[entity_type] || [];
189
- const mainDto: FilterRequestDto = {
190
- ...dto,
191
- quickFilter: [...mainFilters],
192
- savedFilterCode: null,
193
- attributeFilter: [],
194
- };
195
-
196
- if (intersectionIds && intersectionIds.length > 0) {
197
- (mainDto.quickFilter ??= []).push({
198
- filter_attribute: 'id',
199
- filter_operator: 'equal',
200
- filter_value: intersectionIds,
201
- filter_entity_type: entity_type,
202
- });
203
- }
204
-
205
- return await this.applyFilter(mainDto);
206
- }
207
-
208
- async applyFilter(dto: FilterRequestDto) {
209
- const {
210
- entity_type,
211
- quickFilter,
212
- savedFilterCode,
213
- attributeFilter,
214
- tabs,
215
- sortby,
216
- loggedInUser,
217
- queryParams,
218
- customLevelType,
219
- customLevelId,
220
- customAppCode,
221
- } = dto;
222
-
223
- // abstract user details
224
- const {
225
- level_type,
226
- level_id,
227
- id: user_id,
228
- appcode,
229
- organization_id,
230
- } = loggedInUser || {};
231
-
232
- // Fetch meta from entity table service
233
- const entityMeta = await this.entityMasterService.getEntityData(
234
- entity_type,
235
- loggedInUser,
236
- );
237
- const tableName = entityMeta?.data_source; // data_source is the table name
238
-
239
- if (!tableName) {
240
- console.error(`❌ [FilterService] Invalid entity_type: ${entity_type}`);
241
- throw new BadRequestException(`Invalid entity_type: ${entity_type}`);
242
- }
243
-
244
- const getAttributeColumnMeta =
245
- await this.attributeMasterService.findAttributesByMappedEntityType(
246
- entity_type,
247
- loggedInUser,
248
- );
249
-
250
- const attributeMetaMap = getAttributeColumnMeta.reduce(
251
- (acc, attr) => {
252
- acc[attr.attribute_key] = attr;
253
- return acc;
254
- },
255
- {} as Record<string, any>,
256
- );
257
-
258
- // Get and parse saved filters
259
- const savedFilters = await this.getSavedFilters(
260
- savedFilterCode ?? undefined,
261
- );
262
- const savedFiltersNormalized = savedFilters.map((f) => ({
263
- filter_attribute: f.filter_attribute,
264
- filter_operator: f.filter_operator,
265
- filter_value: f.filter_value,
266
- }));
267
-
268
- const baseFilters = [
269
- ...(quickFilter || []).filter(
270
- (f) => f.filter_value != null && f.filter_value !== '',
271
- ),
272
- ...savedFiltersNormalized.filter(
273
- (f) => f.filter_value != null && f.filter_value !== '',
274
- ),
275
- ...(attributeFilter || []).filter(
276
- (f) => f.filter_value != null && f.filter_value !== '',
277
- ),
278
- ];
279
-
280
- // 🧱 Build where clausesx
281
- const baseWhere = this.buildWhereClauses(baseFilters, attributeMetaMap);
282
-
283
- // Handle TEMPLATE entity special condition
284
- if (entity_type === 'TEMP' || entity_type === 'TEM') {
285
- if (level_type === 'ORG') {
286
- baseWhere.push({
287
- query: ` ((e.level_type = 'ORG' AND e.level_id = '${loggedInUser.enterprise_id}'))`,
288
- params: {},
289
- });
290
- } else if (level_type === 'SCH') {
291
- baseWhere.push({
292
- query: `
293
- (
294
- (e.level_type = 'SCH' AND e.level_id = '${loggedInUser.level_id}')
295
- OR
296
- (
297
- e.level_type = 'ORG'
298
- AND e.level_id = '${loggedInUser.enterprise_id}'
299
- AND e.enterprise_id = '${loggedInUser.enterprise_id}'
300
- AND e.code NOT IN (
301
- SELECT sub.code
302
- FROM frm_wf_comm_template AS sub
303
- WHERE sub.level_type = 'SCH' AND sub.level_id = '${loggedInUser.level_id}'
304
- )
305
- )
306
- )
307
- `,
308
- params: {},
309
- });
310
- }
311
- }
312
-
313
- // Default org/level clause — skip TEMPLATE entity
314
- if (
315
- entity_type !== 'ORGP' &&
316
- entity_type !== 'TEMP' &&
317
- entity_type !== 'TEM' && // ✅ skip TEMPLATE
318
- level_type &&
319
- level_id &&
320
- organization_id &&
321
- !customLevelType &&
322
- !customLevelId
323
- ) {
324
- baseWhere.push({
325
- query: 'e.level_type = :level_type AND e.level_id = :level_id',
326
- params: {
327
- level_type,
328
- level_id,
329
- },
330
- });
331
- }
332
-
333
- if (entity_type == 'USR' || entity_type == 'UPR') {
334
- baseWhere.push({
335
- query: 'e.is_customer is NULL',
336
- params: {},
337
- });
338
- }
339
-
340
- if (customLevelType && customLevelId && customAppCode) {
341
- baseWhere.push({
342
- query:
343
- 'e.level_type = :customLevelType AND e.level_id = :customLevelId AND e.appcode = :customAppCode',
344
- params: {
345
- customLevelType,
346
- customLevelId: String(customLevelId),
347
- customAppCode,
348
- },
349
- });
350
- }
351
-
352
- // Handle queryParams filters
353
- if (queryParams) {
354
- Object.entries(queryParams).forEach(([key, value]) => {
355
- if (!value) return;
356
-
357
- // Always convert to string
358
- const strValue = String(value);
359
-
360
- if (key === 'attributeName' && queryParams['attributeValue']) {
361
- const attrName = strValue;
362
- const attrValue = String(queryParams['attributeValue']);
363
-
364
- baseWhere.push({
365
- query: `e.${attrName} = :${attrName}`,
366
- params: { [attrName]: attrValue }, // <-- string
367
- });
368
- } else if (key !== 'attributeValue') {
369
- baseWhere.push({
370
- query: `e.${key} = :${key}`,
371
- params: { [key]: strValue }, // <-- string
372
- });
373
- }
374
- });
375
- }
376
-
377
- console.log('🟠 [FilterService] Constructed baseWhere clauses:', baseWhere);
378
-
379
- let layoutPreferenceRepo =
380
- this.reflectionHelper.getRepoService('LayoutPreference');
381
-
382
- const layoutPreference = await layoutPreferenceRepo.findOne({
383
- where: {
384
- user_id: user_id,
385
- mapped_entity_type: entity_type,
386
- mapped_level_id: level_id,
387
- mapped_level_type: level_type,
388
- type: 'layout',
389
- },
390
- });
391
-
392
- // Extract layout preference
393
- const layout = layoutPreference?.mapped_json?.quick_tab || {};
394
- const showList =
395
- layout?.show_list?.map((val) => {
396
- if (typeof val === 'string') {
397
- // legacy case — old format like ['Active', 'Inactive']
398
- return val.toLowerCase();
399
- }
400
-
401
- if (val && typeof val === 'object' && val.value !== undefined) {
402
- // new format [{ label: 'Active', value: '13023' }]
403
- return String(val.value).toLowerCase();
404
- }
405
-
406
- return ''; // fallback safety
407
- }) || [];
408
-
409
- let filteredTabs = await this.getFilteredTabs(
410
- layout,
411
- showList,
412
- entityMeta,
413
- baseWhere,
414
- tabs,
415
- loggedInUser,
416
- );
417
-
418
- const dataWhere = [...baseWhere];
419
-
420
- if (tabs?.columnName && tabs?.value) {
421
- const tabAttrMeta = attributeMetaMap[tabs.columnName];
422
- const tabValue = tabs.value.toLowerCase();
423
-
424
- if (tabValue === 'others') {
425
- // Extract 'value' (IDs) from showList, ignore 'all'
426
- const valuesToExclude = showList
427
- .filter((v) => v.label.toLowerCase() !== 'all')
428
- .map((v) => v.value);
429
-
430
- if (valuesToExclude.length > 0) {
431
- for (const value of valuesToExclude) {
432
- const resolvedId = await this.resolverService.getResolvedId(
433
- loggedInUser,
434
- tabs.columnName,
435
- value,
436
- entity_type,
437
- );
438
- if (resolvedId) {
439
- const tabCondition = this.buildCondition(
440
- {
441
- filter_attribute: tabs.columnName,
442
- filter_operator: 'not_equal',
443
- filter_value: [resolvedId],
444
- skip_id: true,
445
- },
446
- tabAttrMeta,
447
- );
448
- if (tabCondition) dataWhere.push(tabCondition);
449
- }
450
- }
451
- }
452
- } else if (tabValue !== 'all') {
453
- const resolvedId = await this.resolverService.getResolvedId(
454
- loggedInUser,
455
- tabs.columnName,
456
- tabs.value,
457
- entity_type,
458
- );
459
-
460
- if (resolvedId) {
461
- const tabCondition = this.buildCondition(
462
- {
463
- filter_attribute: tabs.columnName,
464
- filter_operator: 'equal',
465
- filter_value: [resolvedId],
466
- skip_id: true,
467
- },
468
- tabAttrMeta,
469
- );
470
- if (tabCondition) dataWhere.push(tabCondition);
471
- }
472
- }
473
- }
474
-
475
- let qb = this.entityManager
476
- .createQueryBuilder()
477
- .select('e.*')
478
- .from(`${this.schema}.${tableName}`, 'e');
479
- dataWhere.forEach((clause) => qb.andWhere(clause.query, clause.params));
480
-
481
- // Apply sorting
482
- qb = await this.sortTabsByShowList(qb, sortby, layoutPreference, tabs);
483
- const page = dto.page && dto.page > 0 ? dto.page : 1;
484
- const size = dto.size && dto.size > 0 ? dto.size : 10;
485
- if (dto.page && dto.size) {
486
- qb.skip((page - 1) * size).take(size);
487
- }
488
-
489
- let query = await qb.getQuery();
490
-
491
- console.log('------------------------------------------------------\n');
492
- console.log(query);
493
- console.log('\n------------------------------------------------------');
494
- const entity_list = await qb.getRawMany();
495
-
496
- console.log(`📦 [FilterService] Fetched ${entity_list.length} records`);
497
-
498
- const dateAttributes = Object.entries(attributeMetaMap)
499
- .filter(([_, attr]) => attr.data_type === 'date')
500
- .map(([key]) => key);
501
-
502
- const formatDate = (dateStr: string | null): string | null =>
503
- dateStr ? moment(dateStr).format('DD-MM-YYYY') : '';
504
-
505
- const formatDatesInRow = (row: any): any => {
506
- const formattedRow = { ...row };
507
- for (const key of dateAttributes) {
508
- if (formattedRow[key])
509
- formattedRow[key] = formatDate(formattedRow[key]);
510
- }
511
- return formattedRow;
512
- };
513
-
514
- const formattedEntityList = entity_list.map(formatDatesInRow);
515
-
516
- const resolvedEntityList = await Promise.all(
517
- formattedEntityList.map((row) =>
518
- this.resolverService.getResolvedData(loggedInUser, row, entity_type),
519
- ),
520
- );
521
-
522
- const resolvedTabs = await Promise.all(
523
- filteredTabs.map(async (tab) => {
524
- const tabAttrKey = layout?.attribute || tabs?.columnName;
525
-
526
- if (
527
- !tabAttrKey ||
528
- tab.tab_value?.toLowerCase() === 'all' ||
529
- tab.tab_value?.toLowerCase() === 'others'
530
- ) {
531
- return tab;
532
- }
533
-
534
- const resolvedVal = await this.resolverService.getResolvedValue(
535
- loggedInUser,
536
- tabAttrKey,
537
- tab.tab_value,
538
- entity_type,
539
- );
540
-
541
- return { ...tab, tab_value: resolvedVal ?? tab.tab_value };
542
- }),
543
- );
544
-
545
- const countQb = this.entityManager
546
- .createQueryBuilder()
547
- .select('COUNT(*)', 'count')
548
- .from(`${this.schema}.${tableName}`, 'e');
549
- dataWhere.forEach((clause) =>
550
- countQb.andWhere(clause.query, clause.params),
551
- );
552
- const countResult = await countQb.getRawOne();
553
- const total = parseInt(countResult.count, 10);
554
-
555
- console.log('📊 [FilterService] Returning final result with total:', total);
556
-
557
- return {
558
- success: true,
559
- data: {
560
- entity_tabs: resolvedTabs,
561
- entity_list: resolvedEntityList,
562
- pagination: {
563
- total,
564
- page,
565
- size,
566
- totalPages: Math.ceil(total / size),
567
- hasNextPage: page * size < total,
568
- hasPreviousPage: page > 1,
569
- },
570
- },
571
- };
572
- }
573
-
574
- // GET FILTERED TABS LOGIC
575
- private async getFilteredTabs(
576
- layout: any,
577
- showList: any,
578
- entityMeta: any,
579
- baseWhere: any,
580
- tabs: any,
581
- loggedInUser: any,
582
- ) {
583
- let allTabs;
584
- if (layout.attribute) {
585
- allTabs = await this.gettab_value_counts(
586
- entityMeta?.data_source,
587
- layout.attribute,
588
- baseWhere,
589
- );
590
- } else {
591
- allTabs = await this.gettab_value_counts(
592
- entityMeta?.data_source,
593
- tabs?.columnName,
594
- baseWhere,
595
- );
596
- }
597
-
598
- let filteredTabs: any[] = [];
599
-
600
- if (showList?.length > 0) {
601
- // Extract tab IDs (values)
602
- const showValues = (showList || []).map((item) => {
603
- const val = typeof item === 'object' ? item.value : item;
604
- return val ? String(val).toLowerCase() : '';
605
- });
606
-
607
- // Handle "all" logic
608
- const isAllNeeded = layout?.isAllSelected && !showValues.includes('all');
609
- if (isAllNeeded) {
610
- showList.push({ label: 'All', value: 'all' });
611
- showValues.push('all');
612
- }
613
-
614
- // Filter by value IDs (not labels)
615
- filteredTabs = allTabs.filter((tab) => {
616
- const tabValueStr = tab.tab_value
617
- ? String(tab.tab_value).toLowerCase()
618
- : '';
619
- return showValues.includes(tabValueStr);
620
- });
621
-
622
- // Handle "all" tab
623
- const allTab = filteredTabs.find(
624
- (tab) => tab.tab_value?.toString().toLowerCase() === 'all',
625
- );
626
- filteredTabs = filteredTabs.filter(
627
- (tab) => tab.tab_value?.toString().toLowerCase() !== 'all',
628
- );
629
-
630
- // SORTING LOGIC
631
- if (layout.sorting === 'asc') {
632
- filteredTabs.sort((a, b) =>
633
- a.tab_value.toString().localeCompare(b.tab_value.toString()),
634
- );
635
- } else if (layout.sorting === 'dsc') {
636
- filteredTabs.sort((a, b) =>
637
- b.tab_value.toString().localeCompare(a.tab_value.toString()),
638
- );
639
- } else if (layout.sorting === 'count_asc') {
640
- filteredTabs.sort((a, b) => a.tab_value_count - b.tab_value_count);
641
- } else if (layout.sorting === 'count_dsc') {
642
- filteredTabs.sort((a, b) => b.tab_value_count - a.tab_value_count);
643
- } else if (layout.sorting === 'custom') {
644
- // Keep order same as showList
645
- const orderMap = new Map<string, number>(
646
- showList.map((item, index) => [
647
- item.value?.toString().toLowerCase(),
648
- index,
649
- ]),
650
- );
651
- filteredTabs.sort((a, b) => {
652
- const aIndex =
653
- orderMap.get(a.tab_value?.toString().toLowerCase()) ?? Infinity;
654
- const bIndex =
655
- orderMap.get(b.tab_value?.toString().toLowerCase()) ?? Infinity;
656
- return aIndex - bIndex;
657
- });
658
- }
659
-
660
- // Re-add "all" tab at beginning if needed
661
- if (allTab) filteredTabs.unshift(allTab);
662
-
663
- // Combine others if enabled
664
- if (layout?.isCombineOther) {
665
- const originalAllTab = allTabs.find(
666
- (tab) => tab.tab_value?.toString().toLowerCase() === 'all',
667
- );
668
- const allCount = originalAllTab?.tab_value_count ?? 0;
669
- const knownTabCountSum = filteredTabs
670
- .filter((tab) => tab.tab_value?.toString().toLowerCase() !== 'all')
671
- .reduce((acc, tab) => acc + tab.tab_value_count, 0);
672
-
673
- const othersCount = allCount - knownTabCountSum;
674
- filteredTabs.push({
675
- tab_value: 'OTHERS',
676
- tab_value_count: othersCount < 0 ? 0 : othersCount,
677
- });
678
- }
679
- } else {
680
- filteredTabs = allTabs;
681
- }
682
-
683
- return filteredTabs;
684
- }
685
-
686
- // SORTING LOGIC FOR TABS
687
- private async sortTabsByShowList(
688
- qb: any,
689
- sortby: any,
690
- layoutPreference: any,
691
- tabs: any,
692
- ) {
693
- const sorting = layoutPreference?.mapped_json?.sorting;
694
-
695
- if (sorting) {
696
- if (Array.isArray(sorting?.tabs)) {
697
- const preferenceTabArray = sorting?.tabs;
698
- const tabFilter = preferenceTabArray.find(
699
- (tabData) => tabData.tab_name?.value === tabs?.value,
700
- );
701
-
702
- tabFilter?.sortby?.forEach(({ column, order }) => {
703
- qb.addOrderBy(
704
- `e.${column}`,
705
- order?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
706
- );
707
- });
708
- } else if (Array.isArray(sorting.sortby)) {
709
- sorting?.sortby?.forEach(({ column, order }) => {
710
- qb.addOrderBy(
711
- `e.${column}`,
712
- order?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
713
- );
714
- });
715
- }
716
- }
717
-
718
- if (Array.isArray(sortby) && sortby.length > 0) {
719
- sortby.forEach(({ sortColum, sortType }) => {
720
- if (sortColum) {
721
- qb.addOrderBy(
722
- `e.${sortColum}`,
723
- sortType?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
724
- );
725
- }
726
- });
727
- } else {
728
- // fallback if no explicit sortby sent
729
- qb.addOrderBy('e.created_date', 'DESC');
730
- }
731
-
732
- return qb;
733
- }
734
-
735
- private parseFilters(raw: any, isSingle = false): any[] {
736
- if (!raw) return [];
737
-
738
- if (typeof raw === 'string') {
739
- try {
740
- const parsed = JSON.parse(raw);
741
- return isSingle ? [parsed] : parsed;
742
- } catch {
743
- throw new BadRequestException('Invalid JSON in filter input');
744
- }
745
- }
746
-
747
- return isSingle ? [raw] : Array.isArray(raw) ? raw : [];
748
- }
749
-
750
- private async getSavedFilters(code?: string): Promise<any[]> {
751
- if (!code) return [];
752
-
753
- const savedFilter = await this.savedFilterService.getDetailsByCode(code);
754
- if (!savedFilter) {
755
- throw new BadRequestException(`Saved filter not found for code: ${code}`);
756
- }
757
- return savedFilter;
758
- }
759
-
760
- private buildWhereClauses(
761
- filters: any[],
762
- attributeMeta: Record<string, any>,
763
- ) {
764
- return filters
765
- .map((f) => {
766
- const clause = this.buildCondition(
767
- f,
768
- attributeMeta[f.filter_attribute],
769
- );
770
-
771
- if (!clause) return null;
772
-
773
- // Force every param to be a string
774
- if (clause.params) {
775
- Object.keys(clause.params).forEach((k) => {
776
- const val = clause.params[k];
777
- if (!Array.isArray(val)) {
778
- clause.params[k] = String(val); // only convert scalar values
779
- }
780
- });
781
- }
782
-
783
- return clause;
784
- })
785
- .filter(
786
- (clause): clause is { query: string; params: Record<string, string> } =>
787
- clause !== null,
788
- );
789
- }
790
-
791
- private buildCondition(
792
- filter: any,
793
- meta: any,
794
- ): { query: string; params: any } | null {
795
- if (!meta) return null;
796
-
797
- let attr = filter.filter_attribute;
798
- const val = filter.filter_value;
799
- const op = filter.filter_operator;
800
- const key = `param_${attr}_${Math.random().toString(36).substring(2, 8)}`;
801
-
802
- // if (
803
- // (meta.data_source_type === 'entity' ||
804
- // meta.data_source_type === 'master') &&
805
- // !filter.skip_id
806
- // ) {
807
- // attr = `${attr}_id`;
808
- // }
809
-
810
- switch (meta.data_type) {
811
- case 'text':
812
- return this.buildTextCondition(attr, op, val, key);
813
- case 'number':
814
- return this.buildNumberCondition(attr, op, val, key);
815
- case 'date':
816
- return this.buildDateCondition(attr, op, val, key);
817
- case 'select':
818
- return this.buildMultiSelectCondition(attr, op, val, key);
819
- case 'multiselect':
820
- return this.buildMultiSelectCondition(attr, op, val, key);
821
- case 'checkbox':
822
- return this.buildMultiSelectCondition(attr, op, val, key);
823
- case 'radio':
824
- return this.buildMultiSelectCondition(attr, op, val, key);
825
- case 'year':
826
- return this.buildYearCondition(attr, op, val, key);
827
- default:
828
- return null;
829
- }
830
- }
831
-
832
- private buildTextCondition(attr: string, op: string, val: any, key: string) {
833
- switch (op) {
834
- case 'contains':
835
- return {
836
- query: `LOWER(e.${attr}) LIKE :${key}`,
837
- params: { [key]: `%${val ? val.toLowerCase() : ''}%` },
838
- };
839
- case 'equal':
840
- return {
841
- query: `e.${attr} = :${key}`,
842
- params: { [key]: val },
843
- };
844
- case 'not_equal':
845
- return {
846
- query: `e.${attr} != :${key}`,
847
- params: { [key]: val },
848
- };
849
- case 'empty':
850
- return {
851
- query: `e.${attr} IS NULL`,
852
- params: {},
853
- };
854
- case 'not_empty':
855
- return {
856
- query: `e.${attr} IS NOT NULL`,
857
- params: {},
858
- };
859
- default:
860
- throw new BadRequestException(`Unsupported operator for text: ${op}`);
861
- }
862
- }
863
-
864
- private buildNumberCondition(
865
- attr: string,
866
- op: string,
867
- val: any,
868
- key: string,
869
- ) {
870
- switch (op) {
871
- case 'equal':
872
- return { query: `e.${attr} = :${key}`, params: { [key]: val } };
873
- case 'not_equal':
874
- return { query: `e.${attr} != :${key}`, params: { [key]: val } };
875
- case 'greater_than':
876
- return { query: `e.${attr} > :${key}`, params: { [key]: val } };
877
- case 'less_than':
878
- return { query: `e.${attr} < :${key}`, params: { [key]: val } };
879
- case 'less_than_qual_to':
880
- return { query: `e.${attr} <= :${key}`, params: { [key]: val } };
881
- case 'greater_than_qual_to':
882
- return { query: `e.${attr} >= :${key}`, params: { [key]: val } };
883
- case 'empty':
884
- return { query: `e.${attr} IS NULL`, params: {} };
885
- case 'not_empty':
886
- return { query: `e.${attr} IS NOT NULL`, params: {} };
887
-
888
- default:
889
- throw new BadRequestException(`Unsupported operator for number: ${op}`);
890
- }
891
- }
892
-
893
- private buildDateCondition(attr: string, op: string, val: any, key: string) {
894
- const dateColumn = `DATE(e.${attr})`;
895
- const monthColumn = `DATE_TRUNC('month', e.${attr})`;
896
-
897
- // convert to number when needed
898
- const numVal = Number(val);
899
-
900
- // INSIDE buildDateCondition
901
- const subtractBusinessDays = (days: number): string => {
902
- let d = new Date();
903
- let count = 0;
904
-
905
- while (count < days) {
906
- d.setDate(d.getDate() - 1);
907
-
908
- const day = d.getDay(); // 0 = Sunday, 6 = Saturday
909
-
910
- if (day !== 0 && day !== 6) {
911
- count++;
912
- }
913
- }
914
-
915
- return d.toISOString().split('T')[0];
916
- };
917
-
918
- switch (op) {
919
- // ============================================
920
- // BASIC COMPARISONS
921
- // ============================================
922
- case 'equal':
923
- case 'is':
924
- return {
925
- query: `${dateColumn} = :${key}`,
926
- params: { [key]: val },
927
- };
928
-
929
- case 'before':
930
- case 'is_before':
931
- return {
932
- query: `${dateColumn} < :${key}`,
933
- params: { [key]: val },
934
- };
935
-
936
- case 'after':
937
- case 'is_after':
938
- return {
939
- query: `${dateColumn} > :${key}`,
940
- params: { [key]: val },
941
- };
942
-
943
- case 'is_on_or_before':
944
- return {
945
- query: `${dateColumn} <= :${key}`,
946
- params: { [key]: val },
947
- };
948
-
949
- case 'is_on_or_after':
950
- return {
951
- query: `${dateColumn} >= :${key}`,
952
- params: { [key]: val },
953
- };
954
-
955
- // ============================================
956
- // EMPTY / NOT EMPTY
957
- // ============================================
958
- case 'empty':
959
- return {
960
- query: `e.${attr} IS NULL`,
961
- params: {},
962
- };
963
-
964
- case 'not_empty':
965
- return {
966
- query: `e.${attr} IS NOT NULL`,
967
- params: {},
968
- };
969
-
970
- // ============================================
971
- // DAY OFFSET LOGIC (ALWAYS ADJUST -1 DAY)
972
- // ============================================
973
- case 'is_day_before':
974
- if (isNaN(numVal)) {
975
- throw new BadRequestException(
976
- 'Value must be a number for is_day_before',
977
- );
978
- }
979
-
980
- const dayBefore = (() => {
981
- const d = new Date();
982
- d.setDate(d.getDate() - numVal);
983
-
984
- // Format as YYYY-MM-DD in IST
985
- return d.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });
986
- })();
987
-
988
- return {
989
- query: `${dateColumn} <= :${key}`,
990
- params: { [key]: dayBefore },
991
- };
992
-
993
- case 'is_day_after':
994
- if (isNaN(numVal)) {
995
- throw new BadRequestException(
996
- 'Value must be a number for is_day_after',
997
- );
998
- }
999
-
1000
- const dayAfter = (() => {
1001
- const d = new Date();
1002
- d.setDate(d.getDate() - 1 + numVal); // -1 because DB stores previous day
1003
- return d.toISOString().split('T')[0];
1004
- })();
1005
-
1006
- return {
1007
- query: `${dateColumn} > :${key}`,
1008
- params: { [key]: dayAfter },
1009
- };
1010
-
1011
- // ============================================
1012
- // MONTH OFFSET LOGIC
1013
- // ============================================
1014
- case 'is_month_before':
1015
- if (isNaN(numVal)) {
1016
- throw new BadRequestException(
1017
- 'Value must be a number for is_month_before',
1018
- );
1019
- }
1020
-
1021
- const monthBefore = (() => {
1022
- const d = new Date();
1023
- d.setMonth(d.getMonth() - numVal);
1024
- d.setDate(1);
1025
- d.setDate(d.getDate() - 1);
1026
- return d.toISOString().split('T')[0];
1027
- })();
1028
-
1029
- return {
1030
- query: `${monthColumn} < DATE_TRUNC('month', (:${key})::date)`,
1031
- params: { [key]: monthBefore },
1032
- };
1033
-
1034
- case 'is_month_after':
1035
- if (isNaN(numVal)) {
1036
- throw new BadRequestException(
1037
- 'Value must be a number for is_month_after',
1038
- );
1039
- }
1040
-
1041
- const monthAfter = (() => {
1042
- const d = new Date();
1043
- d.setMonth(d.getMonth() + numVal);
1044
- d.setDate(1);
1045
- d.setDate(d.getDate() - 1);
1046
- return d.toISOString().split('T')[0];
1047
- })();
1048
-
1049
- return {
1050
- query: `${monthColumn} > DATE_TRUNC('month', (:${key})::date)`,
1051
- params: { [key]: monthAfter },
1052
- };
1053
-
1054
- // ===== BETWEEN =====
1055
- case 'between': {
1056
- if (typeof val === 'string') {
1057
- val = val.split(',').map((v) => v.trim());
1058
- }
1059
-
1060
- if (
1061
- !Array.isArray(val) ||
1062
- val.length !== 2 ||
1063
- val[0] === '' ||
1064
- val[1] === ''
1065
- ) {
1066
- console.log(`Invalid value for between: ${val}`);
1067
- return null;
1068
- }
1069
-
1070
- return {
1071
- query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1072
- params: {
1073
- [`${key}_start`]: val[0],
1074
- [`${key}_end`]: val[1],
1075
- },
1076
- };
1077
- }
1078
-
1079
- // ===== TODAY =====
1080
- case 'today': {
1081
- const today = moment().format('YYYY-MM-DD');
1082
- return {
1083
- query: `${dateColumn} = :today`,
1084
- params: { today },
1085
- };
1086
- }
1087
-
1088
- // ============================================
1089
- // BUSINESS DAY OFFSET LOGIC (SKIPS WEEKENDS)
1090
- // ALWAYS ADJUST -1 DAY FOR DB SHIFT
1091
- // ============================================
1092
-
1093
- case 'is_before_business_days': {
1094
- if (isNaN(numVal)) {
1095
- throw new BadRequestException('Value must be a number');
1096
- }
1097
-
1098
- const targetDate = subtractBusinessDays(numVal);
1099
-
1100
- return {
1101
- query: `${dateColumn} <= :${key} AND EXTRACT(DOW FROM ${dateColumn}) NOT IN (0, 6)`,
1102
- params: { [key]: targetDate },
1103
- };
1104
- }
1105
-
1106
- case 'is_after_business_days': {
1107
- if (isNaN(numVal)) {
1108
- throw new BadRequestException(
1109
- 'Value must be a number for is_after_business_days',
1110
- );
1111
- }
1112
-
1113
- const businessAfter = (() => {
1114
- let d = new Date();
1115
- let count = 0;
1116
-
1117
- while (count < numVal) {
1118
- d.setDate(d.getDate() + 1);
1119
- const day = d.getDay(); // 0=Sun, 6=Sat
1120
- if (day !== 0 && day !== 6) count++;
1121
- }
1122
-
1123
- // DB shift -1 day
1124
- d.setDate(d.getDate() - 1);
1125
-
1126
- return d.toISOString().split('T')[0];
1127
- })();
1128
-
1129
- return {
1130
- query: `${dateColumn} > :${key}`,
1131
- params: { [key]: businessAfter },
1132
- };
1133
- }
1134
-
1135
- // ============================================
1136
- // IN LAST DAY (range: today to N days before)
1137
- // ============================================
1138
- case 'in_last_day': {
1139
- if (isNaN(numVal)) {
1140
- throw new BadRequestException(
1141
- 'Value must be a number for in_last_day',
1142
- );
1143
- }
1144
-
1145
- const today = (() => {
1146
- const d = new Date();
1147
- return d.toISOString().split('T')[0];
1148
- })();
1149
-
1150
- const lastN = (() => {
1151
- const d = new Date();
1152
- d.setDate(d.getDate() - numVal);
1153
- return d.toISOString().split('T')[0];
1154
- })();
1155
-
1156
- return {
1157
- query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1158
- params: {
1159
- [`${key}_start`]: lastN,
1160
- [`${key}_end`]: today,
1161
- },
1162
- };
1163
- }
1164
-
1165
- // ============================================
1166
- // IN NEXT DAY (range: today to N days after)
1167
- // ============================================
1168
- case 'in_next_day': {
1169
- if (isNaN(numVal)) {
1170
- throw new BadRequestException(
1171
- 'Value must be a number for in_next_day',
1172
- );
1173
- }
1174
-
1175
- const today = (() => {
1176
- const d = new Date();
1177
- return d.toISOString().split('T')[0];
1178
- })();
1179
-
1180
- const nextN = (() => {
1181
- const d = new Date();
1182
- d.setDate(d.getDate() + numVal);
1183
- return d.toISOString().split('T')[0];
1184
- })();
1185
-
1186
- return {
1187
- query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1188
- params: {
1189
- [`${key}_start`]: today,
1190
- [`${key}_end`]: nextN,
1191
- },
1192
- };
1193
- }
1194
-
1195
- default:
1196
- throw new BadRequestException(`Unsupported operator for date: ${op}`);
1197
- }
1198
- }
1199
-
1200
- private buildSelectCondition(
1201
- attr: string,
1202
- op: string,
1203
- val: any,
1204
- key: string,
1205
- ) {
1206
- switch (op) {
1207
- case 'equal':
1208
- return { query: `e.${attr} = :${key}`, params: { [key]: val } };
1209
- case 'not_equal':
1210
- return { query: `e.${attr} != :${key}`, params: { [key]: val } };
1211
- case 'empty':
1212
- return { query: `e.${attr} IS NULL`, params: {} };
1213
- case 'not_empty':
1214
- return { query: `e.${attr} IS NOT NULL`, params: {} };
1215
- default:
1216
- throw new BadRequestException(`Unsupported operator for select: ${op}`);
1217
- }
1218
- }
1219
-
1220
- private buildMultiSelectCondition(
1221
- attr: string,
1222
- op: string,
1223
- val: any,
1224
- key: string,
1225
- ) {
1226
- let arr: string[] = [];
1227
-
1228
- // SAFETY: Convert all to array
1229
- if (Array.isArray(val)) {
1230
- arr = val.map((v) => String(v));
1231
- } else if (typeof val === 'string') {
1232
- arr = val.split(',').map((v) => v.trim());
1233
- } else {
1234
- throw new BadRequestException(`Invalid multiselect value`);
1235
- }
1236
-
1237
- if (arr.length === 0) {
1238
- return { query: '1=1', params: {} };
1239
- }
1240
-
1241
- if (op === 'equal') {
1242
- return {
1243
- query: `e.${attr}::text IN (:...${key})`,
1244
- params: { [key]: arr },
1245
- };
1246
- }
1247
-
1248
- if (op === 'not_equal') {
1249
- return {
1250
- query: `e.${attr}::text NOT IN (:...${key})`,
1251
- params: { [key]: arr },
1252
- };
1253
- }
1254
-
1255
- if (op === 'contains') {
1256
- return {
1257
- query: `e.${attr}::text LIKE :${key}`,
1258
- params: { [key]: `%${val}%` },
1259
- };
1260
- }
1261
-
1262
- if (op === 'not_contains') {
1263
- return {
1264
- query: `e.${attr}::text NOT LIKE :${key}`,
1265
- params: { [key]: `%${val}%` },
1266
- };
1267
- }
1268
-
1269
- if (op === 'empty') return { query: `e.${attr} IS NULL`, params: {} };
1270
- if (op === 'not_empty')
1271
- return { query: `e.${attr} IS NOT NULL`, params: {} };
1272
-
1273
- throw new BadRequestException(`Unsupported operator: ${op}`);
1274
- }
1275
-
1276
- private buildYearCondition(attr: string, op: string, val: any, key: string) {
1277
- switch (op) {
1278
- case 'equal':
1279
- return {
1280
- query: `e.${attr} = :${key}`,
1281
- params: { [key]: parseInt(val, 10) },
1282
- };
1283
- case 'not_equal':
1284
- return {
1285
- query: `e.${attr} != :${key}`,
1286
- params: { [key]: parseInt(val, 10) },
1287
- };
1288
- case 'greater_than':
1289
- return {
1290
- query: `e.${attr} > :${key}`,
1291
- params: { [key]: parseInt(val, 10) },
1292
- };
1293
- case 'less_than':
1294
- return {
1295
- query: `e.${attr} < :${key}`,
1296
- params: { [key]: parseInt(val, 10) },
1297
- };
1298
- default:
1299
- throw new BadRequestException(`Unsupported operator for year: ${op}`);
1300
- }
1301
- }
1302
-
1303
- async queryWithSchema(sql: string, params: any[] = []) {
1304
- await this.entityManager.query('BEGIN');
1305
- await this.entityManager.query(`SET LOCAL search_path TO ${this.schema}`);
1306
- const result = await this.entityManager.query(sql, params);
1307
- await this.entityManager.query('COMMIT');
1308
- return result;
1309
- }
1310
- }
1
+ import {
2
+ BadRequestException,
3
+ forwardRef,
4
+ Inject,
5
+ Injectable,
6
+ } from '@nestjs/common';
7
+ import { AttributeMasterService } from 'src/module/meta/service/attribute-master.service';
8
+ import { EntityMasterService } from 'src/module/meta/service/entity-master.service';
9
+ import { FilterCondition, FilterRequestDto } from '../dto/filter-request.dto';
10
+ import { SavedFilterService } from './saved-filter.service';
11
+
12
+ import * as moment from 'moment';
13
+ import { EntityRelationService } from 'src/module/meta/service/entity-relation.service';
14
+ import { ResolverService } from 'src/module/meta/service/resolver.service';
15
+ import { LoggingService } from 'src/utils/service/loggingUtil.service';
16
+ import { ConfigService } from '@nestjs/config';
17
+ import { ReflectionHelper } from '../../../utils/service/reflection-helper.service';
18
+ import { EntityManager } from 'typeorm';
19
+ import { FlatjsonFilterService } from './flatjson-filter.service';
20
+
21
+ @Injectable()
22
+ export class FilterService {
23
+ constructor(
24
+ private entityManager: EntityManager,
25
+ @Inject(forwardRef(() => AttributeMasterService))
26
+ private readonly attributeMasterService: AttributeMasterService,
27
+ @Inject(forwardRef(() => EntityMasterService))
28
+ private readonly entityMasterService: EntityMasterService,
29
+ @Inject('EntityRelationService')
30
+ private readonly entityRelationService: EntityRelationService,
31
+ @Inject('SavedFilterService')
32
+ private readonly savedFilterService: SavedFilterService,
33
+ @Inject(forwardRef(() => ResolverService))
34
+ private readonly resolverService: ResolverService,
35
+ @Inject(forwardRef(() => LoggingService))
36
+ protected readonly loggingService: LoggingService,
37
+ private readonly configService: ConfigService,
38
+ @Inject(forwardRef(() => ReflectionHelper))
39
+ private readonly reflectionHelper: ReflectionHelper,
40
+ @Inject(forwardRef(() => FlatjsonFilterService))
41
+ private readonly flatjsonFilterService: FlatjsonFilterService,
42
+ ) {}
43
+
44
+ schema = this.configService.get('DB_SCHEMA');
45
+
46
+ private async gettab_value_counts(
47
+ tableName: string,
48
+ column: string | undefined,
49
+ whereClauses: { query: string; params: Record<string, any> }[],
50
+ ) {
51
+ if (!column) return [];
52
+
53
+ let whereSQL = '';
54
+ const values: any[] = [];
55
+ let paramIndex = 1; // PostgreSQL placeholders start at $1
56
+
57
+ if (whereClauses.length > 0) {
58
+ const clauseParts = whereClauses.map((clause) => {
59
+ let parsedQuery = clause.query.replace(/\be\./g, ''); // remove e.
60
+
61
+ Object.entries(clause.params).forEach(([key, val]) => {
62
+ if (Array.isArray(val)) {
63
+ // Create ($1,$2,$3)
64
+ const placeholders = val.map(() => `$${paramIndex++}`).join(', ');
65
+
66
+ parsedQuery = parsedQuery.replace(
67
+ new RegExp(`:${key}`, 'g'),
68
+ `(${placeholders})`,
69
+ );
70
+
71
+ values.push(...val.map((v) => String(v)));
72
+ } else {
73
+ // Create $1
74
+ const placeholder = `$${paramIndex++}`;
75
+
76
+ parsedQuery = parsedQuery.replace(
77
+ new RegExp(`:${key}`, 'g'),
78
+ placeholder,
79
+ );
80
+
81
+ values.push(String(val));
82
+ }
83
+ });
84
+
85
+ return parsedQuery;
86
+ });
87
+
88
+ whereSQL = `WHERE ${clauseParts.join(' AND ')}`;
89
+ }
90
+
91
+ const rawSQL = `
92
+ SELECT ${column} AS tab_value, COUNT(*) AS tab_value_count
93
+ FROM ${this.schema}.${tableName} ${whereSQL}
94
+ GROUP BY ${column}
95
+ `;
96
+
97
+ const rows = await this.entityManager.query(rawSQL, values);
98
+
99
+ const total = rows.reduce(
100
+ (sum, r) => sum + parseInt(r.tab_value_count, 10),
101
+ 0,
102
+ );
103
+
104
+ return [
105
+ { tab_value: 'All', tab_value_count: total },
106
+ ...rows.map((r) => ({
107
+ tab_value: r.tab_value ?? 'BLANK',
108
+ tab_value_count: parseInt(r.tab_value_count, 10),
109
+ })),
110
+ ];
111
+ }
112
+
113
+ /**
114
+ * Route to flatjson or traditional filtering based on configuration
115
+ */
116
+ async applyFilterWithRouting(dto: FilterRequestDto) {
117
+ // Check if flatjson filtering is enabled via config or query param
118
+ const useFlatjson = dto.queryParams?.use_flatjson === 'true';
119
+
120
+ if (useFlatjson) {
121
+ await this.loggingService.log(
122
+ 'info',
123
+ 'FilterService',
124
+ 'applyFilterWithRouting',
125
+ `Using FLATJSON filtering for ${dto.entity_type}`,
126
+ );
127
+
128
+ // Use new flatjson filtering service
129
+ const result = await this.flatjsonFilterService.applyFlatjsonFilter(dto);
130
+
131
+ // Transform to match existing response format
132
+ return {
133
+ success: true,
134
+ data: {
135
+ entity_tabs: result.tabCounts || [],
136
+ entity_list: result.data,
137
+ pagination: {
138
+ total: result.total,
139
+ page: result.page,
140
+ size: result.size,
141
+ totalPages: result.totalPages,
142
+ },
143
+ },
144
+ };
145
+ } else {
146
+ await this.loggingService.log(
147
+ 'info',
148
+ 'FilterService',
149
+ 'applyFilterWithRouting',
150
+ `Using TRADITIONAL filtering for ${dto.entity_type}`,
151
+ );
152
+
153
+ // Use traditional filtering
154
+ return this.applyFilterWrapper(dto);
155
+ }
156
+ }
157
+
158
+ async applyFilterWrapper(dto: FilterRequestDto) {
159
+ const {
160
+ entity_type,
161
+ quickFilter = [],
162
+ savedFilterCode,
163
+ attributeFilter = [],
164
+ loggedInUser,
165
+ } = dto;
166
+
167
+ // 🔹 Step 1: Collect all filters (from body + savedFilter)
168
+ const savedFilters = await this.getSavedFilters(
169
+ savedFilterCode ?? undefined,
170
+ );
171
+ const allFilters = [
172
+ ...quickFilter,
173
+ ...attributeFilter,
174
+ ...savedFilters,
175
+ ].filter((f) => f.filter_value !== '');
176
+
177
+ // 🔹 Step 2: Group filters by filter_entity_type
178
+ const grouped = allFilters.reduce(
179
+ (acc, f) => {
180
+ if (!acc[f.filter_entity_type]) acc[f.filter_entity_type] = [];
181
+ acc[f.filter_entity_type].push(f);
182
+ return acc;
183
+ },
184
+ {} as Record<string, any[]>,
185
+ );
186
+
187
+ console.log('🟠 [FilterService] Grouped filters by entity type:', grouped);
188
+
189
+ // 🔹 Step 3: Handle sub-entities first
190
+ let intersectionIds: number[] | null = null;
191
+ for (const [subEntityType, filters] of Object.entries(grouped)) {
192
+ if (subEntityType === entity_type) continue; // skip main entity for now
193
+
194
+ let { queryParams, tabs, ...newDto } = dto;
195
+
196
+ const subDto: FilterRequestDto = {
197
+ ...newDto,
198
+ entity_type: subEntityType,
199
+ quickFilter: filters as FilterCondition[],
200
+ savedFilterCode: null, // already merged
201
+ attributeFilter: [],
202
+ };
203
+
204
+ const subResult = await this.applyFilter(subDto);
205
+ const subEntityIds = subResult.data.entity_list.map((row) => row.id);
206
+
207
+ console.log(
208
+ `🧩 [FilterService] Sub-entity ${subEntityType} returned IDs:`,
209
+ subEntityIds,
210
+ );
211
+
212
+ if (!subEntityIds.length) {
213
+ console.log(
214
+ `ℹ️ [FilterService] No records for sub-entity ${subEntityType}, returning empty result`,
215
+ );
216
+ return {
217
+ success: true,
218
+ data: { entity_tabs: [], entity_list: [], pagination: {} },
219
+ };
220
+ }
221
+
222
+ const relatedIds = await this.entityRelationService.getRelatedEntityIds(
223
+ entity_type,
224
+ subEntityType,
225
+ subEntityIds,
226
+ dto.loggedInUser.enterprise_id,
227
+ );
228
+
229
+ intersectionIds =
230
+ intersectionIds === null
231
+ ? relatedIds
232
+ : intersectionIds.filter((id) => relatedIds.includes(id));
233
+
234
+ if (intersectionIds.length === 0) {
235
+ console.log(
236
+ '🚫 [FilterService] No intersection IDs left, returning empty result',
237
+ );
238
+ return {
239
+ success: true,
240
+ data: { entity_tabs: [], entity_list: [], pagination: {} },
241
+ };
242
+ }
243
+ }
244
+
245
+ // 🔹 Step 4: Call applyFilter for main entity
246
+ const mainFilters = grouped[entity_type] || [];
247
+ const mainDto: FilterRequestDto = {
248
+ ...dto,
249
+ quickFilter: [...mainFilters],
250
+ savedFilterCode: null,
251
+ attributeFilter: [],
252
+ };
253
+
254
+ if (intersectionIds && intersectionIds.length > 0) {
255
+ (mainDto.quickFilter ??= []).push({
256
+ filter_attribute: 'id',
257
+ filter_operator: 'equal',
258
+ filter_value: intersectionIds,
259
+ filter_entity_type: entity_type,
260
+ });
261
+ }
262
+
263
+ return await this.applyFilter(mainDto);
264
+ }
265
+
266
+ async applyFilter(dto: FilterRequestDto) {
267
+ const {
268
+ entity_type,
269
+ quickFilter,
270
+ savedFilterCode,
271
+ attributeFilter,
272
+ tabs,
273
+ sortby,
274
+ loggedInUser,
275
+ queryParams,
276
+ customLevelType,
277
+ customLevelId,
278
+ customAppCode,
279
+ } = dto;
280
+
281
+ // abstract user details
282
+ const {
283
+ level_type,
284
+ level_id,
285
+ id: user_id,
286
+ appcode,
287
+ organization_id,
288
+ enterprise_id,
289
+ } = loggedInUser || {};
290
+
291
+ // Fetch meta from entity table service
292
+ const entityMeta = await this.entityMasterService.getEntityData(
293
+ entity_type,
294
+ loggedInUser,
295
+ );
296
+ const tableName = entityMeta?.data_source; // data_source is the table name
297
+
298
+ if (!tableName) {
299
+ console.error(`❌ [FilterService] Invalid entity_type: ${entity_type}`);
300
+ throw new BadRequestException(`Invalid entity_type: ${entity_type}`);
301
+ }
302
+
303
+ const getAttributeColumnMeta =
304
+ await this.attributeMasterService.findAttributesByMappedEntityType(
305
+ entity_type,
306
+ loggedInUser,
307
+ );
308
+
309
+ const attributeMetaMap = getAttributeColumnMeta.reduce(
310
+ (acc, attr) => {
311
+ acc[attr.attribute_key] = attr;
312
+ return acc;
313
+ },
314
+ {} as Record<string, any>,
315
+ );
316
+
317
+ // Get and parse saved filters
318
+ const savedFilters = await this.getSavedFilters(
319
+ savedFilterCode ?? undefined,
320
+ );
321
+ const savedFiltersNormalized = savedFilters.map((f) => ({
322
+ filter_attribute: f.filter_attribute,
323
+ filter_operator: f.filter_operator,
324
+ filter_value: f.filter_value,
325
+ }));
326
+
327
+ const baseFilters = [
328
+ ...(quickFilter || []).filter(
329
+ (f) => f.filter_value != null && f.filter_value !== '',
330
+ ),
331
+ ...savedFiltersNormalized.filter(
332
+ (f) => f.filter_value != null && f.filter_value !== '',
333
+ ),
334
+ ...(attributeFilter || []).filter(
335
+ (f) => f.filter_value != null && f.filter_value !== '',
336
+ ),
337
+ ];
338
+
339
+ // 🧱 Build where clausesx
340
+ const baseWhere = this.buildWhereClauses(baseFilters, attributeMetaMap);
341
+
342
+ // Handle TEMPLATE entity special condition
343
+ if (entity_type === 'TEMP' || entity_type === 'TEM') {
344
+ if (level_type === 'ORG') {
345
+ baseWhere.push({
346
+ query: ` ((e.level_type = 'ORG' AND e.level_id = '${loggedInUser.enterprise_id}'))`,
347
+ params: {},
348
+ });
349
+ } else if (level_type === 'SCH') {
350
+ baseWhere.push({
351
+ query: `
352
+ (
353
+ (e.level_type = 'SCH' AND e.level_id = '${loggedInUser.level_id}')
354
+ OR
355
+ (
356
+ e.level_type = 'ORG'
357
+ AND e.level_id = '${loggedInUser.enterprise_id}'
358
+ AND e.enterprise_id = '${loggedInUser.enterprise_id}'
359
+ AND e.code NOT IN (
360
+ SELECT sub.code
361
+ FROM frm_wf_comm_template AS sub
362
+ WHERE sub.level_type = 'SCH' AND sub.level_id = '${loggedInUser.level_id}'
363
+ )
364
+ )
365
+ )
366
+ `,
367
+ params: {},
368
+ });
369
+ }
370
+ }
371
+
372
+ // Default org/level clause — skip TEMPLATE entity
373
+ if (
374
+ entity_type !== 'ORGP' &&
375
+ entity_type !== 'TEMP' &&
376
+ entity_type !== 'TEM' && // ✅ skip TEMPLATE
377
+ level_type &&
378
+ level_id &&
379
+ organization_id &&
380
+ !customLevelType &&
381
+ !customLevelId
382
+ ) {
383
+ baseWhere.push({
384
+ query: 'e.level_type = :level_type AND e.level_id = :level_id',
385
+ params: {
386
+ level_type,
387
+ level_id,
388
+ },
389
+ });
390
+ }
391
+
392
+ if (entity_type == 'USR' || entity_type == 'UPR') {
393
+ baseWhere.push({
394
+ query: 'e.is_customer is NULL',
395
+ params: {},
396
+ });
397
+ }
398
+
399
+ if (customLevelType && customLevelId && customAppCode) {
400
+ baseWhere.push({
401
+ query:
402
+ 'e.level_type = :customLevelType AND e.level_id = :customLevelId AND e.appcode = :customAppCode',
403
+ params: {
404
+ customLevelType,
405
+ customLevelId: String(customLevelId),
406
+ customAppCode,
407
+ },
408
+ });
409
+ }
410
+
411
+ // Handle queryParams filters
412
+ if (queryParams) {
413
+ Object.entries(queryParams).forEach(([key, value]) => {
414
+ if (!value) return;
415
+
416
+ // Always convert to string
417
+ const strValue = String(value);
418
+
419
+ if (key === 'attributeName' && queryParams['attributeValue']) {
420
+ const attrName = strValue;
421
+ const attrValue = String(queryParams['attributeValue']);
422
+
423
+ baseWhere.push({
424
+ query: `e.${attrName} = :${attrName}`,
425
+ params: { [attrName]: attrValue }, // <-- string
426
+ });
427
+ } else if (key !== 'attributeValue') {
428
+ baseWhere.push({
429
+ query: `e.${key} = :${key}`,
430
+ params: { [key]: strValue }, // <-- string
431
+ });
432
+ }
433
+ });
434
+ }
435
+
436
+ console.log('🟠 [FilterService] Constructed baseWhere clauses:', baseWhere);
437
+
438
+ let layoutPreferenceRepo =
439
+ this.reflectionHelper.getRepoService('LayoutPreference');
440
+
441
+ const layoutPreference = await layoutPreferenceRepo.findOne({
442
+ where: {
443
+ user_id: user_id,
444
+ mapped_entity_type: entity_type,
445
+ mapped_level_id: level_id,
446
+ mapped_level_type: level_type,
447
+ type: 'layout',
448
+ },
449
+ });
450
+
451
+ // Extract layout preference
452
+ const layout = layoutPreference?.mapped_json?.quick_tab || {};
453
+ const showList =
454
+ layout?.show_list?.map((val) => {
455
+ if (typeof val === 'string') {
456
+ // legacy case — old format like ['Active', 'Inactive']
457
+ return val.toLowerCase();
458
+ }
459
+
460
+ if (val && typeof val === 'object' && val.value !== undefined) {
461
+ // new format — [{ label: 'Active', value: '13023' }]
462
+ return String(val.value).toLowerCase();
463
+ }
464
+
465
+ return ''; // fallback safety
466
+ }) || [];
467
+
468
+ let filteredTabs = await this.getFilteredTabs(
469
+ layout,
470
+ showList,
471
+ entityMeta,
472
+ baseWhere,
473
+ tabs,
474
+ loggedInUser,
475
+ );
476
+
477
+ const dataWhere = [...baseWhere];
478
+
479
+ // if (tabs?.columnName && tabs?.value) {
480
+ // const tabAttrMeta = attributeMetaMap[tabs.columnName];
481
+ // const tabValue = tabs.value.toLowerCase();
482
+
483
+ // if (tabValue === 'others') {
484
+ // // Extract 'value' (IDs) from showList, ignore 'all'
485
+ // const valuesToExclude = showList
486
+ // .filter((v) => v.label.toLowerCase() !== 'all')
487
+ // .map((v) => v.value);
488
+
489
+ // if (valuesToExclude.length > 0) {
490
+ // for (const value of valuesToExclude) {
491
+ // const resolvedId = await this.resolverService.getResolvedId(
492
+ // loggedInUser,
493
+ // tabs.columnName,
494
+ // value,
495
+ // entity_type,
496
+ // );
497
+ // if (resolvedId) {
498
+ // const tabCondition = this.buildCondition(
499
+ // {
500
+ // filter_attribute: tabs.columnName,
501
+ // filter_operator: 'not_equal',
502
+ // filter_value: [resolvedId],
503
+ // skip_id: true,
504
+ // },
505
+ // tabAttrMeta,
506
+ // );
507
+ // if (tabCondition) dataWhere.push(tabCondition);
508
+ // }
509
+ // }
510
+ // }
511
+ // } else if (tabValue !== 'all') {
512
+ // const resolvedId = await this.resolverService.getResolvedId(
513
+ // loggedInUser,
514
+ // tabs.columnName,
515
+ // tabs.value,
516
+ // entity_type,
517
+ // );
518
+
519
+ // if (resolvedId) {
520
+ // const tabCondition = this.buildCondition(
521
+ // {
522
+ // filter_attribute: tabs.columnName,
523
+ // filter_operator: 'equal',
524
+ // filter_value: [resolvedId],
525
+ // skip_id: true,
526
+ // },
527
+ // tabAttrMeta,
528
+ // );
529
+ // if (tabCondition) dataWhere.push(tabCondition);
530
+ // }
531
+ // }
532
+ // }
533
+
534
+ let qb = this.entityManager
535
+ .createQueryBuilder()
536
+ .select('e.*')
537
+ .from(`${this.schema}.${tableName}`, 'e');
538
+ dataWhere.forEach((clause) => qb.andWhere(clause.query, clause.params));
539
+
540
+ // Apply sorting
541
+ qb = await this.sortTabsByShowList(qb, sortby, layoutPreference, tabs);
542
+ const page = dto.page && dto.page > 0 ? dto.page : 1;
543
+ const size = dto.size && dto.size > 0 ? dto.size : 10;
544
+ if (dto.page && dto.size) {
545
+ qb.skip((page - 1) * size).take(size);
546
+ }
547
+
548
+ let query = await qb.getQuery();
549
+
550
+ console.log('------------------------------------------------------\n');
551
+ console.log(query);
552
+ console.log('\n------------------------------------------------------');
553
+ const entity_list = await qb.getRawMany();
554
+
555
+ console.log(`📦 [FilterService] Fetched ${entity_list.length} records`);
556
+
557
+ const dateAttributes = Object.entries(attributeMetaMap)
558
+ .filter(([_, attr]) => attr.data_type === 'date')
559
+ .map(([key]) => key);
560
+
561
+ const formatDate = (dateStr: string | null): string | null =>
562
+ dateStr ? moment(dateStr).format('DD-MM-YYYY') : '';
563
+
564
+ const formatDatesInRow = (row: any): any => {
565
+ const formattedRow = { ...row };
566
+ for (const key of dateAttributes) {
567
+ if (formattedRow[key])
568
+ formattedRow[key] = formatDate(formattedRow[key]);
569
+ }
570
+ return formattedRow;
571
+ };
572
+
573
+ const formattedEntityList = entity_list.map(formatDatesInRow);
574
+
575
+ // const resolvedEntityList = await Promise.all(
576
+ // formattedEntityList.map((row) =>
577
+ // this.resolverService.getResolvedData(loggedInUser, row, entity_type),
578
+ // ),
579
+ // );
580
+
581
+ const resolvedTabs = await Promise.all(
582
+ filteredTabs.map(async (tab) => {
583
+ const tabAttrKey = layout?.attribute || tabs?.columnName;
584
+
585
+ if (
586
+ !tabAttrKey ||
587
+ tab.tab_value?.toLowerCase() === 'all' ||
588
+ tab.tab_value?.toLowerCase() === 'others'
589
+ ) {
590
+ return tab;
591
+ }
592
+
593
+ // const resolvedVal = await this.resolverService.getResolvedValue(
594
+ // loggedInUser,
595
+ // tabAttrKey,
596
+ // tab.tab_value,
597
+ // entity_type,
598
+ // );
599
+
600
+ return { ...tab, tab_value: tab.tab_value ?? tab.tab_value };
601
+ }),
602
+ );
603
+
604
+ const countQb = this.entityManager
605
+ .createQueryBuilder()
606
+ .select('COUNT(*)', 'count')
607
+ .from(`${this.schema}.${tableName}`, 'e');
608
+ dataWhere.forEach((clause) =>
609
+ countQb.andWhere(clause.query, clause.params),
610
+ );
611
+ const countResult = await countQb.getRawOne();
612
+ const total = parseInt(countResult.count, 10);
613
+
614
+ console.log('📊 [FilterService] Returning final result with total:', total);
615
+
616
+ return {
617
+ success: true,
618
+ data: {
619
+ entity_tabs: resolvedTabs,
620
+ entity_list: formattedEntityList,
621
+ pagination: {
622
+ total,
623
+ page,
624
+ size,
625
+ totalPages: Math.ceil(total / size),
626
+ hasNextPage: page * size < total,
627
+ hasPreviousPage: page > 1,
628
+ },
629
+ },
630
+ };
631
+ }
632
+
633
+ // GET FILTERED TABS LOGIC
634
+ private async getFilteredTabs(
635
+ layout: any,
636
+ showList: any,
637
+ entityMeta: any,
638
+ baseWhere: any,
639
+ tabs: any,
640
+ loggedInUser: any,
641
+ ) {
642
+ let allTabs;
643
+ if (layout.attribute) {
644
+ allTabs = await this.gettab_value_counts(
645
+ entityMeta?.data_source,
646
+ layout.attribute,
647
+ baseWhere,
648
+ );
649
+ } else {
650
+ allTabs = await this.gettab_value_counts(
651
+ entityMeta?.data_source,
652
+ tabs?.columnName,
653
+ baseWhere,
654
+ );
655
+ }
656
+
657
+ let filteredTabs: any[] = [];
658
+
659
+ if (showList?.length > 0) {
660
+ // Extract tab IDs (values)
661
+ const showValues = (showList || []).map((item) => {
662
+ const val = typeof item === 'object' ? item.value : item;
663
+ return val ? String(val).toLowerCase() : '';
664
+ });
665
+
666
+ // Handle "all" logic
667
+ const isAllNeeded = layout?.isAllSelected && !showValues.includes('all');
668
+ if (isAllNeeded) {
669
+ showList.push({ label: 'All', value: 'all' });
670
+ showValues.push('all');
671
+ }
672
+
673
+ // Filter by value IDs (not labels)
674
+ filteredTabs = allTabs.filter((tab) => {
675
+ const tabValueStr = tab.tab_value
676
+ ? String(tab.tab_value).toLowerCase()
677
+ : '';
678
+ return showValues.includes(tabValueStr);
679
+ });
680
+
681
+ // Handle "all" tab
682
+ const allTab = filteredTabs.find(
683
+ (tab) => tab.tab_value?.toString().toLowerCase() === 'all',
684
+ );
685
+ filteredTabs = filteredTabs.filter(
686
+ (tab) => tab.tab_value?.toString().toLowerCase() !== 'all',
687
+ );
688
+
689
+ // SORTING LOGIC
690
+ if (layout.sorting === 'asc') {
691
+ filteredTabs.sort((a, b) =>
692
+ a.tab_value.toString().localeCompare(b.tab_value.toString()),
693
+ );
694
+ } else if (layout.sorting === 'dsc') {
695
+ filteredTabs.sort((a, b) =>
696
+ b.tab_value.toString().localeCompare(a.tab_value.toString()),
697
+ );
698
+ } else if (layout.sorting === 'count_asc') {
699
+ filteredTabs.sort((a, b) => a.tab_value_count - b.tab_value_count);
700
+ } else if (layout.sorting === 'count_dsc') {
701
+ filteredTabs.sort((a, b) => b.tab_value_count - a.tab_value_count);
702
+ } else if (layout.sorting === 'custom') {
703
+ // Keep order same as showList
704
+ const orderMap = new Map<string, number>(
705
+ showList.map((item, index) => [
706
+ item.value?.toString().toLowerCase(),
707
+ index,
708
+ ]),
709
+ );
710
+ filteredTabs.sort((a, b) => {
711
+ const aIndex =
712
+ orderMap.get(a.tab_value?.toString().toLowerCase()) ?? Infinity;
713
+ const bIndex =
714
+ orderMap.get(b.tab_value?.toString().toLowerCase()) ?? Infinity;
715
+ return aIndex - bIndex;
716
+ });
717
+ }
718
+
719
+ // Re-add "all" tab at beginning if needed
720
+ if (allTab) filteredTabs.unshift(allTab);
721
+
722
+ // Combine others if enabled
723
+ if (layout?.isCombineOther) {
724
+ const originalAllTab = allTabs.find(
725
+ (tab) => tab.tab_value?.toString().toLowerCase() === 'all',
726
+ );
727
+ const allCount = originalAllTab?.tab_value_count ?? 0;
728
+ const knownTabCountSum = filteredTabs
729
+ .filter((tab) => tab.tab_value?.toString().toLowerCase() !== 'all')
730
+ .reduce((acc, tab) => acc + tab.tab_value_count, 0);
731
+
732
+ const othersCount = allCount - knownTabCountSum;
733
+ filteredTabs.push({
734
+ tab_value: 'OTHERS',
735
+ tab_value_count: othersCount < 0 ? 0 : othersCount,
736
+ });
737
+ }
738
+ } else {
739
+ filteredTabs = allTabs;
740
+ }
741
+
742
+ return filteredTabs;
743
+ }
744
+
745
+ // SORTING LOGIC FOR TABS
746
+ private async sortTabsByShowList(
747
+ qb: any,
748
+ sortby: any,
749
+ layoutPreference: any,
750
+ tabs: any,
751
+ ) {
752
+ const sorting = layoutPreference?.mapped_json?.sorting;
753
+
754
+ if (sorting) {
755
+ if (Array.isArray(sorting?.tabs)) {
756
+ const preferenceTabArray = sorting?.tabs;
757
+ const tabFilter = preferenceTabArray.find(
758
+ (tabData) => tabData.tab_name?.value === tabs?.value,
759
+ );
760
+
761
+ tabFilter?.sortby?.forEach(({ column, order }) => {
762
+ qb.addOrderBy(
763
+ `e.${column}`,
764
+ order?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
765
+ );
766
+ });
767
+ } else if (Array.isArray(sorting.sortby)) {
768
+ sorting?.sortby?.forEach(({ column, order }) => {
769
+ qb.addOrderBy(
770
+ `e.${column}`,
771
+ order?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
772
+ );
773
+ });
774
+ }
775
+ }
776
+
777
+ if (Array.isArray(sortby) && sortby.length > 0) {
778
+ sortby.forEach(({ sortColum, sortType }) => {
779
+ if (sortColum) {
780
+ qb.addOrderBy(
781
+ `e.${sortColum}`,
782
+ sortType?.toUpperCase() === 'DSC' ? 'DESC' : 'ASC',
783
+ );
784
+ }
785
+ });
786
+ } else {
787
+ // fallback if no explicit sortby sent
788
+ qb.addOrderBy('e.created_date', 'DESC');
789
+ }
790
+
791
+ return qb;
792
+ }
793
+
794
+ private parseFilters(raw: any, isSingle = false): any[] {
795
+ if (!raw) return [];
796
+
797
+ if (typeof raw === 'string') {
798
+ try {
799
+ const parsed = JSON.parse(raw);
800
+ return isSingle ? [parsed] : parsed;
801
+ } catch {
802
+ throw new BadRequestException('Invalid JSON in filter input');
803
+ }
804
+ }
805
+
806
+ return isSingle ? [raw] : Array.isArray(raw) ? raw : [];
807
+ }
808
+
809
+ private async getSavedFilters(code?: string): Promise<any[]> {
810
+ if (!code) return [];
811
+
812
+ const savedFilter = await this.savedFilterService.getDetailsByCode(code);
813
+ if (!savedFilter) {
814
+ throw new BadRequestException(`Saved filter not found for code: ${code}`);
815
+ }
816
+ return savedFilter;
817
+ }
818
+
819
+ private buildWhereClauses(
820
+ filters: any[],
821
+ attributeMeta: Record<string, any>,
822
+ ) {
823
+ return filters
824
+ .map((f) => {
825
+ const clause = this.buildCondition(
826
+ f,
827
+ attributeMeta[f.filter_attribute],
828
+ );
829
+
830
+ if (!clause) return null;
831
+
832
+ // Force every param to be a string
833
+ if (clause.params) {
834
+ Object.keys(clause.params).forEach((k) => {
835
+ const val = clause.params[k];
836
+ if (!Array.isArray(val)) {
837
+ clause.params[k] = String(val); // only convert scalar values
838
+ }
839
+ });
840
+ }
841
+
842
+ return clause;
843
+ })
844
+ .filter(
845
+ (clause): clause is { query: string; params: Record<string, string> } =>
846
+ clause !== null,
847
+ );
848
+ }
849
+
850
+ private buildCondition(
851
+ filter: any,
852
+ meta: any,
853
+ ): { query: string; params: any } | null {
854
+ if (!meta) return null;
855
+
856
+ let attr = filter.filter_attribute;
857
+ const val = filter.filter_value;
858
+ const op = filter.filter_operator;
859
+ const key = `param_${attr}_${Math.random().toString(36).substring(2, 8)}`;
860
+
861
+ // if (
862
+ // (meta.data_source_type === 'entity' ||
863
+ // meta.data_source_type === 'master') &&
864
+ // !filter.skip_id
865
+ // ) {
866
+ // attr = `${attr}_id`;
867
+ // }
868
+
869
+ switch (meta.data_type) {
870
+ case 'text':
871
+ return this.buildTextCondition(attr, op, val, key);
872
+ case 'number':
873
+ return this.buildNumberCondition(attr, op, val, key);
874
+ case 'date':
875
+ return this.buildDateCondition(attr, op, val, key);
876
+ case 'select':
877
+ return this.buildMultiSelectCondition(attr, op, val, key);
878
+ case 'multiselect':
879
+ return this.buildMultiSelectCondition(attr, op, val, key);
880
+ case 'checkbox':
881
+ return this.buildMultiSelectCondition(attr, op, val, key);
882
+ case 'radio':
883
+ return this.buildMultiSelectCondition(attr, op, val, key);
884
+ case 'year':
885
+ return this.buildYearCondition(attr, op, val, key);
886
+ default:
887
+ return null;
888
+ }
889
+ }
890
+
891
+ private buildTextCondition(attr: string, op: string, val: any, key: string) {
892
+ switch (op) {
893
+ case 'contains':
894
+ return {
895
+ query: `LOWER(e.${attr}) LIKE :${key}`,
896
+ params: { [key]: `%${val ? val.toLowerCase() : ''}%` },
897
+ };
898
+ case 'equal':
899
+ return {
900
+ query: `e.${attr} = :${key}`,
901
+ params: { [key]: val },
902
+ };
903
+ case 'not_equal':
904
+ return {
905
+ query: `e.${attr} != :${key}`,
906
+ params: { [key]: val },
907
+ };
908
+ case 'empty':
909
+ return {
910
+ query: `e.${attr} IS NULL`,
911
+ params: {},
912
+ };
913
+ case 'not_empty':
914
+ return {
915
+ query: `e.${attr} IS NOT NULL`,
916
+ params: {},
917
+ };
918
+ default:
919
+ throw new BadRequestException(`Unsupported operator for text: ${op}`);
920
+ }
921
+ }
922
+
923
+ private buildNumberCondition(
924
+ attr: string,
925
+ op: string,
926
+ val: any,
927
+ key: string,
928
+ ) {
929
+ switch (op) {
930
+ case 'equal':
931
+ return { query: `e.${attr} = :${key}`, params: { [key]: val } };
932
+ case 'not_equal':
933
+ return { query: `e.${attr} != :${key}`, params: { [key]: val } };
934
+ case 'greater_than':
935
+ return { query: `e.${attr} > :${key}`, params: { [key]: val } };
936
+ case 'less_than':
937
+ return { query: `e.${attr} < :${key}`, params: { [key]: val } };
938
+ case 'less_than_qual_to':
939
+ return { query: `e.${attr} <= :${key}`, params: { [key]: val } };
940
+ case 'greater_than_qual_to':
941
+ return { query: `e.${attr} >= :${key}`, params: { [key]: val } };
942
+ case 'empty':
943
+ return { query: `e.${attr} IS NULL`, params: {} };
944
+ case 'not_empty':
945
+ return { query: `e.${attr} IS NOT NULL`, params: {} };
946
+
947
+ default:
948
+ throw new BadRequestException(`Unsupported operator for number: ${op}`);
949
+ }
950
+ }
951
+
952
+ private buildDateCondition(attr: string, op: string, val: any, key: string) {
953
+ const dateColumn = `DATE(e.${attr})`;
954
+ const monthColumn = `DATE_TRUNC('month', e.${attr})`;
955
+
956
+ // convert to number when needed
957
+ const numVal = Number(val);
958
+
959
+ // INSIDE buildDateCondition
960
+ const subtractBusinessDays = (days: number): string => {
961
+ let d = new Date();
962
+ let count = 0;
963
+
964
+ while (count < days) {
965
+ d.setDate(d.getDate() - 1);
966
+
967
+ const day = d.getDay(); // 0 = Sunday, 6 = Saturday
968
+
969
+ if (day !== 0 && day !== 6) {
970
+ count++;
971
+ }
972
+ }
973
+
974
+ return d.toISOString().split('T')[0];
975
+ };
976
+
977
+ switch (op) {
978
+ // ============================================
979
+ // BASIC COMPARISONS
980
+ // ============================================
981
+ case 'equal':
982
+ case 'is':
983
+ return {
984
+ query: `${dateColumn} = :${key}`,
985
+ params: { [key]: val },
986
+ };
987
+
988
+ case 'before':
989
+ case 'is_before':
990
+ return {
991
+ query: `${dateColumn} < :${key}`,
992
+ params: { [key]: val },
993
+ };
994
+
995
+ case 'after':
996
+ case 'is_after':
997
+ return {
998
+ query: `${dateColumn} > :${key}`,
999
+ params: { [key]: val },
1000
+ };
1001
+
1002
+ case 'is_on_or_before':
1003
+ return {
1004
+ query: `${dateColumn} <= :${key}`,
1005
+ params: { [key]: val },
1006
+ };
1007
+
1008
+ case 'is_on_or_after':
1009
+ return {
1010
+ query: `${dateColumn} >= :${key}`,
1011
+ params: { [key]: val },
1012
+ };
1013
+
1014
+ // ============================================
1015
+ // EMPTY / NOT EMPTY
1016
+ // ============================================
1017
+ case 'empty':
1018
+ return {
1019
+ query: `e.${attr} IS NULL`,
1020
+ params: {},
1021
+ };
1022
+
1023
+ case 'not_empty':
1024
+ return {
1025
+ query: `e.${attr} IS NOT NULL`,
1026
+ params: {},
1027
+ };
1028
+
1029
+ // ============================================
1030
+ // DAY OFFSET LOGIC (ALWAYS ADJUST -1 DAY)
1031
+ // ============================================
1032
+ case 'is_day_before':
1033
+ if (isNaN(numVal)) {
1034
+ throw new BadRequestException(
1035
+ 'Value must be a number for is_day_before',
1036
+ );
1037
+ }
1038
+
1039
+ const dayBefore = (() => {
1040
+ const d = new Date();
1041
+ d.setDate(d.getDate() - numVal);
1042
+
1043
+ // Format as YYYY-MM-DD in IST
1044
+ return d.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });
1045
+ })();
1046
+
1047
+ return {
1048
+ query: `${dateColumn} <= :${key}`,
1049
+ params: { [key]: dayBefore },
1050
+ };
1051
+
1052
+ case 'is_day_after':
1053
+ if (isNaN(numVal)) {
1054
+ throw new BadRequestException(
1055
+ 'Value must be a number for is_day_after',
1056
+ );
1057
+ }
1058
+
1059
+ const dayAfter = (() => {
1060
+ const d = new Date();
1061
+ d.setDate(d.getDate() - 1 + numVal); // -1 because DB stores previous day
1062
+ return d.toISOString().split('T')[0];
1063
+ })();
1064
+
1065
+ return {
1066
+ query: `${dateColumn} > :${key}`,
1067
+ params: { [key]: dayAfter },
1068
+ };
1069
+
1070
+ // ============================================
1071
+ // MONTH OFFSET LOGIC
1072
+ // ============================================
1073
+ case 'is_month_before':
1074
+ if (isNaN(numVal)) {
1075
+ throw new BadRequestException(
1076
+ 'Value must be a number for is_month_before',
1077
+ );
1078
+ }
1079
+
1080
+ const monthBefore = (() => {
1081
+ const d = new Date();
1082
+ d.setMonth(d.getMonth() - numVal);
1083
+ d.setDate(1);
1084
+ d.setDate(d.getDate() - 1);
1085
+ return d.toISOString().split('T')[0];
1086
+ })();
1087
+
1088
+ return {
1089
+ query: `${monthColumn} < DATE_TRUNC('month', (:${key})::date)`,
1090
+ params: { [key]: monthBefore },
1091
+ };
1092
+
1093
+ case 'is_month_after':
1094
+ if (isNaN(numVal)) {
1095
+ throw new BadRequestException(
1096
+ 'Value must be a number for is_month_after',
1097
+ );
1098
+ }
1099
+
1100
+ const monthAfter = (() => {
1101
+ const d = new Date();
1102
+ d.setMonth(d.getMonth() + numVal);
1103
+ d.setDate(1);
1104
+ d.setDate(d.getDate() - 1);
1105
+ return d.toISOString().split('T')[0];
1106
+ })();
1107
+
1108
+ return {
1109
+ query: `${monthColumn} > DATE_TRUNC('month', (:${key})::date)`,
1110
+ params: { [key]: monthAfter },
1111
+ };
1112
+
1113
+ // ===== BETWEEN =====
1114
+ case 'between': {
1115
+ if (typeof val === 'string') {
1116
+ val = val.split(',').map((v) => v.trim());
1117
+ }
1118
+
1119
+ if (
1120
+ !Array.isArray(val) ||
1121
+ val.length !== 2 ||
1122
+ val[0] === '' ||
1123
+ val[1] === ''
1124
+ ) {
1125
+ console.log(`Invalid value for between: ${val}`);
1126
+ return null;
1127
+ }
1128
+
1129
+ return {
1130
+ query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1131
+ params: {
1132
+ [`${key}_start`]: val[0],
1133
+ [`${key}_end`]: val[1],
1134
+ },
1135
+ };
1136
+ }
1137
+
1138
+ // ===== TODAY =====
1139
+ case 'today': {
1140
+ const today = moment().format('YYYY-MM-DD');
1141
+ return {
1142
+ query: `${dateColumn} = :today`,
1143
+ params: { today },
1144
+ };
1145
+ }
1146
+
1147
+ // ============================================
1148
+ // BUSINESS DAY OFFSET LOGIC (SKIPS WEEKENDS)
1149
+ // ALWAYS ADJUST -1 DAY FOR DB SHIFT
1150
+ // ============================================
1151
+
1152
+ case 'is_before_business_days': {
1153
+ if (isNaN(numVal)) {
1154
+ throw new BadRequestException('Value must be a number');
1155
+ }
1156
+
1157
+ const targetDate = subtractBusinessDays(numVal);
1158
+
1159
+ return {
1160
+ query: `${dateColumn} <= :${key} AND EXTRACT(DOW FROM ${dateColumn}) NOT IN (0, 6)`,
1161
+ params: { [key]: targetDate },
1162
+ };
1163
+ }
1164
+
1165
+ case 'is_after_business_days': {
1166
+ if (isNaN(numVal)) {
1167
+ throw new BadRequestException(
1168
+ 'Value must be a number for is_after_business_days',
1169
+ );
1170
+ }
1171
+
1172
+ const businessAfter = (() => {
1173
+ let d = new Date();
1174
+ let count = 0;
1175
+
1176
+ while (count < numVal) {
1177
+ d.setDate(d.getDate() + 1);
1178
+ const day = d.getDay(); // 0=Sun, 6=Sat
1179
+ if (day !== 0 && day !== 6) count++;
1180
+ }
1181
+
1182
+ // DB shift -1 day
1183
+ d.setDate(d.getDate() - 1);
1184
+
1185
+ return d.toISOString().split('T')[0];
1186
+ })();
1187
+
1188
+ return {
1189
+ query: `${dateColumn} > :${key}`,
1190
+ params: { [key]: businessAfter },
1191
+ };
1192
+ }
1193
+
1194
+ // ============================================
1195
+ // IN LAST DAY (range: today to N days before)
1196
+ // ============================================
1197
+ case 'in_last_day': {
1198
+ if (isNaN(numVal)) {
1199
+ throw new BadRequestException(
1200
+ 'Value must be a number for in_last_day',
1201
+ );
1202
+ }
1203
+
1204
+ const today = (() => {
1205
+ const d = new Date();
1206
+ return d.toISOString().split('T')[0];
1207
+ })();
1208
+
1209
+ const lastN = (() => {
1210
+ const d = new Date();
1211
+ d.setDate(d.getDate() - numVal);
1212
+ return d.toISOString().split('T')[0];
1213
+ })();
1214
+
1215
+ return {
1216
+ query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1217
+ params: {
1218
+ [`${key}_start`]: lastN,
1219
+ [`${key}_end`]: today,
1220
+ },
1221
+ };
1222
+ }
1223
+
1224
+ // ============================================
1225
+ // IN NEXT DAY (range: today to N days after)
1226
+ // ============================================
1227
+ case 'in_next_day': {
1228
+ if (isNaN(numVal)) {
1229
+ throw new BadRequestException(
1230
+ 'Value must be a number for in_next_day',
1231
+ );
1232
+ }
1233
+
1234
+ const today = (() => {
1235
+ const d = new Date();
1236
+ return d.toISOString().split('T')[0];
1237
+ })();
1238
+
1239
+ const nextN = (() => {
1240
+ const d = new Date();
1241
+ d.setDate(d.getDate() + numVal);
1242
+ return d.toISOString().split('T')[0];
1243
+ })();
1244
+
1245
+ return {
1246
+ query: `${dateColumn} BETWEEN :${key}_start AND :${key}_end`,
1247
+ params: {
1248
+ [`${key}_start`]: today,
1249
+ [`${key}_end`]: nextN,
1250
+ },
1251
+ };
1252
+ }
1253
+
1254
+ default:
1255
+ throw new BadRequestException(`Unsupported operator for date: ${op}`);
1256
+ }
1257
+ }
1258
+
1259
+ private buildSelectCondition(
1260
+ attr: string,
1261
+ op: string,
1262
+ val: any,
1263
+ key: string,
1264
+ ) {
1265
+ switch (op) {
1266
+ case 'equal':
1267
+ return { query: `e.${attr} = :${key}`, params: { [key]: val } };
1268
+ case 'not_equal':
1269
+ return { query: `e.${attr} != :${key}`, params: { [key]: val } };
1270
+ case 'empty':
1271
+ return { query: `e.${attr} IS NULL`, params: {} };
1272
+ case 'not_empty':
1273
+ return { query: `e.${attr} IS NOT NULL`, params: {} };
1274
+ default:
1275
+ throw new BadRequestException(`Unsupported operator for select: ${op}`);
1276
+ }
1277
+ }
1278
+
1279
+ private buildMultiSelectCondition(
1280
+ attr: string,
1281
+ op: string,
1282
+ val: any,
1283
+ key: string,
1284
+ ) {
1285
+ let arr: string[] = [];
1286
+
1287
+ // SAFETY: Convert all to array
1288
+ if (Array.isArray(val)) {
1289
+ arr = val.map((v) => String(v));
1290
+ } else if (typeof val === 'string') {
1291
+ arr = val.split(',').map((v) => v.trim());
1292
+ } else {
1293
+ throw new BadRequestException(`Invalid multiselect value`);
1294
+ }
1295
+
1296
+ if (arr.length === 0) {
1297
+ return { query: '1=1', params: {} };
1298
+ }
1299
+
1300
+ if (op === 'equal') {
1301
+ return {
1302
+ query: `e.${attr}::text IN (:...${key})`,
1303
+ params: { [key]: arr },
1304
+ };
1305
+ }
1306
+
1307
+ if (op === 'not_equal') {
1308
+ return {
1309
+ query: `e.${attr}::text NOT IN (:...${key})`,
1310
+ params: { [key]: arr },
1311
+ };
1312
+ }
1313
+
1314
+ if (op === 'contains') {
1315
+ return {
1316
+ query: `e.${attr}::text LIKE :${key}`,
1317
+ params: { [key]: `%${val}%` },
1318
+ };
1319
+ }
1320
+
1321
+ if (op === 'not_contains') {
1322
+ return {
1323
+ query: `e.${attr}::text NOT LIKE :${key}`,
1324
+ params: { [key]: `%${val}%` },
1325
+ };
1326
+ }
1327
+
1328
+ if (op === 'empty') return { query: `e.${attr} IS NULL`, params: {} };
1329
+ if (op === 'not_empty')
1330
+ return { query: `e.${attr} IS NOT NULL`, params: {} };
1331
+
1332
+ throw new BadRequestException(`Unsupported operator: ${op}`);
1333
+ }
1334
+
1335
+ private buildYearCondition(attr: string, op: string, val: any, key: string) {
1336
+ switch (op) {
1337
+ case 'equal':
1338
+ return {
1339
+ query: `e.${attr} = :${key}`,
1340
+ params: { [key]: parseInt(val, 10) },
1341
+ };
1342
+ case 'not_equal':
1343
+ return {
1344
+ query: `e.${attr} != :${key}`,
1345
+ params: { [key]: parseInt(val, 10) },
1346
+ };
1347
+ case 'greater_than':
1348
+ return {
1349
+ query: `e.${attr} > :${key}`,
1350
+ params: { [key]: parseInt(val, 10) },
1351
+ };
1352
+ case 'less_than':
1353
+ return {
1354
+ query: `e.${attr} < :${key}`,
1355
+ params: { [key]: parseInt(val, 10) },
1356
+ };
1357
+ default:
1358
+ throw new BadRequestException(`Unsupported operator for year: ${op}`);
1359
+ }
1360
+ }
1361
+
1362
+ async queryWithSchema(sql: string, params: any[] = []) {
1363
+ await this.entityManager.query('BEGIN');
1364
+ await this.entityManager.query(`SET LOCAL search_path TO ${this.schema}`);
1365
+ const result = await this.entityManager.query(sql, params);
1366
+ await this.entityManager.query('COMMIT');
1367
+ return result;
1368
+ }
1369
+ }