rez_core 5.0.156 → 5.0.157

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