rez_core 5.0.87 → 5.0.88

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