rez_core 5.0.154 → 5.0.156

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