rez_core 5.0.166 → 5.0.168

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