rez_core 5.0.182 → 6.5.1

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