rez_core 5.0.101 → 5.0.102

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