rez_core 6.1.5 → 6.1.7

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