rez_core 5.0.52 → 5.0.53

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