rez_core 6.1.0 → 6.1.2

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