rez_core 5.0.100 → 5.0.102

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