rez_core 3.1.134 → 3.1.136

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 (383) hide show
  1. package/.claude/settings.local.json +26 -0
  2. package/.idea/250218_nodejs_core.iml +9 -0
  3. package/.idea/codeStyles/Project.xml +59 -0
  4. package/.idea/codeStyles/codeStyleConfig.xml +5 -0
  5. package/.idea/copilot.data.migration.agent.xml +6 -0
  6. package/.idea/copilot.data.migration.ask.xml +6 -0
  7. package/.idea/copilot.data.migration.ask2agent.xml +6 -0
  8. package/.idea/copilot.data.migration.edit.xml +6 -0
  9. package/.idea/inspectionProfiles/Project_Default.xml +6 -0
  10. package/.idea/misc.xml +6 -0
  11. package/.idea/modules.xml +8 -0
  12. package/.idea/prettier.xml +6 -0
  13. package/.idea/vcs.xml +6 -0
  14. package/.prettierrc +3 -3
  15. package/README.md +99 -99
  16. package/dist/module/auth/guards/role.guard.js +3 -3
  17. package/dist/module/auth/services/auth.service.js +2 -2
  18. package/dist/module/filter/repository/saved-filter.repository.js +4 -4
  19. package/dist/module/filter/service/filter-evaluator.service.js +2 -2
  20. package/dist/module/filter/service/filter.service.js +7 -7
  21. package/dist/module/integration/examples/usage.example.js +9 -9
  22. package/dist/module/integration/service/integration.service.js +2 -1
  23. package/dist/module/integration/service/integration.service.js.map +1 -1
  24. package/dist/module/integration/service/wrapper.service.js +25 -25
  25. package/dist/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.js +1 -0
  26. package/dist/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.js.map +1 -1
  27. package/dist/module/listmaster/service/list-master-item.service.js +2 -2
  28. package/dist/module/listmaster/service/list-master.service.js +2 -2
  29. package/dist/module/mapper/service/field-mapper.service.js +4 -4
  30. package/dist/module/mapper/service/mapper.service.js +2 -2
  31. package/dist/module/meta/service/entity-dynamic.service.js +18 -18
  32. package/dist/module/meta/service/entity-list.service.js +3 -3
  33. package/dist/module/meta/service/entity-master.service.js +3 -3
  34. package/dist/module/meta/service/entity-relation.service.js +11 -11
  35. package/dist/module/meta/service/entity-service-impl.service.js +3 -3
  36. package/dist/module/meta/service/resolver.service.js +3 -3
  37. package/dist/module/module/repository/menu.repository.js +12 -12
  38. package/dist/module/notification/service/notification.service.js +12 -12
  39. package/dist/module/user/controller/login.controller.js +18 -18
  40. package/dist/module/user/service/role.service.js +4 -4
  41. package/dist/module/user/service/user-session.service.js +2 -2
  42. package/dist/module/workflow/repository/action.repository.js +16 -16
  43. package/dist/module/workflow/repository/comm-template.repository.js +6 -6
  44. package/dist/module/workflow/repository/form-master.repository.js +2 -2
  45. package/dist/module/workflow/repository/stage-group.repository.js +23 -23
  46. package/dist/module/workflow/repository/stage-movement.repository.js +11 -11
  47. package/dist/module/workflow/repository/stage.repository.js +8 -8
  48. package/dist/module/workflow/service/action-template-mapping.service.js +10 -10
  49. package/dist/module/workflow/service/action.service.js +7 -7
  50. package/dist/module/workflow/service/entity-modification.service.js +6 -6
  51. package/dist/module/workflow/service/stage-group.service.js +5 -5
  52. package/dist/module/workflow/service/stage.service.js +2 -2
  53. package/dist/module/workflow/service/task.service.js +33 -33
  54. package/dist/module/workflow/service/workflow-list-master.service.js +15 -15
  55. package/dist/module/workflow/service/workflow-meta.service.js +50 -50
  56. package/dist/module/workflow/service/workflow.service.js +2 -2
  57. package/dist/tsconfig.build.tsbuildinfo +1 -1
  58. package/dist/utils/service/reflection-helper.service.js +2 -2
  59. package/docs/modules/event-driven-integration-design.md +91 -91
  60. package/docs/modules/integration.md +250 -250
  61. package/eslint.config.mjs +34 -34
  62. package/nest-cli.json +14 -14
  63. package/package.json +118 -118
  64. package/server.log +850 -0
  65. package/src/app.controller.ts +12 -12
  66. package/src/app.module.ts +49 -49
  67. package/src/app.service.ts +8 -8
  68. package/src/config/config.module.ts +18 -18
  69. package/src/config/database.config.ts +23 -23
  70. package/src/constant/global.constant.ts +67 -67
  71. package/src/core.module.ts +81 -81
  72. package/src/decorators/roles.decorator.ts +7 -7
  73. package/src/dtos/response.dto.ts +6 -6
  74. package/src/dtos/response.ts +5 -5
  75. package/src/index.ts +1 -1
  76. package/src/module/auth/auth.module.ts +49 -49
  77. package/src/module/auth/controller/auth.controller.ts +28 -28
  78. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  79. package/src/module/auth/guards/jwt.guard.ts +22 -22
  80. package/src/module/auth/guards/role.guard.ts +68 -68
  81. package/src/module/auth/services/auth.service.ts +50 -50
  82. package/src/module/auth/services/jwt.service.ts +11 -11
  83. package/src/module/auth/strategies/google.strategy.ts +54 -54
  84. package/src/module/auth/strategies/jwt.strategy.ts +58 -58
  85. package/src/module/auth/strategies/local.strategy.ts +13 -13
  86. package/src/module/dashboard/controller/dashboard.controller.ts +36 -36
  87. package/src/module/dashboard/dashboard.module.ts +21 -21
  88. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +27 -27
  89. package/src/module/dashboard/entity/widget_master.entity.ts +18 -18
  90. package/src/module/dashboard/repository/dashboard.repository.ts +42 -42
  91. package/src/module/dashboard/service/dashboard.service.ts +73 -73
  92. package/src/module/dev/dev.module.ts +12 -12
  93. package/src/module/dev/service/dev.service.ts +7 -7
  94. package/src/module/enterprise/controller/organization.controller.ts +36 -36
  95. package/src/module/enterprise/enterprise.module.ts +30 -30
  96. package/src/module/enterprise/entity/enterprise.entity.ts +37 -37
  97. package/src/module/enterprise/entity/organization-app-mapping.entity.ts +13 -13
  98. package/src/module/enterprise/entity/organization.entity.ts +92 -92
  99. package/src/module/enterprise/repository/enterprise.repository.ts +31 -31
  100. package/src/module/enterprise/repository/organization.repository.ts +26 -26
  101. package/src/module/enterprise/repository/school.repository.ts +282 -282
  102. package/src/module/enterprise/service/brand.service.ts +5 -5
  103. package/src/module/enterprise/service/enterprise.service.ts +16 -16
  104. package/src/module/enterprise/service/organization-app-mapping.service.ts +4 -4
  105. package/src/module/enterprise/service/organization.service.ts +145 -145
  106. package/src/module/filter/controller/filter.controller.ts +84 -84
  107. package/src/module/filter/dto/filter-request.dto.ts +38 -38
  108. package/src/module/filter/entity/saved-filter-detail.entity.ts +41 -41
  109. package/src/module/filter/entity/saved-filter-master.entity.ts +23 -23
  110. package/src/module/filter/filter.module.ts +31 -31
  111. package/src/module/filter/repository/saved-filter.repository.ts +168 -168
  112. package/src/module/filter/service/filter-evaluator.service.ts +86 -86
  113. package/src/module/filter/service/filter.service.ts +841 -841
  114. package/src/module/filter/service/saved-filter.service.ts +170 -170
  115. package/src/module/ics/controller/ics.controller.ts +21 -21
  116. package/src/module/ics/dto/ics.dto.ts +55 -55
  117. package/src/module/ics/ics.module.ts +13 -13
  118. package/src/module/ics/service/ics.service.ts +60 -60
  119. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  120. package/src/module/integration/controller/integration.controller.ts +662 -662
  121. package/src/module/integration/controller/wrapper.controller.ts +39 -39
  122. package/src/module/integration/dto/create-config.dto.ts +526 -526
  123. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  124. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  125. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  126. package/src/module/integration/entity/user-integration.entity.ts +70 -70
  127. package/src/module/integration/examples/usage.example.ts +338 -338
  128. package/src/module/integration/factories/base.factory.ts +7 -7
  129. package/src/module/integration/factories/email.factory.ts +49 -49
  130. package/src/module/integration/factories/integration.factory.ts +121 -121
  131. package/src/module/integration/factories/sms.factory.ts +51 -51
  132. package/src/module/integration/factories/telephone.factory.ts +41 -41
  133. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  134. package/src/module/integration/integration.module.ts +110 -110
  135. package/src/module/integration/service/calendar-event.service.ts +118 -118
  136. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  137. package/src/module/integration/service/integration-queue.service.ts +229 -229
  138. package/src/module/integration/service/integration.service.ts +2558 -2557
  139. package/src/module/integration/service/oauth.service.ts +224 -224
  140. package/src/module/integration/service/wrapper.service.ts +515 -515
  141. package/src/module/integration/strategies/email/gmail-api.strategy.ts +288 -288
  142. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  143. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  144. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +262 -262
  145. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  146. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  147. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  148. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  149. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  150. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  151. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  152. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -371
  153. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  154. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  155. package/src/module/layout/controller/layout.controller.ts +47 -47
  156. package/src/module/layout/entity/header-items.entity.ts +28 -28
  157. package/src/module/layout/entity/header-section.entity.ts +19 -19
  158. package/src/module/layout/layout.module.ts +21 -21
  159. package/src/module/layout/repository/header-items.repository.ts +18 -18
  160. package/src/module/layout/repository/header-section.repository.ts +22 -22
  161. package/src/module/layout/service/header-section.service.ts +25 -25
  162. package/src/module/layout_preference/controller/layout_preference.controller.ts +47 -47
  163. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  164. package/src/module/layout_preference/layout_preference.module.ts +18 -18
  165. package/src/module/layout_preference/repository/layout_preference.repository.ts +30 -30
  166. package/src/module/layout_preference/service/layout_preference.service.ts +172 -172
  167. package/src/module/lead/controller/lead.controller.ts +30 -30
  168. package/src/module/lead/lead.module.ts +14 -14
  169. package/src/module/lead/repository/lead.repository.ts +41 -41
  170. package/src/module/lead/service/lead.service.ts +54 -54
  171. package/src/module/listmaster/controller/list-master.controller.ts +143 -143
  172. package/src/module/listmaster/entity/list-master-items.entity.ts +41 -41
  173. package/src/module/listmaster/entity/list-master.entity.ts +32 -32
  174. package/src/module/listmaster/listmaster.module.ts +30 -30
  175. package/src/module/listmaster/repository/list-master-items.repository.ts +169 -169
  176. package/src/module/listmaster/repository/list-master.repository.ts +46 -46
  177. package/src/module/listmaster/service/list-master-item.service.ts +292 -292
  178. package/src/module/listmaster/service/list-master.service.ts +360 -360
  179. package/src/module/mapper/controller/field-mapper.controller.ts +69 -69
  180. package/src/module/mapper/controller/mapper.controller.ts +14 -14
  181. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  182. package/src/module/mapper/entity/field-lovs.entity.ts +20 -20
  183. package/src/module/mapper/entity/field-mapper.entity.ts +37 -37
  184. package/src/module/mapper/entity/mapper.entity.ts +17 -17
  185. package/src/module/mapper/mapper.module.ts +34 -34
  186. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  187. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  188. package/src/module/mapper/repository/mapper.repository.ts +15 -15
  189. package/src/module/mapper/service/field-mapper.service.ts +223 -223
  190. package/src/module/mapper/service/mapper.service.ts +72 -72
  191. package/src/module/master/controller/master.controller.ts +74 -74
  192. package/src/module/master/service/master.service.ts +486 -486
  193. package/src/module/meta/controller/app-master.controller.ts +38 -38
  194. package/src/module/meta/controller/attribute-master.controller.ts +66 -66
  195. package/src/module/meta/controller/entity-dynamic.controller.ts +125 -125
  196. package/src/module/meta/controller/entity-master.controller.ts +28 -28
  197. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  198. package/src/module/meta/controller/entity.controller.ts +385 -385
  199. package/src/module/meta/controller/media.controller.ts +82 -82
  200. package/src/module/meta/controller/meta.controller.ts +96 -96
  201. package/src/module/meta/controller/view-master.controller.ts +86 -86
  202. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  203. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  204. package/src/module/meta/dto/entity-table.dto.ts +9 -9
  205. package/src/module/meta/entity/app-master.entity.ts +34 -34
  206. package/src/module/meta/entity/attribute-master.entity.ts +87 -87
  207. package/src/module/meta/entity/base-entity.entity.ts +75 -75
  208. package/src/module/meta/entity/entity-master.entity.ts +78 -78
  209. package/src/module/meta/entity/entity-relation-data.entity.ts +29 -29
  210. package/src/module/meta/entity/entity-relation.entity.ts +23 -23
  211. package/src/module/meta/entity/entity-table-column.entity.ts +61 -61
  212. package/src/module/meta/entity/entity-table.entity.ts +50 -50
  213. package/src/module/meta/entity/media-data.entity.ts +32 -32
  214. package/src/module/meta/entity/preference.entity.ts +62 -62
  215. package/src/module/meta/entity/view-master.entity.ts +41 -41
  216. package/src/module/meta/entity.module.ts +156 -156
  217. package/src/module/meta/repository/app-master.repository.ts +20 -20
  218. package/src/module/meta/repository/attribute-master.repository.ts +110 -110
  219. package/src/module/meta/repository/entity-master.repository.ts +66 -66
  220. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  221. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  222. package/src/module/meta/repository/media-data.repository.ts +50 -50
  223. package/src/module/meta/repository/preference.repository.ts +20 -20
  224. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  225. package/src/module/meta/repository/view-master.repository.ts +42 -42
  226. package/src/module/meta/service/app-master.service.ts +37 -37
  227. package/src/module/meta/service/attribute-master.service.ts +117 -117
  228. package/src/module/meta/service/common.service.ts +9 -9
  229. package/src/module/meta/service/entity-dynamic.service.ts +762 -762
  230. package/src/module/meta/service/entity-list.service.ts +205 -205
  231. package/src/module/meta/service/entity-master.service.ts +164 -164
  232. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  233. package/src/module/meta/service/entity-relation.service.ts +69 -69
  234. package/src/module/meta/service/entity-service-impl.service.ts +524 -524
  235. package/src/module/meta/service/entity-table-column.service.ts +39 -39
  236. package/src/module/meta/service/entity-table.service.ts +150 -150
  237. package/src/module/meta/service/entity-validation.service.ts +185 -185
  238. package/src/module/meta/service/entity.service.ts +67 -67
  239. package/src/module/meta/service/field-group.service.ts +103 -103
  240. package/src/module/meta/service/media-data.service.ts +140 -140
  241. package/src/module/meta/service/populate-meta.service.ts +174 -174
  242. package/src/module/meta/service/preference.service.ts +16 -16
  243. package/src/module/meta/service/resolver.service.ts +256 -256
  244. package/src/module/meta/service/section-master.service.ts +104 -104
  245. package/src/module/meta/service/update-form-json.service.ts +22 -22
  246. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  247. package/src/module/meta/service/view-master.service.ts +111 -111
  248. package/src/module/module/controller/menu.controller.ts +15 -15
  249. package/src/module/module/controller/module-access.controller.ts +132 -132
  250. package/src/module/module/entity/menu.entity.ts +43 -43
  251. package/src/module/module/entity/module-access.entity.ts +25 -25
  252. package/src/module/module/entity/module-action.entity.ts +17 -17
  253. package/src/module/module/entity/module.entity.ts +52 -52
  254. package/src/module/module/module.module.ts +42 -42
  255. package/src/module/module/repository/menu.repository.ts +184 -184
  256. package/src/module/module/repository/module-access.repository.ts +327 -327
  257. package/src/module/module/service/menu.service.ts +82 -82
  258. package/src/module/module/service/module-access.service.ts +209 -209
  259. package/src/module/notification/controller/notification.controller.ts +58 -58
  260. package/src/module/notification/controller/otp.controller.ts +117 -117
  261. package/src/module/notification/entity/notification.entity.ts +23 -23
  262. package/src/module/notification/entity/otp.entity.ts +28 -28
  263. package/src/module/notification/firebase-admin.config.ts +22 -22
  264. package/src/module/notification/notification.module.ts +69 -69
  265. package/src/module/notification/repository/otp.repository.ts +27 -27
  266. package/src/module/notification/service/email.service.ts +127 -127
  267. package/src/module/notification/service/notification.service.ts +138 -138
  268. package/src/module/notification/service/otp.service.ts +121 -121
  269. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  270. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  271. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  272. package/src/module/third-party-module/third-party.module.ts +12 -12
  273. package/src/module/user/controller/login.controller.ts +197 -197
  274. package/src/module/user/controller/user.controller.ts +40 -40
  275. package/src/module/user/dto/create-user.dto.ts +62 -62
  276. package/src/module/user/dto/update-user.dto.ts +4 -4
  277. package/src/module/user/entity/role.entity.ts +33 -33
  278. package/src/module/user/entity/user-role-mapping.entity.ts +38 -38
  279. package/src/module/user/entity/user-session.entity.ts +61 -61
  280. package/src/module/user/entity/user.entity.ts +68 -68
  281. package/src/module/user/repository/role.repository.ts +96 -96
  282. package/src/module/user/repository/user-role-mapping.repository.ts +126 -126
  283. package/src/module/user/repository/user.repository.ts +50 -50
  284. package/src/module/user/repository/userSession.repository.ts +33 -33
  285. package/src/module/user/service/login.service.ts +280 -280
  286. package/src/module/user/service/role.service.ts +189 -189
  287. package/src/module/user/service/user-role-mapping.service.ts +98 -98
  288. package/src/module/user/service/user-session.service.ts +168 -168
  289. package/src/module/user/service/user.service.ts +353 -353
  290. package/src/module/user/user.module.ts +65 -65
  291. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  292. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  293. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  294. package/src/module/workflow/controller/action.controller.ts +95 -95
  295. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  296. package/src/module/workflow/controller/comm-template.controller.ts +34 -34
  297. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  298. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  299. package/src/module/workflow/controller/stage-group.controller.ts +48 -48
  300. package/src/module/workflow/controller/stage.controller.ts +50 -50
  301. package/src/module/workflow/controller/task.controller.ts +77 -77
  302. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  303. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  304. package/src/module/workflow/controller/workflow.controller.ts +67 -67
  305. package/src/module/workflow/entity/action-category.entity.ts +38 -38
  306. package/src/module/workflow/entity/action-data.entity.ts +55 -55
  307. package/src/module/workflow/entity/action-resources-mapping.entity.ts +29 -29
  308. package/src/module/workflow/entity/action-template-mapping.entity.ts +17 -17
  309. package/src/module/workflow/entity/action.entity.ts +50 -50
  310. package/src/module/workflow/entity/activity-log.entity.ts +43 -43
  311. package/src/module/workflow/entity/comm-template.entity.ts +43 -43
  312. package/src/module/workflow/entity/entity-modification.entity.ts +38 -38
  313. package/src/module/workflow/entity/form-master.entity.ts +27 -27
  314. package/src/module/workflow/entity/form.entity.ts +25 -25
  315. package/src/module/workflow/entity/stage-action-mapping.entity.ts +17 -17
  316. package/src/module/workflow/entity/stage-group.entity.ts +23 -23
  317. package/src/module/workflow/entity/stage-movement-data.entity.ts +38 -38
  318. package/src/module/workflow/entity/stage.entity.ts +20 -20
  319. package/src/module/workflow/entity/task-data.entity.ts +88 -88
  320. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  321. package/src/module/workflow/entity/workflow-data.entity.ts +11 -11
  322. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  323. package/src/module/workflow/entity/workflow.entity.ts +20 -20
  324. package/src/module/workflow/repository/action-category.repository.ts +79 -79
  325. package/src/module/workflow/repository/action-data.repository.ts +219 -219
  326. package/src/module/workflow/repository/action.repository.ts +277 -277
  327. package/src/module/workflow/repository/activity-log.repository.ts +121 -121
  328. package/src/module/workflow/repository/comm-template.repository.ts +142 -142
  329. package/src/module/workflow/repository/form-master.repository.ts +61 -61
  330. package/src/module/workflow/repository/stage-group.repository.ts +176 -176
  331. package/src/module/workflow/repository/stage-movement.repository.ts +227 -227
  332. package/src/module/workflow/repository/stage.repository.ts +172 -172
  333. package/src/module/workflow/repository/task.repository.ts +113 -113
  334. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  335. package/src/module/workflow/service/action-category.service.ts +33 -33
  336. package/src/module/workflow/service/action-data.service.ts +62 -62
  337. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  338. package/src/module/workflow/service/action-template-mapping.service.ts +55 -55
  339. package/src/module/workflow/service/action.service.ts +247 -247
  340. package/src/module/workflow/service/activity-log.service.ts +107 -107
  341. package/src/module/workflow/service/comm-template.service.ts +121 -121
  342. package/src/module/workflow/service/entity-modification.service.ts +67 -67
  343. package/src/module/workflow/service/form-master.service.ts +35 -35
  344. package/src/module/workflow/service/populate-workflow.service.ts +303 -303
  345. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  346. package/src/module/workflow/service/stage-group.service.ts +300 -300
  347. package/src/module/workflow/service/stage.service.ts +199 -199
  348. package/src/module/workflow/service/task.service.ts +504 -504
  349. package/src/module/workflow/service/workflow-list-master.service.ts +60 -60
  350. package/src/module/workflow/service/workflow-meta.service.ts +581 -581
  351. package/src/module/workflow/service/workflow.service.ts +205 -205
  352. package/src/module/workflow/workflow.module.ts +176 -176
  353. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +21 -21
  354. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  355. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +35 -35
  356. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  357. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  358. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  359. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +214 -214
  360. package/src/module/workflow-automation/service/workflow-automation.service.ts +343 -343
  361. package/src/module/workflow-automation/workflow-automation.module.ts +34 -34
  362. package/src/resources/dev.properties.yaml +30 -30
  363. package/src/resources/local.properties.yaml +23 -23
  364. package/src/resources/properties.module.ts +12 -12
  365. package/src/resources/properties.yaml.ts +11 -11
  366. package/src/resources/uat.properties.yaml +15 -15
  367. package/src/utils/dto/excel-data.dto.ts +14 -14
  368. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  369. package/src/utils/service/base64util.service.ts +18 -18
  370. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  371. package/src/utils/service/codeGenerator.service.ts +22 -22
  372. package/src/utils/service/dateUtil.service.ts +17 -17
  373. package/src/utils/service/encryptUtil.service.ts +97 -97
  374. package/src/utils/service/excel-helper.service.ts +72 -72
  375. package/src/utils/service/excelUtil.service.ts +15 -15
  376. package/src/utils/service/file-util.service.ts +11 -11
  377. package/src/utils/service/json-util.service.ts +23 -23
  378. package/src/utils/service/loggingUtil.service.ts +34 -34
  379. package/src/utils/service/reflection-helper.service.ts +62 -62
  380. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  381. package/src/utils/utils.module.ts +25 -25
  382. package/tsconfig.build.json +4 -4
  383. package/tsconfig.json +24 -24
@@ -1,2557 +1,2558 @@
1
- import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
2
- import { InjectRepository } from '@nestjs/typeorm';
3
- import { DataSource, Not, Repository } from 'typeorm';
4
- import { ConfigService } from '@nestjs/config';
5
- import { google } from 'googleapis';
6
- import { IntegrationConfig } from '../entity/integration-config.entity';
7
- import { UserIntegration } from '../entity/user-integration.entity';
8
- import { IntegrationEntityMapper } from '../entity/integration-entity-mapper.entity';
9
- import { IntegrationFactory } from '../factories/integration.factory';
10
- import { IntegrationResult } from '../strategies/integration.strategy';
11
- import { GmailApiStrategy } from '../strategies/email/gmail-api.strategy';
12
- import { SendGridApiStrategy } from '../strategies/email/sendgrid-api.strategy';
13
- import { IntegrationQueueService } from './integration-queue.service';
14
- import {
15
- BulkMessageDto,
16
- BulkCreateUserIntegrationDto,
17
- CreateUserIntegrationDto,
18
- UpdateUserIntegrationDto,
19
- } from '../dto/create-config.dto';
20
- import { FieldMapperService } from '../../mapper/service/field-mapper.service';
21
- import { COMM_TEMPLATE } from '../../../constant/global.constant';
22
- import { EntityServiceImpl } from '../../meta/service/entity-service-impl.service';
23
-
24
- export interface SendMessageDto {
25
- levelId: number;
26
- levelType: string;
27
- app_code: string;
28
- to: string;
29
- message: string;
30
- mode?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
31
- priority?: number;
32
- user_id?: number;
33
- }
34
-
35
- export interface GenericMessageDto {
36
- levelId: number;
37
- levelType: string;
38
- app_code: string;
39
- to: string | string[];
40
- message: string;
41
- subject?: string;
42
- type?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
43
- priority?: 'high' | 'medium' | 'low';
44
- cc?: string | string[];
45
- bcc?: string | string[];
46
- html?: string;
47
- attachments?: any[];
48
- mediaUrl?: string;
49
- templateId?: string;
50
- variables?: Record<string, any>;
51
- user_id?: number;
52
- entity_type?: string;
53
- entity_id?: number;
54
- }
55
-
56
- export interface IntegrationConfigWithConfig extends IntegrationConfig {
57
- config?: any;
58
- }
59
-
60
- interface GmailOAuthState {
61
- levelId: number;
62
- levelType: string;
63
- app_code: string;
64
- email?: string;
65
- timestamp: number;
66
- }
67
-
68
- export interface GmailSSOResult {
69
- hubId: number;
70
- configId: number;
71
- }
72
-
73
- @Injectable()
74
- export class IntegrationService {
75
- private readonly logger = new Logger(IntegrationService.name);
76
- private readonly gmailOAuthStates = new Map<string, GmailOAuthState>();
77
-
78
- constructor(
79
- @InjectRepository(IntegrationConfig)
80
- private readonly configRepository: Repository<IntegrationConfig>,
81
- @InjectRepository(UserIntegration)
82
- private readonly userIntegrationRepository: Repository<UserIntegration>,
83
- @InjectRepository(IntegrationEntityMapper)
84
- private readonly entityMapperRepository: Repository<IntegrationEntityMapper>,
85
- private readonly dataSource: DataSource,
86
- private readonly integrationFactory: IntegrationFactory,
87
- private readonly gmailApiStrategy: GmailApiStrategy,
88
- private readonly sendGridApiStrategy: SendGridApiStrategy,
89
- private readonly configService: ConfigService,
90
- @Inject('FieldMapperService') private readonly fieldMapperService: FieldMapperService,
91
- private readonly entityService: EntityServiceImpl,
92
- @Inject(forwardRef(() => IntegrationQueueService))
93
- private readonly queueService?: IntegrationQueueService,
94
- ) {
95
- }
96
-
97
- private deriveServiceType(
98
- integration_type: string,
99
- integration_provider: string,
100
- config_json: any,
101
- ): string {
102
- // All integrations use API only (no SMTP support)
103
- return 'API';
104
- }
105
-
106
- async sendMessage({
107
- levelId,
108
- levelType,
109
- app_code,
110
- to,
111
- message,
112
- mode,
113
- priority = 1,
114
- user_id,
115
- }: SendMessageDto): Promise<IntegrationResult> {
116
- try {
117
- // Get active communication configs for the level
118
- const configs = await this.getActiveConfigs(
119
- levelId,
120
- levelType,
121
- app_code,
122
- mode,
123
- );
124
-
125
- if (!configs.length) {
126
- throw new Error(
127
- `No active communication configuration found for ${levelType} ${levelId}`,
128
- );
129
- }
130
-
131
- // Sort by priority if provided
132
- const sortedConfigs = this.sortConfigsByPriority(configs, priority);
133
-
134
- // Try each config until one succeeds
135
- for (const config of sortedConfigs) {
136
- try {
137
- const result = await this.sendViaConfig(config, to, message, user_id);
138
- if (result.success) {
139
- this.logger.log(
140
- `Message sent successfully via ${config.integration_provider}`,
141
- );
142
- return result;
143
- }
144
-
145
- this.logger.warn(
146
- `Failed to send via ${config.integration_provider}: ${result.error}`,
147
- );
148
- } catch (error) {
149
- this.logger.error(
150
- `Error sending via ${config.integration_provider}:`,
151
- error.message,
152
- );
153
- continue;
154
- }
155
- }
156
-
157
- throw new Error('All communication providers failed');
158
- } catch (error) {
159
- this.logger.error('Communication service error:', error.message);
160
- throw error;
161
- }
162
- }
163
-
164
- async getActiveConfigs(
165
- levelId: number,
166
- levelType: string,
167
- app_code: string,
168
- mode?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
169
- ): Promise<IntegrationConfig[]> {
170
- const queryBuilder = this.configRepository
171
- .createQueryBuilder('config')
172
- .where('config.level_id = :levelId', { levelId })
173
- .andWhere('config.level_type = :levelType', { levelType })
174
- .andWhere('config.app_code = :app_code', { app_code })
175
- .andWhere('config.status = 1');
176
-
177
- if (mode) {
178
- queryBuilder.andWhere('config.integration_type = :mode', { mode });
179
- }
180
-
181
- return await queryBuilder.getMany();
182
- }
183
-
184
- async getSingleActiveConfig(
185
- levelId: number,
186
- levelType: string,
187
- app_code: string,
188
- integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
189
- ): Promise<IntegrationConfig | null> {
190
- const configs = await this.configRepository
191
- .createQueryBuilder('config')
192
- .where('config.level_id = :levelId', { levelId })
193
- .andWhere('config.level_type = :levelType', { levelType })
194
- .andWhere('config.app_code = :app_code', { app_code })
195
- .andWhere('config.integration_type = :integration_type', { integration_type })
196
- .andWhere('config.status = 1')
197
- .orderBy('config.is_default', 'DESC')
198
- .addOrderBy('config.priority', 'ASC')
199
- .addOrderBy('config.created_at', 'DESC')
200
- .getMany();
201
-
202
- return configs.length > 0 ? configs[0] : null;
203
- }
204
-
205
- async getAllIntegrationData(
206
- loggedInUser,
207
- integration_type?: string,
208
- ): Promise<any[]> {
209
- try {
210
- const allIntegrationData = await this.dataSource.query(
211
- `SELECT *
212
- FROM cr_integration_master`,
213
- );
214
-
215
- // if entityType is provided, filter the results
216
- if (integration_type) {
217
- return allIntegrationData.filter(
218
- (data) =>
219
- data.integration_type.toLowerCase() ===
220
- integration_type.toLowerCase(),
221
- );
222
- }
223
-
224
- return allIntegrationData;
225
- } catch (error) {
226
- this.logger.error('Error fetching integration data:', error.message);
227
- return [];
228
- }
229
- }
230
-
231
- private sortConfigsByPriority(
232
- configs: IntegrationConfig[],
233
- _priority: number,
234
- ): IntegrationConfig[] {
235
- return configs.sort((a, b) => {
236
- // First sort by default (true comes first)
237
- if (a.is_default !== b.is_default) {
238
- return a.is_default ? -1 : 1;
239
- }
240
- // Then by priority (lower number = higher priority)
241
- return a.priority - b.priority;
242
- });
243
- }
244
-
245
- private async sendViaConfig(
246
- config: IntegrationConfig,
247
- to: string,
248
- message: string,
249
- user_id?: number,
250
- ): Promise<IntegrationResult> {
251
- const strategy = this.integrationFactory.create(
252
- config.integration_type,
253
- 'API', // service is deprecated, using default
254
- config.integration_provider,
255
- );
256
-
257
- // Get user integration data if user_id provided
258
- let finalConfig = config.config_json;
259
- if (user_id) {
260
- const userIntegrationData = await this.getUserIntegrationForStrategy(
261
- user_id,
262
- config.id,
263
- );
264
-
265
- if (userIntegrationData) {
266
- finalConfig = {
267
- ...config.config_json,
268
- external_user_id: userIntegrationData.external_user_id,
269
- };
270
- }
271
- }
272
-
273
- const result = await strategy.sendMessage(to, message, finalConfig);
274
-
275
- // If token was refreshed, update it in the database
276
- if (result.refreshedToken && result.success) {
277
- try {
278
- const currentConfig = config.config_json as any;
279
- const updatedConfig = {
280
- ...currentConfig,
281
- accessToken: result.refreshedToken,
282
- };
283
-
284
- await this.configRepository.update(config.id, {
285
- config_json: updatedConfig,
286
- } as any);
287
-
288
- this.logger.log(
289
- `Updated access token for ${config.integration_provider} configuration`,
290
- );
291
- } catch (error) {
292
- this.logger.warn(
293
- `Failed to update refreshed token in database: ${error.message}`,
294
- );
295
- }
296
- }
297
-
298
- return result;
299
- }
300
-
301
- async createIntegrationConfig(
302
- levelId: number,
303
- levelType: string,
304
- app_code: string,
305
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
306
- provider: string,
307
- integration_source_id: number,
308
- config: any,
309
- priority?: number,
310
- is_default?: boolean,
311
- ): Promise<
312
- IntegrationConfig | { authUrl: string; state: string; message: string }
313
- > {
314
- // Validate that no duplicate provider configurations exist
315
- await this.validateUniqueActiveConfig(
316
- levelId,
317
- levelType,
318
- app_code,
319
- configType,
320
- provider,
321
- );
322
-
323
- // Deactivate all other configurations of the same integration type
324
- await this.configRepository.update(
325
- {
326
- level_id: levelId,
327
- level_type: levelType,
328
- app_code: app_code,
329
- integration_type: configType,
330
- status: 1,
331
- },
332
- { status: 0 },
333
- );
334
-
335
- // Validate provider and get service type from supported combinations
336
- const supportedCombinations = await this.getSupportedCombinations();
337
- const validCombination = supportedCombinations.find(
338
- (combo) =>
339
- combo.mode === configType &&
340
- combo.provider.toLowerCase() === provider.toLowerCase(),
341
- );
342
-
343
- if (!validCombination) {
344
- throw new Error(`Unsupported combination: ${configType}/${provider}`);
345
- }
346
-
347
- const service = validCombination.service;
348
-
349
- // Check if this requires OAuth flow
350
- const requiresOAuth = this.requiresOAuthFlow(configType, provider, config);
351
-
352
- if (requiresOAuth) {
353
- // Generate OAuth URL and return it instead of creating config immediately
354
- return await this.generateOAuthUrl(
355
- levelId,
356
- levelType,
357
- app_code,
358
- configType,
359
- provider,
360
- integration_source_id,
361
- config,
362
- priority,
363
- is_default,
364
- );
365
- }
366
-
367
- // Direct config creation (non-OAuth flow)
368
- return await this.createDirectConfig(
369
- levelId,
370
- levelType,
371
- app_code,
372
- configType,
373
- provider,
374
- integration_source_id,
375
- config,
376
- priority,
377
- is_default,
378
- );
379
- }
380
-
381
- getSupportedCombinations(): {
382
- mode: string;
383
- service: string;
384
- provider: string;
385
- }[] {
386
- return this.integrationFactory.getAllSupportedCombinations();
387
- }
388
-
389
- async getLevelConfigs(
390
- levelId: number,
391
- levelType: string,
392
- filters?: {
393
- app_code?: string;
394
- integration_type?: 'WA' | 'SMS' | 'EMAIL' | 'TELEPHONE';
395
- integration_provider?: string;
396
- },
397
- ): Promise<
398
- Array<IntegrationConfig & { linkedSource?: string; configDetails?: any }>
399
- > {
400
- const where: any = { level_id: levelId, level_type: levelType };
401
-
402
- if (filters?.app_code) {
403
- where.app_code = filters.app_code;
404
- }
405
-
406
- if (filters?.integration_type) {
407
- where.integration_type = filters.integration_type;
408
- }
409
-
410
- if (filters?.integration_provider) {
411
- where.integration_provider = filters.integration_provider;
412
- }
413
-
414
- const hubs = await this.configRepository.find({
415
- where,
416
- order: { created_at: 'DESC' },
417
- });
418
-
419
- // Enhance hubs with linked source information
420
- const enhancedHubs = await Promise.all(
421
- hubs.map(async (hub) => {
422
- try {
423
- const relatedConfig = await this.configRepository.findOne({
424
- where: { id: hub.id },
425
- });
426
-
427
- if (!relatedConfig) {
428
- return {
429
- ...hub,
430
- linkedSource: 'Configuration not found',
431
- configDetails: null,
432
- };
433
- }
434
-
435
- const linkedSource = this.extractLinkedSource(
436
- hub.integration_type,
437
- hub.integration_provider,
438
- relatedConfig.config_json,
439
- );
440
-
441
- const configDetails = this.extractConfigDetails(
442
- hub.integration_type,
443
- hub.integration_provider,
444
- relatedConfig.config_json,
445
- );
446
-
447
- return {
448
- ...hub,
449
- linkedSource,
450
- configDetails,
451
- };
452
- } catch (error) {
453
- this.logger.warn(
454
- `Error extracting linked source for hub ${hub.id}:`,
455
- error.message,
456
- );
457
- return {
458
- ...hub,
459
- linkedSource: 'Error retrieving source',
460
- configDetails: null,
461
- };
462
- }
463
- }),
464
- );
465
-
466
- return enhancedHubs;
467
- }
468
-
469
- private extractLinkedSource(
470
- configType: string,
471
- provider: string,
472
- configJson: any,
473
- ): string {
474
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
475
-
476
- try {
477
- switch (key) {
478
- // Gmail configurations
479
- case 'email_gmail':
480
- case 'email_smtp_gmail':
481
- return configJson?.email || 'Gmail account not configured';
482
-
483
- // Outlook configurations
484
- case 'email_outlook':
485
- case 'email_smtp_outlook':
486
- return configJson?.email || 'Outlook account not configured';
487
-
488
- // WhatsApp configurations
489
- case 'wa_api_whatsapp':
490
- return configJson?.phoneNumberId
491
- ? `WhatsApp Business: ${configJson.phoneNumberId}`
492
- : 'WhatsApp not configured';
493
-
494
- // SMS configurations
495
- case 'sms_third_party_twilio':
496
- return configJson?.fromNumber
497
- ? `Twilio: ${configJson.fromNumber}`
498
- : 'Twilio number not configured';
499
-
500
- case 'sms_third_party_knowlarity':
501
- return configJson?.callerNumber
502
- ? `Knowlarity: ${configJson.callerNumber}`
503
- : 'Knowlarity number not configured';
504
-
505
- // Telephone configurations
506
- case 'telephone_third_party_knowlarity':
507
- return configJson?.callerNumber
508
- ? `Knowlarity Voice: ${configJson.callerNumber}`
509
- : 'Knowlarity voice number not configured';
510
-
511
- case 'telephone_third_party_ozonetel':
512
- return configJson?.userName
513
- ? `Ozonetel Voice: ${configJson.userName}`
514
- : 'Ozonetel voice not configured';
515
-
516
- // AWS SES configurations
517
- case 'email_aws-ses':
518
- case 'email_ses':
519
- return configJson?.fromEmail || 'AWS SES not configured';
520
-
521
- // SendGrid configurations
522
- case 'email_smtp_sendgrid':
523
- return configJson?.from || 'SendGrid not configured';
524
-
525
- // Generic SMTP configurations
526
- case 'email_smtp_custom':
527
- case 'email_smtp_generic':
528
- return configJson?.from || configJson?.user || 'SMTP not configured';
529
-
530
- default:
531
- // Generic fallback - try to find common identifier fields
532
- if (configJson?.email) return configJson.email;
533
- if (configJson?.from) return configJson.from;
534
- if (configJson?.user) return configJson.user;
535
- if (configJson?.phoneNumberId) return configJson.phoneNumberId;
536
- if (configJson?.fromNumber) return configJson.fromNumber;
537
- if (configJson?.callerNumber) return configJson.callerNumber;
538
-
539
- return `${provider} configured`;
540
- }
541
- } catch (error) {
542
- return 'Configuration error';
543
- }
544
- }
545
-
546
- private extractConfigDetails(
547
- configType: string,
548
- provider: string,
549
- configJson: any,
550
- ): any {
551
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
552
-
553
- try {
554
- switch (key) {
555
- // Gmail configurations
556
- case 'email_gmail':
557
- return {
558
- email: configJson?.email,
559
- authMethod: configJson?.authMethod || 'OAUTH2',
560
- hasRefreshToken: !!configJson?.refreshToken,
561
- isExpired: configJson?.expiryDate
562
- ? new Date(configJson.expiryDate) < new Date()
563
- : false,
564
- };
565
-
566
- case 'email_smtp_gmail':
567
- return {
568
- email: configJson?.email,
569
- authMethod: 'SMTP',
570
- hasPassword: !!configJson?.password,
571
- };
572
-
573
- // Outlook configurations
574
- case 'email_outlook':
575
- return {
576
- email: configJson?.email,
577
- authMethod: 'OAUTH2',
578
- hasRefreshToken: !!configJson?.refreshToken,
579
- tenantId: configJson?.tenantId,
580
- };
581
-
582
- case 'email_smtp_outlook':
583
- return {
584
- email: configJson?.email,
585
- authMethod: 'SMTP',
586
- hasPassword: !!configJson?.password,
587
- };
588
-
589
- // WhatsApp configurations
590
- case 'wa_api_whatsapp':
591
- return {
592
- phoneNumberId: configJson?.phoneNumberId,
593
- apiVersion: configJson?.apiVersion || 'v17.0',
594
- hasAccessToken: !!configJson?.accessToken,
595
- };
596
-
597
- // SMS configurations
598
- case 'sms_third_party_twilio':
599
- return {
600
- fromNumber: configJson?.fromNumber,
601
- accountSid: configJson?.accountSid
602
- ? configJson.accountSid.substring(0, 8) + '...'
603
- : null,
604
- hasAuthToken: !!configJson?.authToken,
605
- };
606
-
607
- case 'sms_third_party_knowlarity':
608
- return {
609
- callerNumber: configJson?.callerNumber,
610
- callType: configJson?.callType || 'sms',
611
- hasApiSecret: !!configJson?.apiSecret,
612
- };
613
-
614
- // Telephone configurations
615
- case 'telephone_third_party_knowlarity':
616
- return {
617
- callerNumber: configJson?.callerNumber,
618
- callType: configJson?.callType || 'voice',
619
- language: configJson?.language || 'en',
620
- hasApiSecret: !!configJson?.apiSecret,
621
- };
622
-
623
- case 'telephone_third_party_ozonetel':
624
- return {
625
- userName: configJson?.userName,
626
- agentID: configJson?.agentID,
627
- campaignName: configJson?.campaignName,
628
- agentLoginUrl: configJson?.agentLoginUrl,
629
- hasApiKey: !!configJson?.apiKey,
630
- };
631
-
632
- // AWS SES configurations
633
- case 'email_aws-ses':
634
- case 'email_ses':
635
- return {
636
- fromEmail: configJson?.fromEmail,
637
- region: configJson?.region,
638
- hasCredentials: !!(
639
- configJson?.accessKeyId && configJson?.secretAccessKey
640
- ),
641
- };
642
-
643
- // SendGrid configurations
644
- case 'email_smtp_sendgrid':
645
- return {
646
- from: configJson?.from,
647
- hasApiKey: !!configJson?.apiKey,
648
- templateId: configJson?.templateId,
649
- };
650
-
651
- // Generic SMTP configurations
652
- case 'email_smtp_custom':
653
- case 'email_smtp_generic':
654
- return {
655
- host: configJson?.host,
656
- port: configJson?.port || 587,
657
- secure: configJson?.secure || false,
658
- from: configJson?.from || configJson?.user,
659
- hasCredentials: !!(configJson?.user && configJson?.password),
660
- };
661
-
662
- default: {
663
- // Generic details - return safe subset of config
664
- const safeConfig: any = {};
665
-
666
- // Include non-sensitive fields
667
- const safeFields = [
668
- 'email',
669
- 'from',
670
- 'user',
671
- 'host',
672
- 'port',
673
- 'secure',
674
- 'phoneNumberId',
675
- 'fromNumber',
676
- 'callerNumber',
677
- 'region',
678
- 'apiVersion',
679
- 'callType',
680
- 'language',
681
- 'templateId',
682
- ];
683
-
684
- safeFields.forEach((field) => {
685
- if (configJson?.[field]) {
686
- safeConfig[field] = configJson[field];
687
- }
688
- });
689
-
690
- // Include boolean indicators for sensitive fields
691
- const sensitiveFields = [
692
- 'accessToken',
693
- 'refreshToken',
694
- 'password',
695
- 'authToken',
696
- 'apiKey',
697
- 'apiSecret',
698
- 'clientSecret',
699
- 'secretAccessKey',
700
- ];
701
-
702
- sensitiveFields.forEach((field) => {
703
- if (configJson?.[field]) {
704
- safeConfig[
705
- `has${field.charAt(0).toUpperCase() + field.slice(1)}`
706
- ] = true;
707
- }
708
- });
709
-
710
- return safeConfig;
711
- }
712
- }
713
- } catch (error) {
714
- return { error: 'Unable to extract configuration details' };
715
- }
716
- }
717
-
718
- async updateConfigStatus(hubId: number, status: number): Promise<void> {
719
- // Find the hub to get level and type information
720
- const config = await this.configRepository.findOne({
721
- where: { id: hubId },
722
- });
723
-
724
- if (!config) {
725
- throw new Error('Integration configuration not found');
726
- }
727
-
728
- // If activating, deactivate ALL other configs of the same integration type
729
- if (status === 1) {
730
- await this.configRepository.update(
731
- {
732
- level_id: config.level_id,
733
- level_type: config.level_type,
734
- app_code: config.app_code,
735
- integration_type: config.integration_type,
736
- status: 1,
737
- id: Not(hubId),
738
- },
739
- { status: 0 },
740
- );
741
- }
742
-
743
- // Update the requested config
744
- await this.configRepository.update(hubId, { status });
745
- }
746
-
747
- async deleteConfiguration(configId: number): Promise<void> {
748
- // Find the hub to get the id
749
- const config = await this.configRepository.findOne({
750
- where: { id: configId },
751
- });
752
-
753
- if (!config) {
754
- throw new Error('Integration configuration not found');
755
- }
756
-
757
- await this.configRepository.delete(configId);
758
-
759
- this.logger.log(`Integration configuration deleted: ${configId}`);
760
- }
761
-
762
- async updateConfiguration(
763
- hubId: number,
764
- updateData: {
765
- config?: any;
766
- priority?: number;
767
- is_default?: boolean;
768
- status?: number;
769
- },
770
- ): Promise<IntegrationConfig & { config?: any }> {
771
- // Find the existing hub
772
- const config = await this.configRepository.findOne({
773
- where: { id: hubId },
774
- });
775
-
776
- if (!config) {
777
- throw new Error('Integration configuration not found');
778
- }
779
-
780
- // Update configuration JSON if provided
781
- if (updateData.config) {
782
- // Merge the new config with existing config
783
- const updatedConfigJson = {
784
- ...config.config_json,
785
- ...updateData.config,
786
- };
787
-
788
- await this.configRepository.update(config.id, {
789
- config_json: updatedConfigJson,
790
- });
791
- }
792
-
793
- // Handle default configuration logic (simplified for now)
794
- if (updateData.is_default === true) {
795
- // Remove default from other configurations of same type and level
796
- await this.configRepository.update(
797
- {
798
- level_id: config.level_id,
799
- level_type: config.level_type,
800
- integration_type: config.integration_type,
801
- id: Not(hubId),
802
- },
803
- { is_default: false },
804
- );
805
- }
806
-
807
- if (config.integration_type === 'TELEPHONE') {
808
- try {
809
- // Extract DID from config (could be did, callerNumber, or fromNumber)
810
- const did = config.config_json.did;
811
-
812
- if (did) {
813
-
814
- await this.entityMapperRepository.delete({integration_config_id: config.id})
815
-
816
- const entityMapper = this.entityMapperRepository.create({
817
- integration_config_id: config.id,
818
- level_id: String(config.level_id),
819
- level_type: config.level_type,
820
- appcode: config.app_code,
821
- did: did,
822
- campaign_name: config.config_json.campaignName || null,
823
- });
824
-
825
- await this.entityMapperRepository.save(entityMapper);
826
- this.logger.log(
827
- `DID mapping created for TELEPHONE integration: ${did} for ${config.level_id} ${config.level_type}`,
828
- );
829
- }
830
- } catch (error) {
831
- this.logger.warn(
832
- `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
833
- );
834
- }
835
- }
836
-
837
- // Apply direct config updates if any
838
- const directUpdates: any = {};
839
- if (updateData.priority !== undefined)
840
- directUpdates.priority = updateData.priority;
841
- if (updateData.is_default !== undefined)
842
- directUpdates.is_default = updateData.is_default;
843
- if (updateData.status !== undefined)
844
- directUpdates.status = updateData.status;
845
-
846
- if (Object.keys(directUpdates).length > 0) {
847
- await this.configRepository.update(config.id, directUpdates);
848
- }
849
-
850
- // Fetch and return updated config
851
- const updatedConfig = await this.configRepository.findOne({
852
- where: { id: hubId },
853
- });
854
-
855
- return {
856
- ...updatedConfig,
857
- config: updatedConfig?.config_json,
858
- } as any;
859
- }
860
-
861
- async sendGenericMessage(
862
- messageDto: GenericMessageDto,
863
- ): Promise<IntegrationResult> {
864
- try {
865
- const {
866
- levelId,
867
- levelType,
868
- app_code,
869
- to,
870
- message,
871
- type,
872
- priority = 'medium',
873
- html,
874
- cc,
875
- bcc,
876
- attachments,
877
- mediaUrl,
878
- templateId,
879
- user_id,
880
- entity_id,
881
- entity_type,
882
- } = messageDto;
883
-
884
- let subject = messageDto.subject;
885
-
886
- // Auto-detect communication type if not specified
887
- const communicationType = this.detectCommunicationType(to, type);
888
-
889
- // Get active configs for the detected type
890
- const configs = await this.getActiveConfigs(
891
- levelId,
892
- levelType,
893
- app_code,
894
- communicationType,
895
- );
896
-
897
- if (!configs.length) {
898
- this.logger.warn(
899
- `No communication hubs found for ${levelType} ${levelId}. Please configure integration providers using the createIntegrationConfig method.`,
900
- );
901
- throw new Error(
902
- `No active ${communicationType} configuration found for ${levelType} ${levelId}. Please configure a communication provider first.`,
903
- );
904
- }
905
-
906
- // Sort hubs by priority and default preference
907
- const sortedConfigs = this.sortConfigsByPriorityAndDefault(
908
- configs,
909
- priority,
910
- );
911
-
912
- // Prepare enhanced config with additional parameters
913
- const enhancedConfig = {
914
- subject,
915
- html,
916
- cc,
917
- bcc,
918
- attachments,
919
- mediaUrl,
920
- };
921
-
922
- // Handle multiple recipients by sending to each individually
923
- if (Array.isArray(to)) {
924
- const results: IntegrationResult[] = [];
925
- let hasSuccess = false;
926
-
927
- for (const recipient of to) {
928
- for (const hub of sortedConfigs) {
929
- try {
930
- const serviceType = this.deriveServiceType(
931
- hub.integration_type,
932
- hub.integration_provider,
933
- hub.config_json,
934
- );
935
- const strategy = this.integrationFactory.create(
936
- hub.integration_type,
937
- serviceType,
938
- hub.integration_provider,
939
- );
940
-
941
- // Process template if provided
942
- let variables;
943
- let richText;
944
- let externalTemplateId: string | undefined = undefined;
945
- if (templateId) {
946
- const templateData = await this.processTemplate(
947
- parseInt(templateId, 10),
948
- entity_type,
949
- entity_id,
950
- );
951
- variables = templateData.variables;
952
- externalTemplateId = templateData.externalTemplateId;
953
- richText = templateData.rich_text;
954
- subject = templateData.subject;
955
- }
956
-
957
- // Merge config with enhanced parameters
958
- let finalConfig = {
959
- ...hub.config_json,
960
- ...enhancedConfig,
961
- templateId: externalTemplateId,
962
- variables,
963
- richText,
964
- };
965
-
966
- // Handle user integration if user_id provided
967
- if (user_id) {
968
- const userIntegrationData =
969
- await this.getUserIntegrationForStrategy(user_id, hub.id);
970
-
971
- if (userIntegrationData) {
972
- finalConfig = {
973
- ...finalConfig,
974
- external_user_id: userIntegrationData.external_user_id,
975
- };
976
- }
977
- }
978
-
979
- const result = await strategy.sendMessage(
980
- recipient,
981
- message,
982
- finalConfig,
983
- );
984
-
985
- if (result.success) {
986
- this.logger.log(
987
- `Generic message sent successfully via ${hub.integration_provider} to ${recipient}`,
988
- );
989
- results.push(result);
990
- hasSuccess = true;
991
- break; // Move to next recipient
992
- }
993
-
994
- this.logger.warn(
995
- `Failed to send via ${hub.integration_provider} to ${recipient}: ${result.error}`,
996
- );
997
- } catch (error) {
998
- this.logger.error(
999
- `Error sending via ${hub.integration_provider} to ${recipient}:`,
1000
- error.message,
1001
- );
1002
- continue;
1003
- }
1004
- }
1005
- }
1006
-
1007
- if (hasSuccess) {
1008
- return {
1009
- success: true,
1010
- messageId: results.map((r) => r.messageId).join(','),
1011
- provider: 'multiple',
1012
- service: 'multiple',
1013
- timestamp: new Date(),
1014
- };
1015
- }
1016
- } else {
1017
- // Handle single recipient
1018
- for (const hub of sortedConfigs) {
1019
- try {
1020
- const serviceType = this.deriveServiceType(
1021
- hub.integration_type,
1022
- hub.integration_provider,
1023
- hub.config_json,
1024
- );
1025
- const strategy = this.integrationFactory.create(
1026
- hub.integration_type,
1027
- serviceType,
1028
- hub.integration_provider,
1029
- );
1030
-
1031
- // Process template if provided
1032
- let variables;
1033
- let externalTemplateId: string | undefined = undefined;
1034
- let richText;
1035
- if (templateId) {
1036
- const templateData = await this.processTemplate(
1037
- parseInt(templateId, 10),
1038
- entity_type,
1039
- entity_id,
1040
- );
1041
- variables = templateData.variables;
1042
- externalTemplateId = templateData.externalTemplateId;
1043
- richText = templateData.rich_text;
1044
- subject = templateData.subject;
1045
- }
1046
-
1047
- // Merge config with enhanced parameters
1048
- let finalConfig = {
1049
- ...hub.config_json,
1050
- ...enhancedConfig,
1051
- templateId: externalTemplateId,
1052
- variables,
1053
- richText
1054
- };
1055
-
1056
- // Handle user integration if user_id provided
1057
- if (user_id) {
1058
- const userIntegrationData =
1059
- await this.getUserIntegrationForStrategy(user_id, hub.id);
1060
-
1061
- if (userIntegrationData) {
1062
- finalConfig = {
1063
- ...finalConfig,
1064
- external_user_id: userIntegrationData.external_user_id,
1065
- };
1066
- }
1067
- }
1068
-
1069
- const result = await strategy.sendMessage(
1070
- to,
1071
- message,
1072
- finalConfig,
1073
- );
1074
-
1075
- if (result.success) {
1076
- this.logger.log(
1077
- `Generic message sent successfully via ${hub.integration_provider} to ${to}`,
1078
- );
1079
- return result;
1080
- }
1081
-
1082
- this.logger.warn(
1083
- `Failed to send via ${hub.integration_provider}: ${result.error}`,
1084
- );
1085
- } catch (error) {
1086
- this.logger.error(
1087
- `Error sending via ${hub.integration_provider}:`,
1088
- error.message,
1089
- );
1090
- continue;
1091
- }
1092
- }
1093
- }
1094
-
1095
- throw new Error('All communication providers failed');
1096
- } catch (error) {
1097
- this.logger.error('Generic communication service error:', error.message);
1098
- throw error;
1099
- }
1100
- }
1101
-
1102
- async sendBulkMessage(
1103
- bulkDto: BulkMessageDto,
1104
- ): Promise<{ results: IntegrationResult[]; summary: any }> {
1105
- try {
1106
- const {
1107
- levelId,
1108
- levelType,
1109
- app_code,
1110
- recipients,
1111
- message,
1112
- type,
1113
- priority = 'low',
1114
- subject,
1115
- html,
1116
- templateId,
1117
- variables,
1118
- batchSize = 10,
1119
- } = bulkDto;
1120
-
1121
- const results: IntegrationResult[] = [];
1122
- const batches = this.chunkArray(recipients, batchSize);
1123
-
1124
- for (let i = 0; i < batches.length; i++) {
1125
- const batch = batches[i];
1126
- this.logger.log(
1127
- `Processing batch ${i + 1}/${batches.length} with ${batch.length} recipients`,
1128
- );
1129
-
1130
- const batchPromises = batch.map(async (recipient) => {
1131
- try {
1132
- const messageDto: GenericMessageDto = {
1133
- levelId,
1134
- levelType,
1135
- app_code,
1136
- to: recipient,
1137
- message,
1138
- type,
1139
- priority,
1140
- subject,
1141
- html,
1142
- templateId,
1143
- variables,
1144
- };
1145
-
1146
- return await this.sendGenericMessage(messageDto);
1147
- } catch (error) {
1148
- return {
1149
- success: false,
1150
- provider: 'unknown',
1151
- service: 'unknown',
1152
- error: error.message,
1153
- timestamp: new Date(),
1154
- } as IntegrationResult;
1155
- }
1156
- });
1157
-
1158
- const batchResults = await Promise.allSettled(batchPromises);
1159
- const processedResults = batchResults.map((result) => {
1160
- if (result.status === 'fulfilled') {
1161
- return result.value;
1162
- } else {
1163
- return {
1164
- success: false,
1165
- provider: 'unknown',
1166
- service: 'unknown',
1167
- error: result.reason?.message || 'Unknown error',
1168
- timestamp: new Date(),
1169
- } as IntegrationResult;
1170
- }
1171
- });
1172
-
1173
- results.push(...processedResults);
1174
-
1175
- // Rate limiting delay between batches
1176
- if (i < batches.length - 1) {
1177
- await new Promise((resolve) => setTimeout(resolve, 1000));
1178
- }
1179
- }
1180
-
1181
- const summary = {
1182
- total: results.length,
1183
- successful: results.filter((r) => r.success).length,
1184
- failed: results.filter((r) => !r.success).length,
1185
- successRate:
1186
- (
1187
- (results.filter((r) => r.success).length / results.length) *
1188
- 100
1189
- ).toFixed(2) + '%',
1190
- };
1191
-
1192
- this.logger.log(
1193
- `Bulk message completed: ${summary.successful}/${summary.total} successful`,
1194
- );
1195
-
1196
- return { results, summary };
1197
- } catch (error) {
1198
- this.logger.error('Bulk communication service error:', error.message);
1199
- throw error;
1200
- }
1201
- }
1202
-
1203
- async scheduleMessage(
1204
- scheduledDto: any,
1205
- ): Promise<{ scheduled: boolean; scheduleId?: string }> {
1206
- // For now, return a placeholder. In production, integrate with a job queue like Bull or Agenda
1207
- this.logger.log(`Message scheduled for ${scheduledDto.scheduleFor}`);
1208
-
1209
- return {
1210
- scheduled: true,
1211
- scheduleId: `sched_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
1212
- };
1213
- }
1214
-
1215
- async sendTemplateMessage(templateDto: any): Promise<IntegrationResult> {
1216
- // Get template content (integrate with your template system)
1217
- const template = await this.getTemplate(templateDto.templateId);
1218
-
1219
- const processedMessage = this.replaceTemplateVariables(
1220
- template.content,
1221
- templateDto.variables,
1222
- );
1223
- const processedSubject = template.subject
1224
- ? this.replaceTemplateVariables(template.subject, templateDto.variables)
1225
- : undefined;
1226
-
1227
- const messageDto: GenericMessageDto = {
1228
- levelId: templateDto.levelId,
1229
- levelType: templateDto.levelType,
1230
- app_code: templateDto.app_code,
1231
- to: templateDto.to,
1232
- message: processedMessage,
1233
- subject: processedSubject,
1234
- type: templateDto.type,
1235
- templateId: templateDto.templateId,
1236
- variables: templateDto.variables,
1237
- };
1238
-
1239
- return this.sendGenericMessage(messageDto);
1240
- }
1241
-
1242
- private detectCommunicationType(
1243
- to: string | string[],
1244
- type?: string,
1245
- ): 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE' {
1246
- if (type) {
1247
- return type as 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
1248
- }
1249
-
1250
- const recipient = Array.isArray(to) ? to[0] : to;
1251
-
1252
- // Email detection
1253
- if (recipient.includes('@')) {
1254
- return 'EMAIL';
1255
- }
1256
-
1257
- // Phone number detection (basic)
1258
- if (/^\+?[\d\s\-\(\)]+$/.test(recipient)) {
1259
- // Could be SMS or WhatsApp, default to SMS
1260
- return 'SMS';
1261
- }
1262
-
1263
- // Default to EMAIL if unsure
1264
- return 'EMAIL';
1265
- }
1266
-
1267
- private sortConfigsByPriorityAndDefault(
1268
- configs: IntegrationConfigWithConfig[],
1269
- _priority: string,
1270
- ): IntegrationConfigWithConfig[] {
1271
- return configs.sort((a, b) => {
1272
- // First sort by default (true comes first)
1273
- if (a.is_default !== b.is_default) {
1274
- return b.is_default ? 1 : -1;
1275
- }
1276
-
1277
- // Then sort by priority (lower number = higher priority)
1278
- if (a.priority !== b.priority) {
1279
- return a.priority - b.priority;
1280
- }
1281
-
1282
- // Finally sort by created_at descending (newest first)
1283
- return (
1284
- new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
1285
- );
1286
- });
1287
- }
1288
-
1289
- private async processTemplate(
1290
- templateId: number,
1291
- entity_type: any,
1292
- entity_id: any,
1293
- ): Promise<{ variables?: Record<string, any>; externalTemplateId?: string; rich_text?: string; subject?: string }> {
1294
- const commTemplate: any = await this.entityService.getEntityData(COMM_TEMPLATE, templateId, {} as any);
1295
- if (!commTemplate) {
1296
- return {
1297
- variables: {},
1298
- externalTemplateId: undefined,
1299
- };
1300
- }
1301
-
1302
- let variables = {};
1303
- if (commTemplate.mapper_id) {
1304
- variables = await this.fieldMapperService.resolveData(
1305
- commTemplate.mapper_id,
1306
- "LOOKUP",
1307
- entity_type,
1308
- entity_id,
1309
- {} as any,
1310
- );
1311
- }
1312
-
1313
- if (!commTemplate.template_id) {
1314
- let richText = commTemplate.rich_text;
1315
-
1316
- richText = richText.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1317
- const value = variables[key];
1318
- return value !== undefined ? String(value) : match;
1319
- });
1320
-
1321
- return {
1322
- rich_text: richText,
1323
- subject: commTemplate.subject
1324
- };
1325
- }
1326
-
1327
- return {
1328
- variables,
1329
- externalTemplateId: commTemplate.template_id,
1330
- };
1331
- }
1332
-
1333
- private replaceTemplateVariables(
1334
- template: string,
1335
- variables: Record<string, any>,
1336
- ): string {
1337
- return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1338
- const value = variables[key];
1339
- return value !== undefined ? String(value) : match;
1340
- });
1341
- }
1342
-
1343
- private async getTemplate(templateId: string) {
1344
- // Placeholder for template system integration
1345
- // In production, this would connect to your template database/service
1346
- return {
1347
- id: templateId,
1348
- subject: 'Default Subject {{variable}}',
1349
- content: 'Hello {{name}}, this is a template message with {{variable}}.',
1350
- };
1351
- }
1352
-
1353
- private chunkArray<T>(array: T[], chunkSize: number): T[][] {
1354
- const chunks: T[][] = [];
1355
- for (let i = 0; i < array.length; i += chunkSize) {
1356
- chunks.push(array.slice(i, i + chunkSize));
1357
- }
1358
- return chunks;
1359
- }
1360
-
1361
- async initGmailOAuth(
1362
- levelId: number,
1363
- levelType: string,
1364
- app_code: string,
1365
- email?: string,
1366
- ): Promise<{ authUrl: string; state: string }> {
1367
- try {
1368
- // Get system OAuth credentials from config
1369
- const clientId = this.configService.get<string>('CLIENT_ID');
1370
- const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1371
-
1372
- if (!clientId || !clientSecret) {
1373
- throw new Error('Gmail OAuth credentials not configured');
1374
- }
1375
-
1376
- const state = this.generateSecureState();
1377
- // Use the existing registered callback URL
1378
- const callbackUrl =
1379
- this.configService.get<string>('CALLBACK_URL') ||
1380
- 'http://localhost:5001/auth/google/callback';
1381
-
1382
- this.gmailOAuthStates.set(state, {
1383
- levelId,
1384
- levelType,
1385
- app_code,
1386
- email,
1387
- timestamp: Date.now(),
1388
- });
1389
-
1390
- // Auto-cleanup after 10 minutes
1391
- setTimeout(
1392
- () => {
1393
- this.gmailOAuthStates.delete(state);
1394
- },
1395
- 10 * 60 * 1000,
1396
- );
1397
-
1398
- const oauth2Client = new google.auth.OAuth2(
1399
- clientId,
1400
- clientSecret,
1401
- callbackUrl,
1402
- );
1403
-
1404
- const scopes = [
1405
- 'https://www.googleapis.com/auth/gmail.send',
1406
- 'https://www.googleapis.com/auth/gmail.readonly',
1407
- 'https://www.googleapis.com/auth/userinfo.email',
1408
- 'https://www.googleapis.com/auth/calendar',
1409
- ];
1410
-
1411
- const authUrl = oauth2Client.generateAuthUrl({
1412
- access_type: 'offline',
1413
- scope: scopes,
1414
- state: `gmail_config:${state}`, // Prefix to identify Gmail config requests
1415
- prompt: 'consent',
1416
- login_hint: email,
1417
- });
1418
-
1419
- return { authUrl, state };
1420
- } catch (error) {
1421
- this.logger.error('Error initializing Gmail OAuth:', error.message);
1422
- throw new Error('Failed to initialize Gmail OAuth');
1423
- }
1424
- }
1425
-
1426
- async handleGmailOAuthCallback(
1427
- code: string,
1428
- state: string,
1429
- ): Promise<GmailSSOResult> {
1430
- try {
1431
- const oauthState = this.gmailOAuthStates.get(state);
1432
- if (!oauthState) {
1433
- throw new Error('Invalid or expired OAuth state');
1434
- }
1435
-
1436
- this.gmailOAuthStates.delete(state);
1437
-
1438
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1439
- throw new Error('OAuth state expired');
1440
- }
1441
-
1442
- // Get system OAuth credentials
1443
- const clientId = this.configService.get<string>('CLIENT_ID');
1444
- const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1445
- const callbackUrl =
1446
- this.configService.get<string>('CALLBACK_URL') ||
1447
- 'http://localhost:5001/auth/google/callback';
1448
-
1449
- const oauth2Client = new google.auth.OAuth2(
1450
- clientId,
1451
- clientSecret,
1452
- callbackUrl,
1453
- );
1454
-
1455
- const { tokens } = await oauth2Client.getToken(code);
1456
-
1457
- if (!tokens.access_token) {
1458
- throw new Error('Failed to obtain access token');
1459
- }
1460
-
1461
- // Get user email from Google
1462
- oauth2Client.setCredentials(tokens);
1463
- const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client });
1464
- const userInfo = await oauth2.userinfo.get();
1465
- const email = userInfo.data.email;
1466
-
1467
- if (!email) {
1468
- throw new Error('Failed to get user email');
1469
- }
1470
-
1471
- // Verify email matches if hint was provided
1472
- if (oauthState.email && oauthState.email !== email) {
1473
- throw new Error('Email mismatch with OAuth hint');
1474
- }
1475
-
1476
- const gmailConfig = {
1477
- clientId,
1478
- clientSecret,
1479
- email: email,
1480
- accessToken: tokens.access_token,
1481
- refreshToken: tokens.refresh_token,
1482
- scope: tokens.scope,
1483
- tokenType: tokens.token_type,
1484
- expiryDate: tokens.expiry_date,
1485
- };
1486
-
1487
- // Validate that no active EMAIL configuration exists
1488
- await this.validateUniqueActiveConfig(
1489
- oauthState.levelId,
1490
- oauthState.levelType,
1491
- oauthState.app_code,
1492
- 'EMAIL',
1493
- 'gmail',
1494
- );
1495
-
1496
- // Create integration config
1497
- const config = this.configRepository.create({
1498
- app_code: oauthState.app_code,
1499
- integration_type: 'EMAIL',
1500
- integration_provider: 'gmail',
1501
- integration_source_id: 1, // Gmail source ID
1502
- level_id: oauthState.levelId,
1503
- level_type: oauthState.levelType,
1504
- status: 1,
1505
- priority: 1,
1506
- is_default: false,
1507
- config_json: gmailConfig as any,
1508
- });
1509
-
1510
- const savedConfig = await this.configRepository.save(config);
1511
-
1512
- this.logger.log(
1513
- `Gmail OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1514
- );
1515
-
1516
- return {
1517
- hubId: savedConfig.id,
1518
- configId: savedConfig.id,
1519
- };
1520
- } catch (error) {
1521
- this.logger.error('Error handling Gmail OAuth callback:', error.message);
1522
- throw new Error(`Failed to complete Gmail OAuth: ${error.message}`);
1523
- }
1524
- }
1525
-
1526
- async handleGmailTokensCallback(
1527
- email: string,
1528
- accessToken: string,
1529
- refreshToken: string,
1530
- state: string,
1531
- ): Promise<GmailSSOResult> {
1532
- try {
1533
- const oauthState = this.gmailOAuthStates.get(state);
1534
- if (!oauthState) {
1535
- throw new Error('Invalid or expired OAuth state');
1536
- }
1537
-
1538
- this.gmailOAuthStates.delete(state);
1539
-
1540
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1541
- throw new Error('OAuth state expired');
1542
- }
1543
-
1544
- // Verify email matches if hint was provided
1545
- if (oauthState.email && oauthState.email !== email) {
1546
- throw new Error('Email mismatch with OAuth hint');
1547
- }
1548
-
1549
- // Validate that no active EMAIL configuration exists
1550
- await this.validateUniqueActiveConfig(
1551
- oauthState.levelId,
1552
- oauthState.levelType,
1553
- oauthState.app_code,
1554
- 'EMAIL',
1555
- 'gmail',
1556
- );
1557
-
1558
- // Pure SSO configuration - no client credentials stored per user
1559
- const gmailConfig = {
1560
- email: email,
1561
- accessToken: accessToken,
1562
- refreshToken: refreshToken,
1563
- authMethod: 'GOOGLE_SSO',
1564
- scopes: [
1565
- 'https://www.googleapis.com/auth/gmail.send',
1566
- 'https://www.googleapis.com/auth/userinfo.email',
1567
- ],
1568
- };
1569
-
1570
- // Create integration config
1571
- const config = this.configRepository.create({
1572
- app_code: oauthState.app_code,
1573
- integration_type: 'EMAIL',
1574
- integration_provider: 'gmail',
1575
- integration_source_id: 1, // Gmail source ID
1576
- level_id: oauthState.levelId,
1577
- level_type: oauthState.levelType,
1578
- status: 1,
1579
- priority: 1,
1580
- is_default: false,
1581
- config_json: gmailConfig as any,
1582
- });
1583
-
1584
- const savedConfig = await this.configRepository.save(config);
1585
-
1586
- this.logger.log(
1587
- `Gmail tokens configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1588
- );
1589
-
1590
- return {
1591
- hubId: savedConfig.id,
1592
- configId: savedConfig.id,
1593
- };
1594
- } catch (error) {
1595
- this.logger.error('Error handling Gmail tokens callback:', error.message);
1596
- throw new Error(
1597
- `Failed to complete Gmail tokens callback: ${error.message}`,
1598
- );
1599
- }
1600
- }
1601
-
1602
- async testGmailConfig(
1603
- hubId: number,
1604
- ): Promise<{ success: boolean; error?: string }> {
1605
- try {
1606
- const integrationConfig = await this.configRepository.findOne({
1607
- where: { id: hubId },
1608
- });
1609
-
1610
- if (!integrationConfig) {
1611
- throw new Error('Integration config not found');
1612
- }
1613
-
1614
- const isValid = await this.gmailApiStrategy.validateConnection(
1615
- integrationConfig.config_json,
1616
- );
1617
-
1618
- if (!isValid) {
1619
- return {
1620
- success: false,
1621
- error: 'Gmail configuration is invalid or expired',
1622
- };
1623
- }
1624
-
1625
- return { success: true };
1626
- } catch (error) {
1627
- this.logger.error('Error testing Gmail config:', error.message);
1628
- return { success: false, error: error.message };
1629
- }
1630
- }
1631
-
1632
- private generateSecureState(): string {
1633
- return Math.random().toString(36).substring(2) + Date.now().toString(36);
1634
- }
1635
-
1636
- private async validateUniqueActiveConfig(
1637
- levelId: number,
1638
- levelType: string,
1639
- app_code: string,
1640
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1641
- provider: string,
1642
- excludeHubId?: number,
1643
- ): Promise<void> {
1644
- // Find all active configurations of the same provider for this level and app_code
1645
- const query = this.configRepository
1646
- .createQueryBuilder('hub')
1647
- .where('hub.level_id = :levelId', { levelId })
1648
- .andWhere('hub.level_type = :levelType', { levelType })
1649
- .andWhere('hub.app_code = :app_code', { app_code })
1650
- .andWhere('hub.integration_type = :configType', { configType })
1651
- .andWhere('hub.integration_provider = :provider', { provider })
1652
- .andWhere('hub.status = :status', { status: 1 });
1653
-
1654
- // Exclude current hub if updating
1655
- if (excludeHubId) {
1656
- query.andWhere('hub.id != :excludeHubId', { excludeHubId });
1657
- }
1658
-
1659
- const existingActiveConfigs = await query.getMany();
1660
-
1661
- // If there are existing active configurations of the same provider, throw error
1662
- if (existingActiveConfigs.length > 0) {
1663
- throw new Error(
1664
- `A ${provider} configuration already exists for ${configType} in app_code ${app_code}, ${levelType} ${levelId}. Only one configuration per provider is allowed.`,
1665
- );
1666
- }
1667
- }
1668
-
1669
- private requiresOAuthFlow(
1670
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1671
- provider: string,
1672
- config: any,
1673
- ): boolean {
1674
- // Check if config indicates OAuth is needed (missing tokens or explicit OAuth request)
1675
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1676
-
1677
- switch (key) {
1678
- case 'email_gmail':
1679
- // Requires OAuth if no access token provided or OAuth explicitly requested
1680
- return !config.accessToken || config.useOAuth === true;
1681
-
1682
- case 'email_outlook':
1683
- // Requires OAuth if no access token provided or OAuth explicitly requested
1684
- return !config.accessToken || config.useOAuth === true;
1685
-
1686
- default:
1687
- // Most other providers don't require OAuth
1688
- return false;
1689
- }
1690
- }
1691
-
1692
- private async generateOAuthUrl(
1693
- levelId: number,
1694
- levelType: string,
1695
- app_code: string,
1696
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1697
- provider: string,
1698
- integration_source_id: number,
1699
- config: any,
1700
- priority?: number,
1701
- is_default?: boolean,
1702
- ): Promise<{ authUrl: string; state: string; message: string }> {
1703
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1704
-
1705
- switch (key) {
1706
- case 'email_gmail':
1707
- const gmailResult = await this.initGmailOAuth(
1708
- levelId,
1709
- levelType,
1710
- app_code,
1711
- config.email,
1712
- );
1713
- return {
1714
- authUrl: gmailResult.authUrl,
1715
- state: gmailResult.state,
1716
- message:
1717
- 'Please complete Gmail OAuth authorization. Configuration will be created automatically after authorization.',
1718
- };
1719
-
1720
- case 'email_outlook':
1721
- const outlookResult = await this.initOutlookOAuth(
1722
- levelId,
1723
- levelType,
1724
- app_code,
1725
- config.email,
1726
- );
1727
- return {
1728
- authUrl: outlookResult.authUrl,
1729
- state: outlookResult.state,
1730
- message:
1731
- 'Please complete Outlook OAuth authorization. Configuration will be created automatically after authorization.',
1732
- };
1733
-
1734
- default:
1735
- throw new Error(`OAuth not supported for ${configType}/${provider}`);
1736
- }
1737
- }
1738
-
1739
- private async createDirectConfig(
1740
- levelId: number,
1741
- levelType: string,
1742
- app_code: string,
1743
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1744
- provider: string,
1745
- integration_source_id: number,
1746
- config: any,
1747
- priority?: number,
1748
- is_default?: boolean,
1749
- ): Promise<IntegrationConfig> {
1750
- // Validate that no duplicate provider configurations exist
1751
- await this.validateUniqueActiveConfig(
1752
- levelId,
1753
- levelType,
1754
- app_code,
1755
- configType,
1756
- provider,
1757
- );
1758
-
1759
- // Deactivate all other configurations of the same integration type
1760
- await this.configRepository.update(
1761
- {
1762
- level_id: levelId,
1763
- level_type: levelType,
1764
- app_code: app_code,
1765
- integration_type: configType,
1766
- status: 1,
1767
- },
1768
- { status: 0 },
1769
- );
1770
-
1771
- // If setting as default, remove default from other configurations of same type and app_code
1772
- if (is_default) {
1773
- await this.configRepository.update(
1774
- {
1775
- level_id: levelId,
1776
- level_type: levelType,
1777
- app_code: app_code,
1778
- integration_type: configType,
1779
- },
1780
- { is_default: false },
1781
- );
1782
- }
1783
-
1784
- // Create integration config
1785
- const integrationConfig = this.configRepository.create({
1786
- app_code: app_code,
1787
- integration_type: configType,
1788
- integration_provider: provider,
1789
- integration_source_id: integration_source_id,
1790
- level_id: levelId,
1791
- level_type: levelType,
1792
- status: 1,
1793
- priority: priority || 1,
1794
- is_default: is_default || false,
1795
- config_json: config,
1796
- });
1797
-
1798
- const savedConfig = await this.configRepository.save(integrationConfig);
1799
- this.logger.log(
1800
- `Communication config created: ${configType}/${provider} for ${levelType} ${levelId}`,
1801
- );
1802
-
1803
- // Store DID mapping for TELEPHONE integration
1804
- if (configType === 'TELEPHONE') {
1805
- try {
1806
- // Extract DID from config (could be did, callerNumber, or fromNumber)
1807
- const did = config.did || config.callerNumber || config.fromNumber;
1808
-
1809
- if (did) {
1810
- const entityMapper = this.entityMapperRepository.create({
1811
- integration_config_id: savedConfig.id,
1812
- level_id: String(levelId),
1813
- level_type: levelType,
1814
- appcode: app_code,
1815
- did: did,
1816
- campaign_name: config.campaignName || null,
1817
- });
1818
-
1819
- await this.entityMapperRepository.save(entityMapper);
1820
- this.logger.log(
1821
- `DID mapping created for TELEPHONE integration: ${did} for ${levelType} ${levelId}`,
1822
- );
1823
- }
1824
- } catch (error) {
1825
- this.logger.warn(
1826
- `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
1827
- );
1828
- }
1829
- }
1830
-
1831
- return Array.isArray(savedConfig) ? savedConfig[0] : savedConfig;
1832
- }
1833
-
1834
- async initOutlookOAuth(
1835
- levelId: number,
1836
- levelType: string,
1837
- app_code: string,
1838
- email?: string,
1839
- ): Promise<{ authUrl: string; state: string }> {
1840
- try {
1841
- // Get system OAuth credentials from config
1842
- const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1843
- const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1844
-
1845
- if (!clientId || !tenantId) {
1846
- throw new Error('Outlook OAuth credentials not configured');
1847
- }
1848
-
1849
- const state = this.generateSecureState();
1850
- const callbackUrl =
1851
- this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1852
- 'http://localhost:5001/auth/outlook/callback';
1853
-
1854
- this.gmailOAuthStates.set(state, {
1855
- levelId,
1856
- levelType,
1857
- app_code,
1858
- email,
1859
- timestamp: Date.now(),
1860
- });
1861
-
1862
- // Auto-cleanup after 10 minutes
1863
- setTimeout(
1864
- () => {
1865
- this.gmailOAuthStates.delete(state);
1866
- },
1867
- 10 * 60 * 1000,
1868
- );
1869
-
1870
- const scopes = [
1871
- 'https://graph.microsoft.com/Mail.Send',
1872
- 'https://graph.microsoft.com/User.Read',
1873
- ];
1874
-
1875
- const authUrl =
1876
- `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
1877
- `client_id=${clientId}&` +
1878
- `response_type=code&` +
1879
- `redirect_uri=${encodeURIComponent(callbackUrl)}&` +
1880
- `scope=${encodeURIComponent(scopes.join(' '))}&` +
1881
- `state=outlook_config:${state}&` +
1882
- `response_mode=query&` +
1883
- `prompt=consent` +
1884
- (email ? `&login_hint=${encodeURIComponent(email)}` : '');
1885
-
1886
- return { authUrl, state };
1887
- } catch (error) {
1888
- this.logger.error('Error initializing Outlook OAuth:', error.message);
1889
- throw new Error('Failed to initialize Outlook OAuth');
1890
- }
1891
- }
1892
-
1893
- async handleOutlookOAuthCallback(
1894
- code: string,
1895
- state: string,
1896
- ): Promise<GmailSSOResult> {
1897
- try {
1898
- const oauthState = this.gmailOAuthStates.get(state);
1899
- if (!oauthState) {
1900
- throw new Error('Invalid or expired OAuth state');
1901
- }
1902
-
1903
- this.gmailOAuthStates.delete(state);
1904
-
1905
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1906
- throw new Error('OAuth state expired');
1907
- }
1908
-
1909
- const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1910
- const clientSecret = this.configService.get<string>(
1911
- 'OUTLOOK_CLIENT_SECRET',
1912
- );
1913
- const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1914
- const callbackUrl =
1915
- this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1916
- 'http://localhost:5001/auth/outlook/callback';
1917
-
1918
- // Exchange code for tokens
1919
- const tokenResponse = await fetch(
1920
- `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
1921
- {
1922
- method: 'POST',
1923
- headers: {
1924
- 'Content-Type': 'application/x-www-form-urlencoded',
1925
- },
1926
- body: new URLSearchParams({
1927
- client_id: clientId!,
1928
- client_secret: clientSecret!,
1929
- code: code,
1930
- redirect_uri: callbackUrl,
1931
- grant_type: 'authorization_code',
1932
- }),
1933
- },
1934
- );
1935
-
1936
- const tokens = await tokenResponse.json();
1937
-
1938
- if (!tokens.access_token) {
1939
- throw new Error('Failed to obtain access token');
1940
- }
1941
-
1942
- // Get user info from Microsoft Graph
1943
- const userResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
1944
- headers: {
1945
- Authorization: `Bearer ${tokens.access_token}`,
1946
- },
1947
- });
1948
-
1949
- const userInfo = await userResponse.json();
1950
- const email = userInfo.mail || userInfo.userPrincipalName;
1951
-
1952
- if (!email) {
1953
- throw new Error('Failed to get user email');
1954
- }
1955
-
1956
- // Validate that no active EMAIL configuration exists
1957
- await this.validateUniqueActiveConfig(
1958
- oauthState.levelId,
1959
- oauthState.levelType,
1960
- oauthState.app_code,
1961
- 'EMAIL',
1962
- 'outlook',
1963
- );
1964
-
1965
- const outlookConfig = {
1966
- clientId,
1967
- tenantId,
1968
- email: email,
1969
- accessToken: tokens.access_token,
1970
- refreshToken: tokens.refresh_token,
1971
- scope: tokens.scope,
1972
- tokenType: tokens.token_type,
1973
- expiresIn: tokens.expires_in,
1974
- };
1975
-
1976
- // Create integration config
1977
- const config = this.configRepository.create({
1978
- app_code: oauthState.app_code,
1979
- integration_type: 'EMAIL',
1980
- integration_provider: 'outlook',
1981
- integration_source_id: 1, // Outlook source ID
1982
- level_id: oauthState.levelId,
1983
- level_type: oauthState.levelType,
1984
- status: 1,
1985
- priority: 1,
1986
- is_default: false,
1987
- config_json: outlookConfig as any,
1988
- });
1989
-
1990
- const savedConfig = await this.configRepository.save(config);
1991
-
1992
- this.logger.log(
1993
- `Outlook OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1994
- );
1995
-
1996
- return {
1997
- hubId: savedConfig.id,
1998
- configId: savedConfig.id,
1999
- };
2000
- } catch (error) {
2001
- this.logger.error(
2002
- 'Error handling Outlook OAuth callback:',
2003
- error.message,
2004
- );
2005
- throw new Error(`Failed to complete Outlook OAuth: ${error.message}`);
2006
- }
2007
- }
2008
-
2009
- async getIntegrationConfigById(hubId: number): Promise<
2010
- | (IntegrationConfig & {
2011
- config: IntegrationConfig;
2012
- linkedSource?: string;
2013
- configDetails?: any;
2014
- })
2015
- | null
2016
- > {
2017
- try {
2018
- // Find the integration config by ID
2019
- const integrationConfig = await this.configRepository.findOne({
2020
- where: { id: hubId },
2021
- });
2022
-
2023
- if (!integrationConfig) {
2024
- return null;
2025
- }
2026
-
2027
- // Extract linked source and config details
2028
- const linkedSource = this.extractLinkedSource(
2029
- integrationConfig.integration_type,
2030
- integrationConfig.integration_provider,
2031
- integrationConfig.config_json,
2032
- );
2033
-
2034
- const configDetails = this.extractConfigDetails(
2035
- integrationConfig.integration_type,
2036
- integrationConfig.integration_provider,
2037
- integrationConfig.config_json,
2038
- );
2039
-
2040
- return {
2041
- ...integrationConfig,
2042
- config: integrationConfig,
2043
- linkedSource,
2044
- configDetails,
2045
- };
2046
- } catch (error) {
2047
- this.logger.error(
2048
- `Error fetching communication config by ID ${hubId}:`,
2049
- error.message,
2050
- );
2051
- throw new Error(
2052
- `Failed to fetch communication configuration: ${error.message}`,
2053
- );
2054
- }
2055
- }
2056
-
2057
- async getIntegrationTemplates(
2058
- levelId: number,
2059
- levelType: string,
2060
- app_code: string,
2061
- integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
2062
- ): Promise<{
2063
- success: boolean;
2064
- data?: Array<{
2065
- label: string;
2066
- value: string;
2067
- }>;
2068
- error?: string;
2069
- }> {
2070
- try {
2071
- // Get active configuration for the integration type
2072
- const config = await this.getSingleActiveConfig(
2073
- levelId,
2074
- levelType,
2075
- app_code,
2076
- integration_type,
2077
- );
2078
-
2079
- if (!config) {
2080
- return {
2081
- success: false,
2082
- error: `No active ${integration_type} configuration found for this level`,
2083
- };
2084
- }
2085
-
2086
- // Create strategy instance
2087
- const strategy = this.integrationFactory.create(
2088
- config.integration_type,
2089
- 'API',
2090
- config.integration_provider,
2091
- );
2092
-
2093
- // Check if strategy supports getTemplates
2094
- if (typeof (strategy as any).getTemplates !== 'function') {
2095
- return {
2096
- success: false,
2097
- error: `Template retrieval not supported for provider: ${config.integration_provider}`,
2098
- };
2099
- }
2100
-
2101
- // Call getTemplates method
2102
- return await (strategy as any).getTemplates(config.config_json);
2103
- } catch (error) {
2104
- this.logger.error(
2105
- `Error fetching templates for ${integration_type} level ${levelId}/${levelType}:`,
2106
- error.message,
2107
- );
2108
- return {
2109
- success: false,
2110
- error: `Failed to fetch templates: ${error.message}`,
2111
- };
2112
- }
2113
- }
2114
-
2115
- async getSendGridTemplates(
2116
- levelId: number,
2117
- levelType: string,
2118
- app_code: string,
2119
- ): Promise<{
2120
- success: boolean;
2121
- data?: Array<{
2122
- label: string;
2123
- value: string;
2124
- }>;
2125
- error?: string;
2126
- }> {
2127
- try {
2128
- // Find active SendGrid configurations for this level
2129
- const hubs = await this.getActiveConfigs(
2130
- levelId,
2131
- levelType,
2132
- app_code,
2133
- 'EMAIL',
2134
- );
2135
-
2136
- // Look for SendGrid provider
2137
- const sendGridHub = hubs.find(
2138
- (hub) => hub.integration_provider === 'sendgrid',
2139
- );
2140
-
2141
- if (!sendGridHub) {
2142
- return {
2143
- success: false,
2144
- error: 'No active SendGrid configuration found for this level',
2145
- };
2146
- }
2147
-
2148
- // Extract API key from configuration
2149
- const apiKey = sendGridHub.config_json?.apiKey;
2150
-
2151
- if (!apiKey) {
2152
- return {
2153
- success: false,
2154
- error: 'SendGrid API key not found in configuration',
2155
- };
2156
- }
2157
-
2158
- // Use the SendGrid strategy to fetch templates
2159
- return this.sendGridApiStrategy.getTemplates(apiKey);
2160
- } catch (error) {
2161
- this.logger.error(
2162
- `Error fetching SendGrid templates for level ${levelId}/${levelType}:`,
2163
- error.message,
2164
- );
2165
- return {
2166
- success: false,
2167
- error: `Failed to fetch SendGrid templates: ${error.message}`,
2168
- };
2169
- }
2170
- }
2171
-
2172
- async getSendGridVerifiedSenders(apiKey: string): Promise<{
2173
- success: boolean;
2174
- data?: Array<{
2175
- label: string;
2176
- value: string;
2177
- }>;
2178
- error?: string;
2179
- }> {
2180
- try {
2181
- if (!apiKey) {
2182
- return {
2183
- success: false,
2184
- error: 'SendGrid API key not found in configuration',
2185
- };
2186
- }
2187
-
2188
- // Use the SendGrid strategy to fetch verified senders
2189
- return this.sendGridApiStrategy.getVerifiedSenders(apiKey);
2190
- } catch (error) {
2191
- this.logger.error(
2192
- `Error fetching SendGrid verified senders`,
2193
- error.message,
2194
- );
2195
- return {
2196
- success: false,
2197
- error: `Failed to fetch SendGrid verified senders: ${error.message}`,
2198
- };
2199
- }
2200
- }
2201
-
2202
- // UserIntegration Management Methods
2203
-
2204
- async createUserIntegration(
2205
- createDto: CreateUserIntegrationDto,
2206
- ): Promise<UserIntegration> {
2207
- try {
2208
- // Check if mapping already exists
2209
- const existing = await this.userIntegrationRepository.findOne({
2210
- where: {
2211
- user_id: createDto.user_id,
2212
- integration_config_id: createDto.integration_config_id,
2213
- },
2214
- });
2215
-
2216
- if (existing) {
2217
- throw new Error('User integration mapping already exists');
2218
- }
2219
-
2220
- // Verify integration config exists
2221
- const config = await this.configRepository.findOne({
2222
- where: { id: createDto.integration_config_id },
2223
- });
2224
-
2225
- if (!config) {
2226
- throw new Error('Integration configuration not found');
2227
- }
2228
-
2229
- const userIntegration = this.userIntegrationRepository.create(createDto);
2230
- return await this.userIntegrationRepository.save(userIntegration);
2231
- } catch (error) {
2232
- this.logger.error(
2233
- `Error creating user integration mapping: ${error.message}`,
2234
- );
2235
- throw error;
2236
- }
2237
- }
2238
-
2239
- async bulkCreateUserIntegration(
2240
- bulkDto: BulkCreateUserIntegrationDto,
2241
- ): Promise<{
2242
- created: UserIntegration[];
2243
- updated: UserIntegration[];
2244
- failed: Array<{ data: CreateUserIntegrationDto; error: string }>;
2245
- summary: {
2246
- total: number;
2247
- created: number;
2248
- updated: number;
2249
- failed: number;
2250
- };
2251
- }> {
2252
- const created: UserIntegration[] = [];
2253
- const updated: UserIntegration[] = [];
2254
- const failed: Array<{ data: CreateUserIntegrationDto; error: string }> = [];
2255
-
2256
- try {
2257
- for (const createDto of bulkDto.user_integrations) {
2258
- try {
2259
- // Check if mapping already exists
2260
- const existing = await this.userIntegrationRepository.findOne({
2261
- where: {
2262
- user_id: createDto.user_id,
2263
- integration_config_id: createDto.integration_config_id,
2264
- },
2265
- });
2266
-
2267
- if (existing) {
2268
- // Update existing mapping
2269
- if (createDto.external_user_id !== undefined) {
2270
- existing.external_user_id = createDto.external_user_id;
2271
- }
2272
- if (createDto.external_user_data !== undefined) {
2273
- existing.external_user_data = createDto.external_user_data;
2274
- }
2275
- if (createDto.is_active !== undefined) {
2276
- existing.is_active = createDto.is_active;
2277
- }
2278
-
2279
- const updatedIntegration =
2280
- await this.userIntegrationRepository.save(existing);
2281
- updated.push(updatedIntegration);
2282
-
2283
- this.logger.log(
2284
- `Updated user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2285
- );
2286
- } else {
2287
- // Verify integration config exists
2288
- const config = await this.configRepository.findOne({
2289
- where: { id: createDto.integration_config_id },
2290
- });
2291
-
2292
- if (!config) {
2293
- failed.push({
2294
- data: createDto,
2295
- error: 'Integration configuration not found',
2296
- });
2297
- continue;
2298
- }
2299
-
2300
- // Create new mapping
2301
- const userIntegration =
2302
- this.userIntegrationRepository.create(createDto);
2303
- const savedIntegration =
2304
- await this.userIntegrationRepository.save(userIntegration);
2305
- created.push(savedIntegration);
2306
-
2307
- this.logger.log(
2308
- `Created user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2309
- );
2310
- }
2311
- } catch (error) {
2312
- failed.push({
2313
- data: createDto,
2314
- error: error.message || 'Unknown error',
2315
- });
2316
- this.logger.error(
2317
- `Error processing user integration for user ${createDto.user_id}: ${error.message}`,
2318
- );
2319
- }
2320
- }
2321
-
2322
- const summary = {
2323
- total: bulkDto.user_integrations.length,
2324
- created: created.length,
2325
- updated: updated.length,
2326
- failed: failed.length,
2327
- };
2328
-
2329
- this.logger.log(
2330
- `Bulk user integration completed: ${summary.created} created, ${summary.updated} updated, ${summary.failed} failed`,
2331
- );
2332
-
2333
- return { created, updated, failed, summary };
2334
- } catch (error) {
2335
- this.logger.error(
2336
- `Error in bulk user integration creation: ${error.message}`,
2337
- );
2338
- throw error;
2339
- }
2340
- }
2341
-
2342
- async getUserIntegrations(userId: number): Promise<UserIntegration[]> {
2343
- try {
2344
- return await this.userIntegrationRepository.find({
2345
- where: { user_id: userId, is_active: true },
2346
- order: { created_at: 'DESC' },
2347
- });
2348
- } catch (error) {
2349
- this.logger.error(
2350
- `Error fetching user integrations for user ${userId}: ${error.message}`,
2351
- );
2352
- throw error;
2353
- }
2354
- }
2355
-
2356
- async getConfigUserIntegrations(
2357
- configId: number,
2358
- ): Promise<UserIntegration[]> {
2359
- try {
2360
- return await this.userIntegrationRepository.find({
2361
- where: { integration_config_id: configId, is_active: true },
2362
- order: { created_at: 'DESC' },
2363
- });
2364
- } catch (error) {
2365
- this.logger.error(
2366
- `Error fetching user integrations for config ${configId}: ${error.message}`,
2367
- );
2368
- throw error;
2369
- }
2370
- }
2371
-
2372
- async getUserIntegrationByUserAndConfig(
2373
- userId: number,
2374
- configId: number,
2375
- ): Promise<UserIntegration | null> {
2376
- try {
2377
- return await this.userIntegrationRepository.findOne({
2378
- where: {
2379
- user_id: userId,
2380
- integration_config_id: configId,
2381
- is_active: true,
2382
- },
2383
- });
2384
- } catch (error) {
2385
- this.logger.error(
2386
- `Error fetching user integration for user ${userId} and config ${configId}: ${error.message}`,
2387
- );
2388
- throw error;
2389
- }
2390
- }
2391
-
2392
- async updateUserIntegration(
2393
- id: number,
2394
- updateDto: UpdateUserIntegrationDto,
2395
- ): Promise<UserIntegration> {
2396
- try {
2397
- const userIntegration = await this.userIntegrationRepository.findOne({
2398
- where: { id },
2399
- });
2400
-
2401
- if (!userIntegration) {
2402
- throw new Error('User integration mapping not found');
2403
- }
2404
-
2405
- Object.assign(userIntegration, updateDto);
2406
- return await this.userIntegrationRepository.save(userIntegration);
2407
- } catch (error) {
2408
- this.logger.error(
2409
- `Error updating user integration ${id}: ${error.message}`,
2410
- );
2411
- throw error;
2412
- }
2413
- }
2414
-
2415
- async deleteUserIntegration(id: number): Promise<void> {
2416
- try {
2417
- const userIntegration = await this.userIntegrationRepository.findOne({
2418
- where: { id },
2419
- });
2420
-
2421
- if (!userIntegration) {
2422
- throw new Error('User integration mapping not found');
2423
- }
2424
-
2425
- await this.userIntegrationRepository.remove(userIntegration);
2426
- } catch (error) {
2427
- this.logger.error(
2428
- `Error deleting user integration ${id}: ${error.message}`,
2429
- );
2430
- throw error;
2431
- }
2432
- }
2433
-
2434
- /**
2435
- * Get user integration data for a specific integration strategy
2436
- * This method is intended to be used by strategies that need user mapping
2437
- */
2438
- async getUserIntegrationForStrategy(
2439
- userId: number,
2440
- integrationConfigId: number,
2441
- ): Promise<any | null> {
2442
- try {
2443
- const userIntegration = await this.getUserIntegrationByUserAndConfig(
2444
- userId,
2445
- integrationConfigId,
2446
- );
2447
-
2448
- if (!userIntegration) {
2449
- return null;
2450
- }
2451
-
2452
- return {
2453
- external_user_id: userIntegration.external_user_id,
2454
- external_user_data: userIntegration.external_user_data,
2455
- };
2456
- } catch (error) {
2457
- this.logger.error(
2458
- `Error fetching user integration data for strategy: ${error.message}`,
2459
- );
2460
- return null;
2461
- }
2462
- }
2463
-
2464
- /**
2465
- * Check agent status for TELEPHONE integration
2466
- * Works with any provider that implements checkAgentStatus method
2467
- */
2468
- async checkAgentStatus(
2469
- levelId: number,
2470
- levelType: string,
2471
- appCode: string,
2472
- userId: number,
2473
- integrationType: 'TELEPHONE' = 'TELEPHONE',
2474
- ): Promise<{
2475
- success: boolean;
2476
- isReady?: boolean;
2477
- state?: string;
2478
- agentInfo?: any;
2479
- error?: string;
2480
- }> {
2481
- try {
2482
- // Get the active configuration
2483
- const config = await this.getSingleActiveConfig(
2484
- levelId,
2485
- levelType,
2486
- appCode,
2487
- integrationType,
2488
- );
2489
-
2490
- if (!config) {
2491
- return {
2492
- success: false,
2493
- error: 'No active TELEPHONE configuration found',
2494
- };
2495
- }
2496
-
2497
- // Get user integration mapping
2498
- const userIntegration = await this.getUserIntegrationByUserAndConfig(
2499
- userId,
2500
- config.id,
2501
- );
2502
-
2503
- if (!userIntegration) {
2504
- return {
2505
- success: false,
2506
- error: 'User integration mapping not found. Please configure agent details.',
2507
- };
2508
- }
2509
-
2510
- // Create strategy instance
2511
- const strategy = this.integrationFactory.create(
2512
- config.integration_type,
2513
- 'API', // service is deprecated, using default
2514
- config.integration_provider,
2515
- );
2516
-
2517
- // Get the merged config with user data
2518
- let mergedConfig = config.config_json;
2519
-
2520
- if (strategy.createUserSpecificConfig) {
2521
- mergedConfig = strategy.createUserSpecificConfig(
2522
- config.config_json,
2523
- userIntegration.external_user_id,
2524
- );
2525
- }
2526
-
2527
- // Check if strategy supports agent status check
2528
- if (typeof (strategy as any).checkAgentStatus !== 'function') {
2529
- return {
2530
- success: false,
2531
- error: `Agent status check not supported for provider: ${config.integration_provider}`,
2532
- };
2533
- }
2534
-
2535
- // Check agent status
2536
- const statusResult = await (strategy as any).checkAgentStatus(
2537
- mergedConfig,
2538
- );
2539
-
2540
- return {
2541
- success: true,
2542
- isReady: statusResult.isReady,
2543
- state: statusResult.state,
2544
- error: statusResult.error,
2545
- };
2546
- } catch (error) {
2547
- this.logger.error(
2548
- `Error checking agent status: ${error.message}`,
2549
- error.stack,
2550
- );
2551
- return {
2552
- success: false,
2553
- error: error.message || 'Failed to check agent status',
2554
- };
2555
- }
2556
- }
2557
- }
1
+ import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
2
+ import { InjectRepository } from '@nestjs/typeorm';
3
+ import { DataSource, Not, Repository } from 'typeorm';
4
+ import { ConfigService } from '@nestjs/config';
5
+ import { google } from 'googleapis';
6
+ import { IntegrationConfig } from '../entity/integration-config.entity';
7
+ import { UserIntegration } from '../entity/user-integration.entity';
8
+ import { IntegrationEntityMapper } from '../entity/integration-entity-mapper.entity';
9
+ import { IntegrationFactory } from '../factories/integration.factory';
10
+ import { IntegrationResult } from '../strategies/integration.strategy';
11
+ import { GmailApiStrategy } from '../strategies/email/gmail-api.strategy';
12
+ import { SendGridApiStrategy } from '../strategies/email/sendgrid-api.strategy';
13
+ import { IntegrationQueueService } from './integration-queue.service';
14
+ import {
15
+ BulkMessageDto,
16
+ BulkCreateUserIntegrationDto,
17
+ CreateUserIntegrationDto,
18
+ UpdateUserIntegrationDto,
19
+ } from '../dto/create-config.dto';
20
+ import { FieldMapperService } from '../../mapper/service/field-mapper.service';
21
+ import { COMM_TEMPLATE } from '../../../constant/global.constant';
22
+ import { EntityServiceImpl } from '../../meta/service/entity-service-impl.service';
23
+
24
+ export interface SendMessageDto {
25
+ levelId: number;
26
+ levelType: string;
27
+ app_code: string;
28
+ to: string;
29
+ message: string;
30
+ mode?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
31
+ priority?: number;
32
+ user_id?: number;
33
+ }
34
+
35
+ export interface GenericMessageDto {
36
+ levelId: number;
37
+ levelType: string;
38
+ app_code: string;
39
+ to: string | string[];
40
+ message: string;
41
+ subject?: string;
42
+ type?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
43
+ priority?: 'high' | 'medium' | 'low';
44
+ cc?: string | string[];
45
+ bcc?: string | string[];
46
+ html?: string;
47
+ attachments?: any[];
48
+ mediaUrl?: string;
49
+ templateId?: string;
50
+ variables?: Record<string, any>;
51
+ user_id?: number;
52
+ entity_type?: string;
53
+ entity_id?: number;
54
+ }
55
+
56
+ export interface IntegrationConfigWithConfig extends IntegrationConfig {
57
+ config?: any;
58
+ }
59
+
60
+ interface GmailOAuthState {
61
+ levelId: number;
62
+ levelType: string;
63
+ app_code: string;
64
+ email?: string;
65
+ timestamp: number;
66
+ }
67
+
68
+ export interface GmailSSOResult {
69
+ hubId: number;
70
+ configId: number;
71
+ }
72
+
73
+ @Injectable()
74
+ export class IntegrationService {
75
+ private readonly logger = new Logger(IntegrationService.name);
76
+ private readonly gmailOAuthStates = new Map<string, GmailOAuthState>();
77
+
78
+ constructor(
79
+ @InjectRepository(IntegrationConfig)
80
+ private readonly configRepository: Repository<IntegrationConfig>,
81
+ @InjectRepository(UserIntegration)
82
+ private readonly userIntegrationRepository: Repository<UserIntegration>,
83
+ @InjectRepository(IntegrationEntityMapper)
84
+ private readonly entityMapperRepository: Repository<IntegrationEntityMapper>,
85
+ private readonly dataSource: DataSource,
86
+ private readonly integrationFactory: IntegrationFactory,
87
+ private readonly gmailApiStrategy: GmailApiStrategy,
88
+ private readonly sendGridApiStrategy: SendGridApiStrategy,
89
+ private readonly configService: ConfigService,
90
+ @Inject('FieldMapperService') private readonly fieldMapperService: FieldMapperService,
91
+ private readonly entityService: EntityServiceImpl,
92
+ @Inject(forwardRef(() => IntegrationQueueService))
93
+ private readonly queueService?: IntegrationQueueService,
94
+ ) {
95
+ }
96
+
97
+ private deriveServiceType(
98
+ integration_type: string,
99
+ integration_provider: string,
100
+ config_json: any,
101
+ ): string {
102
+ // All integrations use API only (no SMTP support)
103
+ return 'API';
104
+ }
105
+
106
+ async sendMessage({
107
+ levelId,
108
+ levelType,
109
+ app_code,
110
+ to,
111
+ message,
112
+ mode,
113
+ priority = 1,
114
+ user_id,
115
+ }: SendMessageDto): Promise<IntegrationResult> {
116
+ try {
117
+ // Get active communication configs for the level
118
+ const configs = await this.getActiveConfigs(
119
+ levelId,
120
+ levelType,
121
+ app_code,
122
+ mode,
123
+ );
124
+
125
+ if (!configs.length) {
126
+ throw new Error(
127
+ `No active communication configuration found for ${levelType} ${levelId}`,
128
+ );
129
+ }
130
+
131
+ // Sort by priority if provided
132
+ const sortedConfigs = this.sortConfigsByPriority(configs, priority);
133
+
134
+ // Try each config until one succeeds
135
+ for (const config of sortedConfigs) {
136
+ try {
137
+ const result = await this.sendViaConfig(config, to, message, user_id);
138
+ if (result.success) {
139
+ this.logger.log(
140
+ `Message sent successfully via ${config.integration_provider}`,
141
+ );
142
+ return result;
143
+ }
144
+
145
+ this.logger.warn(
146
+ `Failed to send via ${config.integration_provider}: ${result.error}`,
147
+ );
148
+ } catch (error) {
149
+ this.logger.error(
150
+ `Error sending via ${config.integration_provider}:`,
151
+ error.message,
152
+ );
153
+ continue;
154
+ }
155
+ }
156
+
157
+ throw new Error('All communication providers failed');
158
+ } catch (error) {
159
+ this.logger.error('Communication service error:', error.message);
160
+ throw error;
161
+ }
162
+ }
163
+
164
+ async getActiveConfigs(
165
+ levelId: number,
166
+ levelType: string,
167
+ app_code: string,
168
+ mode?: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
169
+ ): Promise<IntegrationConfig[]> {
170
+ const queryBuilder = this.configRepository
171
+ .createQueryBuilder('config')
172
+ .where('config.level_id = :levelId', { levelId })
173
+ .andWhere('config.level_type = :levelType', { levelType })
174
+ .andWhere('config.app_code = :app_code', { app_code })
175
+ .andWhere('config.status = 1');
176
+
177
+ if (mode) {
178
+ queryBuilder.andWhere('config.integration_type = :mode', { mode });
179
+ }
180
+
181
+ return await queryBuilder.getMany();
182
+ }
183
+
184
+ async getSingleActiveConfig(
185
+ levelId: number,
186
+ levelType: string,
187
+ app_code: string,
188
+ integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
189
+ ): Promise<IntegrationConfig | null> {
190
+ const configs = await this.configRepository
191
+ .createQueryBuilder('config')
192
+ .where('config.level_id = :levelId', { levelId })
193
+ .andWhere('config.level_type = :levelType', { levelType })
194
+ .andWhere('config.app_code = :app_code', { app_code })
195
+ .andWhere('config.integration_type = :integration_type', { integration_type })
196
+ .andWhere('config.status = 1')
197
+ .orderBy('config.is_default', 'DESC')
198
+ .addOrderBy('config.priority', 'ASC')
199
+ .addOrderBy('config.created_at', 'DESC')
200
+ .getMany();
201
+
202
+ return configs.length > 0 ? configs[0] : null;
203
+ }
204
+
205
+ async getAllIntegrationData(
206
+ loggedInUser,
207
+ integration_type?: string,
208
+ ): Promise<any[]> {
209
+ try {
210
+ const allIntegrationData = await this.dataSource.query(
211
+ `SELECT *
212
+ FROM cr_integration_master`,
213
+ );
214
+
215
+ // if entityType is provided, filter the results
216
+ if (integration_type) {
217
+ return allIntegrationData.filter(
218
+ (data) =>
219
+ data.integration_type.toLowerCase() ===
220
+ integration_type.toLowerCase(),
221
+ );
222
+ }
223
+
224
+ return allIntegrationData;
225
+ } catch (error) {
226
+ this.logger.error('Error fetching integration data:', error.message);
227
+ return [];
228
+ }
229
+ }
230
+
231
+ private sortConfigsByPriority(
232
+ configs: IntegrationConfig[],
233
+ _priority: number,
234
+ ): IntegrationConfig[] {
235
+ return configs.sort((a, b) => {
236
+ // First sort by default (true comes first)
237
+ if (a.is_default !== b.is_default) {
238
+ return a.is_default ? -1 : 1;
239
+ }
240
+ // Then by priority (lower number = higher priority)
241
+ return a.priority - b.priority;
242
+ });
243
+ }
244
+
245
+ private async sendViaConfig(
246
+ config: IntegrationConfig,
247
+ to: string,
248
+ message: string,
249
+ user_id?: number,
250
+ ): Promise<IntegrationResult> {
251
+ const strategy = this.integrationFactory.create(
252
+ config.integration_type,
253
+ 'API', // service is deprecated, using default
254
+ config.integration_provider,
255
+ );
256
+
257
+ // Get user integration data if user_id provided
258
+ let finalConfig = config.config_json;
259
+ if (user_id) {
260
+ const userIntegrationData = await this.getUserIntegrationForStrategy(
261
+ user_id,
262
+ config.id,
263
+ );
264
+
265
+ if (userIntegrationData) {
266
+ finalConfig = {
267
+ ...config.config_json,
268
+ external_user_id: userIntegrationData.external_user_id,
269
+ };
270
+ }
271
+ }
272
+
273
+ const result = await strategy.sendMessage(to, message, finalConfig);
274
+
275
+ // If token was refreshed, update it in the database
276
+ if (result.refreshedToken && result.success) {
277
+ try {
278
+ const currentConfig = config.config_json as any;
279
+ const updatedConfig = {
280
+ ...currentConfig,
281
+ accessToken: result.refreshedToken,
282
+ };
283
+
284
+ await this.configRepository.update(config.id, {
285
+ config_json: updatedConfig,
286
+ } as any);
287
+
288
+ this.logger.log(
289
+ `Updated access token for ${config.integration_provider} configuration`,
290
+ );
291
+ } catch (error) {
292
+ this.logger.warn(
293
+ `Failed to update refreshed token in database: ${error.message}`,
294
+ );
295
+ }
296
+ }
297
+
298
+ return result;
299
+ }
300
+
301
+ async createIntegrationConfig(
302
+ levelId: number,
303
+ levelType: string,
304
+ app_code: string,
305
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
306
+ provider: string,
307
+ integration_source_id: number,
308
+ config: any,
309
+ priority?: number,
310
+ is_default?: boolean,
311
+ ): Promise<
312
+ IntegrationConfig | { authUrl: string; state: string; message: string }
313
+ > {
314
+ // Validate that no duplicate provider configurations exist
315
+ await this.validateUniqueActiveConfig(
316
+ levelId,
317
+ levelType,
318
+ app_code,
319
+ configType,
320
+ provider,
321
+ );
322
+
323
+ // Deactivate all other configurations of the same integration type
324
+ await this.configRepository.update(
325
+ {
326
+ level_id: levelId,
327
+ level_type: levelType,
328
+ app_code: app_code,
329
+ integration_type: configType,
330
+ status: 1,
331
+ },
332
+ { status: 0 },
333
+ );
334
+
335
+ // Validate provider and get service type from supported combinations
336
+ const supportedCombinations = await this.getSupportedCombinations();
337
+ const validCombination = supportedCombinations.find(
338
+ (combo) =>
339
+ combo.mode === configType &&
340
+ combo.provider.toLowerCase() === provider.toLowerCase(),
341
+ );
342
+
343
+ if (!validCombination) {
344
+ throw new Error(`Unsupported combination: ${configType}/${provider}`);
345
+ }
346
+
347
+ const service = validCombination.service;
348
+
349
+ // Check if this requires OAuth flow
350
+ const requiresOAuth = this.requiresOAuthFlow(configType, provider, config);
351
+
352
+ if (requiresOAuth) {
353
+ // Generate OAuth URL and return it instead of creating config immediately
354
+ return await this.generateOAuthUrl(
355
+ levelId,
356
+ levelType,
357
+ app_code,
358
+ configType,
359
+ provider,
360
+ integration_source_id,
361
+ config,
362
+ priority,
363
+ is_default,
364
+ );
365
+ }
366
+
367
+ // Direct config creation (non-OAuth flow)
368
+ return await this.createDirectConfig(
369
+ levelId,
370
+ levelType,
371
+ app_code,
372
+ configType,
373
+ provider,
374
+ integration_source_id,
375
+ config,
376
+ priority,
377
+ is_default,
378
+ );
379
+ }
380
+
381
+ getSupportedCombinations(): {
382
+ mode: string;
383
+ service: string;
384
+ provider: string;
385
+ }[] {
386
+ return this.integrationFactory.getAllSupportedCombinations();
387
+ }
388
+
389
+ async getLevelConfigs(
390
+ levelId: number,
391
+ levelType: string,
392
+ filters?: {
393
+ app_code?: string;
394
+ integration_type?: 'WA' | 'SMS' | 'EMAIL' | 'TELEPHONE';
395
+ integration_provider?: string;
396
+ },
397
+ ): Promise<
398
+ Array<IntegrationConfig & { linkedSource?: string; configDetails?: any }>
399
+ > {
400
+ const where: any = { level_id: levelId, level_type: levelType };
401
+
402
+ if (filters?.app_code) {
403
+ where.app_code = filters.app_code;
404
+ }
405
+
406
+ if (filters?.integration_type) {
407
+ where.integration_type = filters.integration_type;
408
+ }
409
+
410
+ if (filters?.integration_provider) {
411
+ where.integration_provider = filters.integration_provider;
412
+ }
413
+
414
+ const hubs = await this.configRepository.find({
415
+ where,
416
+ order: { created_at: 'DESC' },
417
+ });
418
+
419
+ // Enhance hubs with linked source information
420
+ const enhancedHubs = await Promise.all(
421
+ hubs.map(async (hub) => {
422
+ try {
423
+ const relatedConfig = await this.configRepository.findOne({
424
+ where: { id: hub.id },
425
+ });
426
+
427
+ if (!relatedConfig) {
428
+ return {
429
+ ...hub,
430
+ linkedSource: 'Configuration not found',
431
+ configDetails: null,
432
+ };
433
+ }
434
+
435
+ const linkedSource = this.extractLinkedSource(
436
+ hub.integration_type,
437
+ hub.integration_provider,
438
+ relatedConfig.config_json,
439
+ );
440
+
441
+ const configDetails = this.extractConfigDetails(
442
+ hub.integration_type,
443
+ hub.integration_provider,
444
+ relatedConfig.config_json,
445
+ );
446
+
447
+ return {
448
+ ...hub,
449
+ linkedSource,
450
+ configDetails,
451
+ };
452
+ } catch (error) {
453
+ this.logger.warn(
454
+ `Error extracting linked source for hub ${hub.id}:`,
455
+ error.message,
456
+ );
457
+ return {
458
+ ...hub,
459
+ linkedSource: 'Error retrieving source',
460
+ configDetails: null,
461
+ };
462
+ }
463
+ }),
464
+ );
465
+
466
+ return enhancedHubs;
467
+ }
468
+
469
+ private extractLinkedSource(
470
+ configType: string,
471
+ provider: string,
472
+ configJson: any,
473
+ ): string {
474
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
475
+
476
+ try {
477
+ switch (key) {
478
+ // Gmail configurations
479
+ case 'email_gmail':
480
+ case 'email_smtp_gmail':
481
+ return configJson?.email || 'Gmail account not configured';
482
+
483
+ // Outlook configurations
484
+ case 'email_outlook':
485
+ case 'email_smtp_outlook':
486
+ return configJson?.email || 'Outlook account not configured';
487
+
488
+ // WhatsApp configurations
489
+ case 'wa_api_whatsapp':
490
+ return configJson?.phoneNumberId
491
+ ? `WhatsApp Business: ${configJson.phoneNumberId}`
492
+ : 'WhatsApp not configured';
493
+
494
+ // SMS configurations
495
+ case 'sms_third_party_twilio':
496
+ return configJson?.fromNumber
497
+ ? `Twilio: ${configJson.fromNumber}`
498
+ : 'Twilio number not configured';
499
+
500
+ case 'sms_third_party_knowlarity':
501
+ return configJson?.callerNumber
502
+ ? `Knowlarity: ${configJson.callerNumber}`
503
+ : 'Knowlarity number not configured';
504
+
505
+ // Telephone configurations
506
+ case 'telephone_third_party_knowlarity':
507
+ return configJson?.callerNumber
508
+ ? `Knowlarity Voice: ${configJson.callerNumber}`
509
+ : 'Knowlarity voice number not configured';
510
+
511
+ case 'telephone_third_party_ozonetel':
512
+ return configJson?.userName
513
+ ? `Ozonetel Voice: ${configJson.userName}`
514
+ : 'Ozonetel voice not configured';
515
+
516
+ // AWS SES configurations
517
+ case 'email_aws-ses':
518
+ case 'email_ses':
519
+ return configJson?.fromEmail || 'AWS SES not configured';
520
+
521
+ // SendGrid configurations
522
+ case 'email_smtp_sendgrid':
523
+ return configJson?.from || 'SendGrid not configured';
524
+
525
+ // Generic SMTP configurations
526
+ case 'email_smtp_custom':
527
+ case 'email_smtp_generic':
528
+ return configJson?.from || configJson?.user || 'SMTP not configured';
529
+
530
+ default:
531
+ // Generic fallback - try to find common identifier fields
532
+ if (configJson?.email) return configJson.email;
533
+ if (configJson?.from) return configJson.from;
534
+ if (configJson?.user) return configJson.user;
535
+ if (configJson?.phoneNumberId) return configJson.phoneNumberId;
536
+ if (configJson?.fromNumber) return configJson.fromNumber;
537
+ if (configJson?.callerNumber) return configJson.callerNumber;
538
+
539
+ return `${provider} configured`;
540
+ }
541
+ } catch (error) {
542
+ return 'Configuration error';
543
+ }
544
+ }
545
+
546
+ private extractConfigDetails(
547
+ configType: string,
548
+ provider: string,
549
+ configJson: any,
550
+ ): any {
551
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
552
+
553
+ try {
554
+ switch (key) {
555
+ // Gmail configurations
556
+ case 'email_gmail':
557
+ return {
558
+ email: configJson?.email,
559
+ authMethod: configJson?.authMethod || 'OAUTH2',
560
+ hasRefreshToken: !!configJson?.refreshToken,
561
+ isExpired: configJson?.expiryDate
562
+ ? new Date(configJson.expiryDate) < new Date()
563
+ : false,
564
+ };
565
+
566
+ case 'email_smtp_gmail':
567
+ return {
568
+ email: configJson?.email,
569
+ authMethod: 'SMTP',
570
+ hasPassword: !!configJson?.password,
571
+ };
572
+
573
+ // Outlook configurations
574
+ case 'email_outlook':
575
+ return {
576
+ email: configJson?.email,
577
+ authMethod: 'OAUTH2',
578
+ hasRefreshToken: !!configJson?.refreshToken,
579
+ tenantId: configJson?.tenantId,
580
+ };
581
+
582
+ case 'email_smtp_outlook':
583
+ return {
584
+ email: configJson?.email,
585
+ authMethod: 'SMTP',
586
+ hasPassword: !!configJson?.password,
587
+ };
588
+
589
+ // WhatsApp configurations
590
+ case 'wa_api_whatsapp':
591
+ return {
592
+ phoneNumberId: configJson?.phoneNumberId,
593
+ apiVersion: configJson?.apiVersion || 'v17.0',
594
+ hasAccessToken: !!configJson?.accessToken,
595
+ };
596
+
597
+ // SMS configurations
598
+ case 'sms_third_party_twilio':
599
+ return {
600
+ fromNumber: configJson?.fromNumber,
601
+ accountSid: configJson?.accountSid
602
+ ? configJson.accountSid.substring(0, 8) + '...'
603
+ : null,
604
+ hasAuthToken: !!configJson?.authToken,
605
+ };
606
+
607
+ case 'sms_third_party_knowlarity':
608
+ return {
609
+ callerNumber: configJson?.callerNumber,
610
+ callType: configJson?.callType || 'sms',
611
+ hasApiSecret: !!configJson?.apiSecret,
612
+ };
613
+
614
+ // Telephone configurations
615
+ case 'telephone_third_party_knowlarity':
616
+ return {
617
+ callerNumber: configJson?.callerNumber,
618
+ callType: configJson?.callType || 'voice',
619
+ language: configJson?.language || 'en',
620
+ hasApiSecret: !!configJson?.apiSecret,
621
+ };
622
+
623
+ case 'telephone_third_party_ozonetel':
624
+ return {
625
+ userName: configJson?.userName,
626
+ agentID: configJson?.agentID,
627
+ campaignName: configJson?.campaignName,
628
+ agentLoginUrl: configJson?.agentLoginUrl,
629
+ hasApiKey: !!configJson?.apiKey,
630
+ };
631
+
632
+ // AWS SES configurations
633
+ case 'email_aws-ses':
634
+ case 'email_ses':
635
+ return {
636
+ fromEmail: configJson?.fromEmail,
637
+ region: configJson?.region,
638
+ hasCredentials: !!(
639
+ configJson?.accessKeyId && configJson?.secretAccessKey
640
+ ),
641
+ };
642
+
643
+ // SendGrid configurations
644
+ case 'email_smtp_sendgrid':
645
+ return {
646
+ from: configJson?.from,
647
+ hasApiKey: !!configJson?.apiKey,
648
+ templateId: configJson?.templateId,
649
+ };
650
+
651
+ // Generic SMTP configurations
652
+ case 'email_smtp_custom':
653
+ case 'email_smtp_generic':
654
+ return {
655
+ host: configJson?.host,
656
+ port: configJson?.port || 587,
657
+ secure: configJson?.secure || false,
658
+ from: configJson?.from || configJson?.user,
659
+ hasCredentials: !!(configJson?.user && configJson?.password),
660
+ };
661
+
662
+ default: {
663
+ // Generic details - return safe subset of config
664
+ const safeConfig: any = {};
665
+
666
+ // Include non-sensitive fields
667
+ const safeFields = [
668
+ 'email',
669
+ 'from',
670
+ 'user',
671
+ 'host',
672
+ 'port',
673
+ 'secure',
674
+ 'phoneNumberId',
675
+ 'fromNumber',
676
+ 'callerNumber',
677
+ 'region',
678
+ 'apiVersion',
679
+ 'callType',
680
+ 'language',
681
+ 'templateId',
682
+ ];
683
+
684
+ safeFields.forEach((field) => {
685
+ if (configJson?.[field]) {
686
+ safeConfig[field] = configJson[field];
687
+ }
688
+ });
689
+
690
+ // Include boolean indicators for sensitive fields
691
+ const sensitiveFields = [
692
+ 'accessToken',
693
+ 'refreshToken',
694
+ 'password',
695
+ 'authToken',
696
+ 'apiKey',
697
+ 'apiSecret',
698
+ 'clientSecret',
699
+ 'secretAccessKey',
700
+ ];
701
+
702
+ sensitiveFields.forEach((field) => {
703
+ if (configJson?.[field]) {
704
+ safeConfig[
705
+ `has${field.charAt(0).toUpperCase() + field.slice(1)}`
706
+ ] = true;
707
+ }
708
+ });
709
+
710
+ return safeConfig;
711
+ }
712
+ }
713
+ } catch (error) {
714
+ return { error: 'Unable to extract configuration details' };
715
+ }
716
+ }
717
+
718
+ async updateConfigStatus(hubId: number, status: number): Promise<void> {
719
+ // Find the hub to get level and type information
720
+ const config = await this.configRepository.findOne({
721
+ where: { id: hubId },
722
+ });
723
+
724
+ if (!config) {
725
+ throw new Error('Integration configuration not found');
726
+ }
727
+
728
+ // If activating, deactivate ALL other configs of the same integration type
729
+ if (status === 1) {
730
+ await this.configRepository.update(
731
+ {
732
+ level_id: config.level_id,
733
+ level_type: config.level_type,
734
+ app_code: config.app_code,
735
+ integration_type: config.integration_type,
736
+ status: 1,
737
+ id: Not(hubId),
738
+ },
739
+ { status: 0 },
740
+ );
741
+ }
742
+
743
+ // Update the requested config
744
+ await this.configRepository.update(hubId, { status });
745
+ }
746
+
747
+ async deleteConfiguration(configId: number): Promise<void> {
748
+ // Find the hub to get the id
749
+ const config = await this.configRepository.findOne({
750
+ where: { id: configId },
751
+ });
752
+
753
+ if (!config) {
754
+ throw new Error('Integration configuration not found');
755
+ }
756
+
757
+ await this.configRepository.delete(configId);
758
+
759
+ this.logger.log(`Integration configuration deleted: ${configId}`);
760
+ }
761
+
762
+ async updateConfiguration(
763
+ hubId: number,
764
+ updateData: {
765
+ config?: any;
766
+ priority?: number;
767
+ is_default?: boolean;
768
+ status?: number;
769
+ },
770
+ ): Promise<IntegrationConfig & { config?: any }> {
771
+ // Find the existing hub
772
+ const config = await this.configRepository.findOne({
773
+ where: { id: hubId },
774
+ });
775
+
776
+ if (!config) {
777
+ throw new Error('Integration configuration not found');
778
+ }
779
+
780
+ // Update configuration JSON if provided
781
+ if (updateData.config) {
782
+ // Merge the new config with existing config
783
+ const updatedConfigJson = {
784
+ ...config.config_json,
785
+ ...updateData.config,
786
+ };
787
+
788
+ await this.configRepository.update(config.id, {
789
+ config_json: updatedConfigJson,
790
+ });
791
+ }
792
+
793
+ // Handle default configuration logic (simplified for now)
794
+ if (updateData.is_default === true) {
795
+ // Remove default from other configurations of same type and level
796
+ await this.configRepository.update(
797
+ {
798
+ level_id: config.level_id,
799
+ level_type: config.level_type,
800
+ integration_type: config.integration_type,
801
+ id: Not(hubId),
802
+ },
803
+ { is_default: false },
804
+ );
805
+ }
806
+
807
+ if (config.integration_type === 'TELEPHONE') {
808
+ try {
809
+ // Extract DID from config (could be did, callerNumber, or fromNumber)
810
+ const did = config.config_json.did;
811
+
812
+ if (did) {
813
+
814
+ await this.entityMapperRepository.delete({integration_config_id: config.id})
815
+
816
+ const entityMapper = this.entityMapperRepository.create({
817
+ integration_config_id: config.id,
818
+ level_id: String(config.level_id),
819
+ level_type: config.level_type,
820
+ appcode: config.app_code,
821
+ did: did,
822
+ campaign_name: config.config_json.campaignName || null,
823
+ });
824
+
825
+ await this.entityMapperRepository.save(entityMapper);
826
+ this.logger.log(
827
+ `DID mapping created for TELEPHONE integration: ${did} for ${config.level_id} ${config.level_type}`,
828
+ );
829
+ }
830
+ } catch (error) {
831
+ this.logger.warn(
832
+ `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
833
+ );
834
+ }
835
+ }
836
+
837
+ // Apply direct config updates if any
838
+ const directUpdates: any = {};
839
+ if (updateData.priority !== undefined)
840
+ directUpdates.priority = updateData.priority;
841
+ if (updateData.is_default !== undefined)
842
+ directUpdates.is_default = updateData.is_default;
843
+ if (updateData.status !== undefined)
844
+ directUpdates.status = updateData.status;
845
+
846
+ if (Object.keys(directUpdates).length > 0) {
847
+ await this.configRepository.update(config.id, directUpdates);
848
+ }
849
+
850
+ // Fetch and return updated config
851
+ const updatedConfig = await this.configRepository.findOne({
852
+ where: { id: hubId },
853
+ });
854
+
855
+ return {
856
+ ...updatedConfig,
857
+ config: updatedConfig?.config_json,
858
+ } as any;
859
+ }
860
+
861
+ async sendGenericMessage(
862
+ messageDto: GenericMessageDto,
863
+ ): Promise<IntegrationResult> {
864
+ try {
865
+ const {
866
+ levelId,
867
+ levelType,
868
+ app_code,
869
+ to,
870
+ message,
871
+ type,
872
+ priority = 'medium',
873
+ html,
874
+ cc,
875
+ bcc,
876
+ attachments,
877
+ mediaUrl,
878
+ templateId,
879
+ user_id,
880
+ entity_id,
881
+ entity_type,
882
+ } = messageDto;
883
+
884
+ let subject = messageDto.subject;
885
+
886
+ // Auto-detect communication type if not specified
887
+ const communicationType = this.detectCommunicationType(to, type);
888
+
889
+ // Get active configs for the detected type
890
+ const configs = await this.getActiveConfigs(
891
+ levelId,
892
+ levelType,
893
+ app_code,
894
+ communicationType,
895
+ );
896
+
897
+ if (!configs.length) {
898
+ this.logger.warn(
899
+ `No communication hubs found for ${levelType} ${levelId}. Please configure integration providers using the createIntegrationConfig method.`,
900
+ );
901
+ throw new Error(
902
+ `No active ${communicationType} configuration found for ${levelType} ${levelId}. Please configure a communication provider first.`,
903
+ );
904
+ }
905
+
906
+ // Sort hubs by priority and default preference
907
+ const sortedConfigs = this.sortConfigsByPriorityAndDefault(
908
+ configs,
909
+ priority,
910
+ );
911
+
912
+ // Prepare enhanced config with additional parameters
913
+ const enhancedConfig = {
914
+ subject,
915
+ html,
916
+ cc,
917
+ bcc,
918
+ attachments,
919
+ mediaUrl,
920
+ };
921
+
922
+ // Handle multiple recipients by sending to each individually
923
+ if (Array.isArray(to)) {
924
+ const results: IntegrationResult[] = [];
925
+ let hasSuccess = false;
926
+
927
+ for (const recipient of to) {
928
+ for (const hub of sortedConfigs) {
929
+ try {
930
+ const serviceType = this.deriveServiceType(
931
+ hub.integration_type,
932
+ hub.integration_provider,
933
+ hub.config_json,
934
+ );
935
+ const strategy = this.integrationFactory.create(
936
+ hub.integration_type,
937
+ serviceType,
938
+ hub.integration_provider,
939
+ );
940
+
941
+ // Process template if provided
942
+ let variables;
943
+ let richText;
944
+ let externalTemplateId: string | undefined = undefined;
945
+ if (templateId) {
946
+ const templateData = await this.processTemplate(
947
+ parseInt(templateId, 10),
948
+ entity_type,
949
+ entity_id,
950
+ );
951
+ variables = templateData.variables;
952
+ externalTemplateId = templateData.externalTemplateId;
953
+ richText = templateData.rich_text;
954
+ subject = templateData.subject;
955
+ }
956
+
957
+ // Merge config with enhanced parameters
958
+ let finalConfig = {
959
+ ...hub.config_json,
960
+ ...enhancedConfig,
961
+ templateId: externalTemplateId,
962
+ variables,
963
+ richText,
964
+ };
965
+
966
+ // Handle user integration if user_id provided
967
+ if (user_id) {
968
+ const userIntegrationData =
969
+ await this.getUserIntegrationForStrategy(user_id, hub.id);
970
+
971
+ if (userIntegrationData) {
972
+ finalConfig = {
973
+ ...finalConfig,
974
+ external_user_id: userIntegrationData.external_user_id,
975
+ };
976
+ }
977
+ }
978
+
979
+ const result = await strategy.sendMessage(
980
+ recipient,
981
+ message,
982
+ finalConfig,
983
+ );
984
+
985
+ if (result.success) {
986
+ this.logger.log(
987
+ `Generic message sent successfully via ${hub.integration_provider} to ${recipient}`,
988
+ );
989
+ results.push(result);
990
+ hasSuccess = true;
991
+ break; // Move to next recipient
992
+ }
993
+
994
+ this.logger.warn(
995
+ `Failed to send via ${hub.integration_provider} to ${recipient}: ${result.error}`,
996
+ );
997
+ } catch (error) {
998
+ this.logger.error(
999
+ `Error sending via ${hub.integration_provider} to ${recipient}:`,
1000
+ error.message,
1001
+ );
1002
+ continue;
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ if (hasSuccess) {
1008
+ return {
1009
+ success: true,
1010
+ messageId: results.map((r) => r.messageId).join(','),
1011
+ provider: 'multiple',
1012
+ service: 'multiple',
1013
+ timestamp: new Date(),
1014
+ message: results.map((r) => r.message).join(','),
1015
+ };
1016
+ }
1017
+ } else {
1018
+ // Handle single recipient
1019
+ for (const hub of sortedConfigs) {
1020
+ try {
1021
+ const serviceType = this.deriveServiceType(
1022
+ hub.integration_type,
1023
+ hub.integration_provider,
1024
+ hub.config_json,
1025
+ );
1026
+ const strategy = this.integrationFactory.create(
1027
+ hub.integration_type,
1028
+ serviceType,
1029
+ hub.integration_provider,
1030
+ );
1031
+
1032
+ // Process template if provided
1033
+ let variables;
1034
+ let externalTemplateId: string | undefined = undefined;
1035
+ let richText;
1036
+ if (templateId) {
1037
+ const templateData = await this.processTemplate(
1038
+ parseInt(templateId, 10),
1039
+ entity_type,
1040
+ entity_id,
1041
+ );
1042
+ variables = templateData.variables;
1043
+ externalTemplateId = templateData.externalTemplateId;
1044
+ richText = templateData.rich_text;
1045
+ subject = templateData.subject;
1046
+ }
1047
+
1048
+ // Merge config with enhanced parameters
1049
+ let finalConfig = {
1050
+ ...hub.config_json,
1051
+ ...enhancedConfig,
1052
+ templateId: externalTemplateId,
1053
+ variables,
1054
+ richText
1055
+ };
1056
+
1057
+ // Handle user integration if user_id provided
1058
+ if (user_id) {
1059
+ const userIntegrationData =
1060
+ await this.getUserIntegrationForStrategy(user_id, hub.id);
1061
+
1062
+ if (userIntegrationData) {
1063
+ finalConfig = {
1064
+ ...finalConfig,
1065
+ external_user_id: userIntegrationData.external_user_id,
1066
+ };
1067
+ }
1068
+ }
1069
+
1070
+ const result = await strategy.sendMessage(
1071
+ to,
1072
+ message,
1073
+ finalConfig,
1074
+ );
1075
+
1076
+ if (result.success) {
1077
+ this.logger.log(
1078
+ `Generic message sent successfully via ${hub.integration_provider} to ${to}`,
1079
+ );
1080
+ return result;
1081
+ }
1082
+
1083
+ this.logger.warn(
1084
+ `Failed to send via ${hub.integration_provider}: ${result.error}`,
1085
+ );
1086
+ } catch (error) {
1087
+ this.logger.error(
1088
+ `Error sending via ${hub.integration_provider}:`,
1089
+ error.message,
1090
+ );
1091
+ continue;
1092
+ }
1093
+ }
1094
+ }
1095
+
1096
+ throw new Error('All communication providers failed');
1097
+ } catch (error) {
1098
+ this.logger.error('Generic communication service error:', error.message);
1099
+ throw error;
1100
+ }
1101
+ }
1102
+
1103
+ async sendBulkMessage(
1104
+ bulkDto: BulkMessageDto,
1105
+ ): Promise<{ results: IntegrationResult[]; summary: any }> {
1106
+ try {
1107
+ const {
1108
+ levelId,
1109
+ levelType,
1110
+ app_code,
1111
+ recipients,
1112
+ message,
1113
+ type,
1114
+ priority = 'low',
1115
+ subject,
1116
+ html,
1117
+ templateId,
1118
+ variables,
1119
+ batchSize = 10,
1120
+ } = bulkDto;
1121
+
1122
+ const results: IntegrationResult[] = [];
1123
+ const batches = this.chunkArray(recipients, batchSize);
1124
+
1125
+ for (let i = 0; i < batches.length; i++) {
1126
+ const batch = batches[i];
1127
+ this.logger.log(
1128
+ `Processing batch ${i + 1}/${batches.length} with ${batch.length} recipients`,
1129
+ );
1130
+
1131
+ const batchPromises = batch.map(async (recipient) => {
1132
+ try {
1133
+ const messageDto: GenericMessageDto = {
1134
+ levelId,
1135
+ levelType,
1136
+ app_code,
1137
+ to: recipient,
1138
+ message,
1139
+ type,
1140
+ priority,
1141
+ subject,
1142
+ html,
1143
+ templateId,
1144
+ variables,
1145
+ };
1146
+
1147
+ return await this.sendGenericMessage(messageDto);
1148
+ } catch (error) {
1149
+ return {
1150
+ success: false,
1151
+ provider: 'unknown',
1152
+ service: 'unknown',
1153
+ error: error.message,
1154
+ timestamp: new Date(),
1155
+ } as IntegrationResult;
1156
+ }
1157
+ });
1158
+
1159
+ const batchResults = await Promise.allSettled(batchPromises);
1160
+ const processedResults = batchResults.map((result) => {
1161
+ if (result.status === 'fulfilled') {
1162
+ return result.value;
1163
+ } else {
1164
+ return {
1165
+ success: false,
1166
+ provider: 'unknown',
1167
+ service: 'unknown',
1168
+ error: result.reason?.message || 'Unknown error',
1169
+ timestamp: new Date(),
1170
+ } as IntegrationResult;
1171
+ }
1172
+ });
1173
+
1174
+ results.push(...processedResults);
1175
+
1176
+ // Rate limiting delay between batches
1177
+ if (i < batches.length - 1) {
1178
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1179
+ }
1180
+ }
1181
+
1182
+ const summary = {
1183
+ total: results.length,
1184
+ successful: results.filter((r) => r.success).length,
1185
+ failed: results.filter((r) => !r.success).length,
1186
+ successRate:
1187
+ (
1188
+ (results.filter((r) => r.success).length / results.length) *
1189
+ 100
1190
+ ).toFixed(2) + '%',
1191
+ };
1192
+
1193
+ this.logger.log(
1194
+ `Bulk message completed: ${summary.successful}/${summary.total} successful`,
1195
+ );
1196
+
1197
+ return { results, summary };
1198
+ } catch (error) {
1199
+ this.logger.error('Bulk communication service error:', error.message);
1200
+ throw error;
1201
+ }
1202
+ }
1203
+
1204
+ async scheduleMessage(
1205
+ scheduledDto: any,
1206
+ ): Promise<{ scheduled: boolean; scheduleId?: string }> {
1207
+ // For now, return a placeholder. In production, integrate with a job queue like Bull or Agenda
1208
+ this.logger.log(`Message scheduled for ${scheduledDto.scheduleFor}`);
1209
+
1210
+ return {
1211
+ scheduled: true,
1212
+ scheduleId: `sched_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
1213
+ };
1214
+ }
1215
+
1216
+ async sendTemplateMessage(templateDto: any): Promise<IntegrationResult> {
1217
+ // Get template content (integrate with your template system)
1218
+ const template = await this.getTemplate(templateDto.templateId);
1219
+
1220
+ const processedMessage = this.replaceTemplateVariables(
1221
+ template.content,
1222
+ templateDto.variables,
1223
+ );
1224
+ const processedSubject = template.subject
1225
+ ? this.replaceTemplateVariables(template.subject, templateDto.variables)
1226
+ : undefined;
1227
+
1228
+ const messageDto: GenericMessageDto = {
1229
+ levelId: templateDto.levelId,
1230
+ levelType: templateDto.levelType,
1231
+ app_code: templateDto.app_code,
1232
+ to: templateDto.to,
1233
+ message: processedMessage,
1234
+ subject: processedSubject,
1235
+ type: templateDto.type,
1236
+ templateId: templateDto.templateId,
1237
+ variables: templateDto.variables,
1238
+ };
1239
+
1240
+ return this.sendGenericMessage(messageDto);
1241
+ }
1242
+
1243
+ private detectCommunicationType(
1244
+ to: string | string[],
1245
+ type?: string,
1246
+ ): 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE' {
1247
+ if (type) {
1248
+ return type as 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
1249
+ }
1250
+
1251
+ const recipient = Array.isArray(to) ? to[0] : to;
1252
+
1253
+ // Email detection
1254
+ if (recipient.includes('@')) {
1255
+ return 'EMAIL';
1256
+ }
1257
+
1258
+ // Phone number detection (basic)
1259
+ if (/^\+?[\d\s\-\(\)]+$/.test(recipient)) {
1260
+ // Could be SMS or WhatsApp, default to SMS
1261
+ return 'SMS';
1262
+ }
1263
+
1264
+ // Default to EMAIL if unsure
1265
+ return 'EMAIL';
1266
+ }
1267
+
1268
+ private sortConfigsByPriorityAndDefault(
1269
+ configs: IntegrationConfigWithConfig[],
1270
+ _priority: string,
1271
+ ): IntegrationConfigWithConfig[] {
1272
+ return configs.sort((a, b) => {
1273
+ // First sort by default (true comes first)
1274
+ if (a.is_default !== b.is_default) {
1275
+ return b.is_default ? 1 : -1;
1276
+ }
1277
+
1278
+ // Then sort by priority (lower number = higher priority)
1279
+ if (a.priority !== b.priority) {
1280
+ return a.priority - b.priority;
1281
+ }
1282
+
1283
+ // Finally sort by created_at descending (newest first)
1284
+ return (
1285
+ new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
1286
+ );
1287
+ });
1288
+ }
1289
+
1290
+ private async processTemplate(
1291
+ templateId: number,
1292
+ entity_type: any,
1293
+ entity_id: any,
1294
+ ): Promise<{ variables?: Record<string, any>; externalTemplateId?: string; rich_text?: string; subject?: string }> {
1295
+ const commTemplate: any = await this.entityService.getEntityData(COMM_TEMPLATE, templateId, {} as any);
1296
+ if (!commTemplate) {
1297
+ return {
1298
+ variables: {},
1299
+ externalTemplateId: undefined,
1300
+ };
1301
+ }
1302
+
1303
+ let variables = {};
1304
+ if (commTemplate.mapper_id) {
1305
+ variables = await this.fieldMapperService.resolveData(
1306
+ commTemplate.mapper_id,
1307
+ "LOOKUP",
1308
+ entity_type,
1309
+ entity_id,
1310
+ {} as any,
1311
+ );
1312
+ }
1313
+
1314
+ if (!commTemplate.template_id) {
1315
+ let richText = commTemplate.rich_text;
1316
+
1317
+ richText = richText.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1318
+ const value = variables[key];
1319
+ return value !== undefined ? String(value) : match;
1320
+ });
1321
+
1322
+ return {
1323
+ rich_text: richText,
1324
+ subject: commTemplate.subject
1325
+ };
1326
+ }
1327
+
1328
+ return {
1329
+ variables,
1330
+ externalTemplateId: commTemplate.template_id,
1331
+ };
1332
+ }
1333
+
1334
+ private replaceTemplateVariables(
1335
+ template: string,
1336
+ variables: Record<string, any>,
1337
+ ): string {
1338
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1339
+ const value = variables[key];
1340
+ return value !== undefined ? String(value) : match;
1341
+ });
1342
+ }
1343
+
1344
+ private async getTemplate(templateId: string) {
1345
+ // Placeholder for template system integration
1346
+ // In production, this would connect to your template database/service
1347
+ return {
1348
+ id: templateId,
1349
+ subject: 'Default Subject {{variable}}',
1350
+ content: 'Hello {{name}}, this is a template message with {{variable}}.',
1351
+ };
1352
+ }
1353
+
1354
+ private chunkArray<T>(array: T[], chunkSize: number): T[][] {
1355
+ const chunks: T[][] = [];
1356
+ for (let i = 0; i < array.length; i += chunkSize) {
1357
+ chunks.push(array.slice(i, i + chunkSize));
1358
+ }
1359
+ return chunks;
1360
+ }
1361
+
1362
+ async initGmailOAuth(
1363
+ levelId: number,
1364
+ levelType: string,
1365
+ app_code: string,
1366
+ email?: string,
1367
+ ): Promise<{ authUrl: string; state: string }> {
1368
+ try {
1369
+ // Get system OAuth credentials from config
1370
+ const clientId = this.configService.get<string>('CLIENT_ID');
1371
+ const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1372
+
1373
+ if (!clientId || !clientSecret) {
1374
+ throw new Error('Gmail OAuth credentials not configured');
1375
+ }
1376
+
1377
+ const state = this.generateSecureState();
1378
+ // Use the existing registered callback URL
1379
+ const callbackUrl =
1380
+ this.configService.get<string>('CALLBACK_URL') ||
1381
+ 'http://localhost:5001/auth/google/callback';
1382
+
1383
+ this.gmailOAuthStates.set(state, {
1384
+ levelId,
1385
+ levelType,
1386
+ app_code,
1387
+ email,
1388
+ timestamp: Date.now(),
1389
+ });
1390
+
1391
+ // Auto-cleanup after 10 minutes
1392
+ setTimeout(
1393
+ () => {
1394
+ this.gmailOAuthStates.delete(state);
1395
+ },
1396
+ 10 * 60 * 1000,
1397
+ );
1398
+
1399
+ const oauth2Client = new google.auth.OAuth2(
1400
+ clientId,
1401
+ clientSecret,
1402
+ callbackUrl,
1403
+ );
1404
+
1405
+ const scopes = [
1406
+ 'https://www.googleapis.com/auth/gmail.send',
1407
+ 'https://www.googleapis.com/auth/gmail.readonly',
1408
+ 'https://www.googleapis.com/auth/userinfo.email',
1409
+ 'https://www.googleapis.com/auth/calendar',
1410
+ ];
1411
+
1412
+ const authUrl = oauth2Client.generateAuthUrl({
1413
+ access_type: 'offline',
1414
+ scope: scopes,
1415
+ state: `gmail_config:${state}`, // Prefix to identify Gmail config requests
1416
+ prompt: 'consent',
1417
+ login_hint: email,
1418
+ });
1419
+
1420
+ return { authUrl, state };
1421
+ } catch (error) {
1422
+ this.logger.error('Error initializing Gmail OAuth:', error.message);
1423
+ throw new Error('Failed to initialize Gmail OAuth');
1424
+ }
1425
+ }
1426
+
1427
+ async handleGmailOAuthCallback(
1428
+ code: string,
1429
+ state: string,
1430
+ ): Promise<GmailSSOResult> {
1431
+ try {
1432
+ const oauthState = this.gmailOAuthStates.get(state);
1433
+ if (!oauthState) {
1434
+ throw new Error('Invalid or expired OAuth state');
1435
+ }
1436
+
1437
+ this.gmailOAuthStates.delete(state);
1438
+
1439
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1440
+ throw new Error('OAuth state expired');
1441
+ }
1442
+
1443
+ // Get system OAuth credentials
1444
+ const clientId = this.configService.get<string>('CLIENT_ID');
1445
+ const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1446
+ const callbackUrl =
1447
+ this.configService.get<string>('CALLBACK_URL') ||
1448
+ 'http://localhost:5001/auth/google/callback';
1449
+
1450
+ const oauth2Client = new google.auth.OAuth2(
1451
+ clientId,
1452
+ clientSecret,
1453
+ callbackUrl,
1454
+ );
1455
+
1456
+ const { tokens } = await oauth2Client.getToken(code);
1457
+
1458
+ if (!tokens.access_token) {
1459
+ throw new Error('Failed to obtain access token');
1460
+ }
1461
+
1462
+ // Get user email from Google
1463
+ oauth2Client.setCredentials(tokens);
1464
+ const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client });
1465
+ const userInfo = await oauth2.userinfo.get();
1466
+ const email = userInfo.data.email;
1467
+
1468
+ if (!email) {
1469
+ throw new Error('Failed to get user email');
1470
+ }
1471
+
1472
+ // Verify email matches if hint was provided
1473
+ if (oauthState.email && oauthState.email !== email) {
1474
+ throw new Error('Email mismatch with OAuth hint');
1475
+ }
1476
+
1477
+ const gmailConfig = {
1478
+ clientId,
1479
+ clientSecret,
1480
+ email: email,
1481
+ accessToken: tokens.access_token,
1482
+ refreshToken: tokens.refresh_token,
1483
+ scope: tokens.scope,
1484
+ tokenType: tokens.token_type,
1485
+ expiryDate: tokens.expiry_date,
1486
+ };
1487
+
1488
+ // Validate that no active EMAIL configuration exists
1489
+ await this.validateUniqueActiveConfig(
1490
+ oauthState.levelId,
1491
+ oauthState.levelType,
1492
+ oauthState.app_code,
1493
+ 'EMAIL',
1494
+ 'gmail',
1495
+ );
1496
+
1497
+ // Create integration config
1498
+ const config = this.configRepository.create({
1499
+ app_code: oauthState.app_code,
1500
+ integration_type: 'EMAIL',
1501
+ integration_provider: 'gmail',
1502
+ integration_source_id: 1, // Gmail source ID
1503
+ level_id: oauthState.levelId,
1504
+ level_type: oauthState.levelType,
1505
+ status: 1,
1506
+ priority: 1,
1507
+ is_default: false,
1508
+ config_json: gmailConfig as any,
1509
+ });
1510
+
1511
+ const savedConfig = await this.configRepository.save(config);
1512
+
1513
+ this.logger.log(
1514
+ `Gmail OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1515
+ );
1516
+
1517
+ return {
1518
+ hubId: savedConfig.id,
1519
+ configId: savedConfig.id,
1520
+ };
1521
+ } catch (error) {
1522
+ this.logger.error('Error handling Gmail OAuth callback:', error.message);
1523
+ throw new Error(`Failed to complete Gmail OAuth: ${error.message}`);
1524
+ }
1525
+ }
1526
+
1527
+ async handleGmailTokensCallback(
1528
+ email: string,
1529
+ accessToken: string,
1530
+ refreshToken: string,
1531
+ state: string,
1532
+ ): Promise<GmailSSOResult> {
1533
+ try {
1534
+ const oauthState = this.gmailOAuthStates.get(state);
1535
+ if (!oauthState) {
1536
+ throw new Error('Invalid or expired OAuth state');
1537
+ }
1538
+
1539
+ this.gmailOAuthStates.delete(state);
1540
+
1541
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1542
+ throw new Error('OAuth state expired');
1543
+ }
1544
+
1545
+ // Verify email matches if hint was provided
1546
+ if (oauthState.email && oauthState.email !== email) {
1547
+ throw new Error('Email mismatch with OAuth hint');
1548
+ }
1549
+
1550
+ // Validate that no active EMAIL configuration exists
1551
+ await this.validateUniqueActiveConfig(
1552
+ oauthState.levelId,
1553
+ oauthState.levelType,
1554
+ oauthState.app_code,
1555
+ 'EMAIL',
1556
+ 'gmail',
1557
+ );
1558
+
1559
+ // Pure SSO configuration - no client credentials stored per user
1560
+ const gmailConfig = {
1561
+ email: email,
1562
+ accessToken: accessToken,
1563
+ refreshToken: refreshToken,
1564
+ authMethod: 'GOOGLE_SSO',
1565
+ scopes: [
1566
+ 'https://www.googleapis.com/auth/gmail.send',
1567
+ 'https://www.googleapis.com/auth/userinfo.email',
1568
+ ],
1569
+ };
1570
+
1571
+ // Create integration config
1572
+ const config = this.configRepository.create({
1573
+ app_code: oauthState.app_code,
1574
+ integration_type: 'EMAIL',
1575
+ integration_provider: 'gmail',
1576
+ integration_source_id: 1, // Gmail source ID
1577
+ level_id: oauthState.levelId,
1578
+ level_type: oauthState.levelType,
1579
+ status: 1,
1580
+ priority: 1,
1581
+ is_default: false,
1582
+ config_json: gmailConfig as any,
1583
+ });
1584
+
1585
+ const savedConfig = await this.configRepository.save(config);
1586
+
1587
+ this.logger.log(
1588
+ `Gmail tokens configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1589
+ );
1590
+
1591
+ return {
1592
+ hubId: savedConfig.id,
1593
+ configId: savedConfig.id,
1594
+ };
1595
+ } catch (error) {
1596
+ this.logger.error('Error handling Gmail tokens callback:', error.message);
1597
+ throw new Error(
1598
+ `Failed to complete Gmail tokens callback: ${error.message}`,
1599
+ );
1600
+ }
1601
+ }
1602
+
1603
+ async testGmailConfig(
1604
+ hubId: number,
1605
+ ): Promise<{ success: boolean; error?: string }> {
1606
+ try {
1607
+ const integrationConfig = await this.configRepository.findOne({
1608
+ where: { id: hubId },
1609
+ });
1610
+
1611
+ if (!integrationConfig) {
1612
+ throw new Error('Integration config not found');
1613
+ }
1614
+
1615
+ const isValid = await this.gmailApiStrategy.validateConnection(
1616
+ integrationConfig.config_json,
1617
+ );
1618
+
1619
+ if (!isValid) {
1620
+ return {
1621
+ success: false,
1622
+ error: 'Gmail configuration is invalid or expired',
1623
+ };
1624
+ }
1625
+
1626
+ return { success: true };
1627
+ } catch (error) {
1628
+ this.logger.error('Error testing Gmail config:', error.message);
1629
+ return { success: false, error: error.message };
1630
+ }
1631
+ }
1632
+
1633
+ private generateSecureState(): string {
1634
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
1635
+ }
1636
+
1637
+ private async validateUniqueActiveConfig(
1638
+ levelId: number,
1639
+ levelType: string,
1640
+ app_code: string,
1641
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1642
+ provider: string,
1643
+ excludeHubId?: number,
1644
+ ): Promise<void> {
1645
+ // Find all active configurations of the same provider for this level and app_code
1646
+ const query = this.configRepository
1647
+ .createQueryBuilder('hub')
1648
+ .where('hub.level_id = :levelId', { levelId })
1649
+ .andWhere('hub.level_type = :levelType', { levelType })
1650
+ .andWhere('hub.app_code = :app_code', { app_code })
1651
+ .andWhere('hub.integration_type = :configType', { configType })
1652
+ .andWhere('hub.integration_provider = :provider', { provider })
1653
+ .andWhere('hub.status = :status', { status: 1 });
1654
+
1655
+ // Exclude current hub if updating
1656
+ if (excludeHubId) {
1657
+ query.andWhere('hub.id != :excludeHubId', { excludeHubId });
1658
+ }
1659
+
1660
+ const existingActiveConfigs = await query.getMany();
1661
+
1662
+ // If there are existing active configurations of the same provider, throw error
1663
+ if (existingActiveConfigs.length > 0) {
1664
+ throw new Error(
1665
+ `A ${provider} configuration already exists for ${configType} in app_code ${app_code}, ${levelType} ${levelId}. Only one configuration per provider is allowed.`,
1666
+ );
1667
+ }
1668
+ }
1669
+
1670
+ private requiresOAuthFlow(
1671
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1672
+ provider: string,
1673
+ config: any,
1674
+ ): boolean {
1675
+ // Check if config indicates OAuth is needed (missing tokens or explicit OAuth request)
1676
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1677
+
1678
+ switch (key) {
1679
+ case 'email_gmail':
1680
+ // Requires OAuth if no access token provided or OAuth explicitly requested
1681
+ return !config.accessToken || config.useOAuth === true;
1682
+
1683
+ case 'email_outlook':
1684
+ // Requires OAuth if no access token provided or OAuth explicitly requested
1685
+ return !config.accessToken || config.useOAuth === true;
1686
+
1687
+ default:
1688
+ // Most other providers don't require OAuth
1689
+ return false;
1690
+ }
1691
+ }
1692
+
1693
+ private async generateOAuthUrl(
1694
+ levelId: number,
1695
+ levelType: string,
1696
+ app_code: string,
1697
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1698
+ provider: string,
1699
+ integration_source_id: number,
1700
+ config: any,
1701
+ priority?: number,
1702
+ is_default?: boolean,
1703
+ ): Promise<{ authUrl: string; state: string; message: string }> {
1704
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1705
+
1706
+ switch (key) {
1707
+ case 'email_gmail':
1708
+ const gmailResult = await this.initGmailOAuth(
1709
+ levelId,
1710
+ levelType,
1711
+ app_code,
1712
+ config.email,
1713
+ );
1714
+ return {
1715
+ authUrl: gmailResult.authUrl,
1716
+ state: gmailResult.state,
1717
+ message:
1718
+ 'Please complete Gmail OAuth authorization. Configuration will be created automatically after authorization.',
1719
+ };
1720
+
1721
+ case 'email_outlook':
1722
+ const outlookResult = await this.initOutlookOAuth(
1723
+ levelId,
1724
+ levelType,
1725
+ app_code,
1726
+ config.email,
1727
+ );
1728
+ return {
1729
+ authUrl: outlookResult.authUrl,
1730
+ state: outlookResult.state,
1731
+ message:
1732
+ 'Please complete Outlook OAuth authorization. Configuration will be created automatically after authorization.',
1733
+ };
1734
+
1735
+ default:
1736
+ throw new Error(`OAuth not supported for ${configType}/${provider}`);
1737
+ }
1738
+ }
1739
+
1740
+ private async createDirectConfig(
1741
+ levelId: number,
1742
+ levelType: string,
1743
+ app_code: string,
1744
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1745
+ provider: string,
1746
+ integration_source_id: number,
1747
+ config: any,
1748
+ priority?: number,
1749
+ is_default?: boolean,
1750
+ ): Promise<IntegrationConfig> {
1751
+ // Validate that no duplicate provider configurations exist
1752
+ await this.validateUniqueActiveConfig(
1753
+ levelId,
1754
+ levelType,
1755
+ app_code,
1756
+ configType,
1757
+ provider,
1758
+ );
1759
+
1760
+ // Deactivate all other configurations of the same integration type
1761
+ await this.configRepository.update(
1762
+ {
1763
+ level_id: levelId,
1764
+ level_type: levelType,
1765
+ app_code: app_code,
1766
+ integration_type: configType,
1767
+ status: 1,
1768
+ },
1769
+ { status: 0 },
1770
+ );
1771
+
1772
+ // If setting as default, remove default from other configurations of same type and app_code
1773
+ if (is_default) {
1774
+ await this.configRepository.update(
1775
+ {
1776
+ level_id: levelId,
1777
+ level_type: levelType,
1778
+ app_code: app_code,
1779
+ integration_type: configType,
1780
+ },
1781
+ { is_default: false },
1782
+ );
1783
+ }
1784
+
1785
+ // Create integration config
1786
+ const integrationConfig = this.configRepository.create({
1787
+ app_code: app_code,
1788
+ integration_type: configType,
1789
+ integration_provider: provider,
1790
+ integration_source_id: integration_source_id,
1791
+ level_id: levelId,
1792
+ level_type: levelType,
1793
+ status: 1,
1794
+ priority: priority || 1,
1795
+ is_default: is_default || false,
1796
+ config_json: config,
1797
+ });
1798
+
1799
+ const savedConfig = await this.configRepository.save(integrationConfig);
1800
+ this.logger.log(
1801
+ `Communication config created: ${configType}/${provider} for ${levelType} ${levelId}`,
1802
+ );
1803
+
1804
+ // Store DID mapping for TELEPHONE integration
1805
+ if (configType === 'TELEPHONE') {
1806
+ try {
1807
+ // Extract DID from config (could be did, callerNumber, or fromNumber)
1808
+ const did = config.did || config.callerNumber || config.fromNumber;
1809
+
1810
+ if (did) {
1811
+ const entityMapper = this.entityMapperRepository.create({
1812
+ integration_config_id: savedConfig.id,
1813
+ level_id: String(levelId),
1814
+ level_type: levelType,
1815
+ appcode: app_code,
1816
+ did: did,
1817
+ campaign_name: config.campaignName || null,
1818
+ });
1819
+
1820
+ await this.entityMapperRepository.save(entityMapper);
1821
+ this.logger.log(
1822
+ `DID mapping created for TELEPHONE integration: ${did} for ${levelType} ${levelId}`,
1823
+ );
1824
+ }
1825
+ } catch (error) {
1826
+ this.logger.warn(
1827
+ `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
1828
+ );
1829
+ }
1830
+ }
1831
+
1832
+ return Array.isArray(savedConfig) ? savedConfig[0] : savedConfig;
1833
+ }
1834
+
1835
+ async initOutlookOAuth(
1836
+ levelId: number,
1837
+ levelType: string,
1838
+ app_code: string,
1839
+ email?: string,
1840
+ ): Promise<{ authUrl: string; state: string }> {
1841
+ try {
1842
+ // Get system OAuth credentials from config
1843
+ const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1844
+ const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1845
+
1846
+ if (!clientId || !tenantId) {
1847
+ throw new Error('Outlook OAuth credentials not configured');
1848
+ }
1849
+
1850
+ const state = this.generateSecureState();
1851
+ const callbackUrl =
1852
+ this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1853
+ 'http://localhost:5001/auth/outlook/callback';
1854
+
1855
+ this.gmailOAuthStates.set(state, {
1856
+ levelId,
1857
+ levelType,
1858
+ app_code,
1859
+ email,
1860
+ timestamp: Date.now(),
1861
+ });
1862
+
1863
+ // Auto-cleanup after 10 minutes
1864
+ setTimeout(
1865
+ () => {
1866
+ this.gmailOAuthStates.delete(state);
1867
+ },
1868
+ 10 * 60 * 1000,
1869
+ );
1870
+
1871
+ const scopes = [
1872
+ 'https://graph.microsoft.com/Mail.Send',
1873
+ 'https://graph.microsoft.com/User.Read',
1874
+ ];
1875
+
1876
+ const authUrl =
1877
+ `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
1878
+ `client_id=${clientId}&` +
1879
+ `response_type=code&` +
1880
+ `redirect_uri=${encodeURIComponent(callbackUrl)}&` +
1881
+ `scope=${encodeURIComponent(scopes.join(' '))}&` +
1882
+ `state=outlook_config:${state}&` +
1883
+ `response_mode=query&` +
1884
+ `prompt=consent` +
1885
+ (email ? `&login_hint=${encodeURIComponent(email)}` : '');
1886
+
1887
+ return { authUrl, state };
1888
+ } catch (error) {
1889
+ this.logger.error('Error initializing Outlook OAuth:', error.message);
1890
+ throw new Error('Failed to initialize Outlook OAuth');
1891
+ }
1892
+ }
1893
+
1894
+ async handleOutlookOAuthCallback(
1895
+ code: string,
1896
+ state: string,
1897
+ ): Promise<GmailSSOResult> {
1898
+ try {
1899
+ const oauthState = this.gmailOAuthStates.get(state);
1900
+ if (!oauthState) {
1901
+ throw new Error('Invalid or expired OAuth state');
1902
+ }
1903
+
1904
+ this.gmailOAuthStates.delete(state);
1905
+
1906
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1907
+ throw new Error('OAuth state expired');
1908
+ }
1909
+
1910
+ const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1911
+ const clientSecret = this.configService.get<string>(
1912
+ 'OUTLOOK_CLIENT_SECRET',
1913
+ );
1914
+ const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1915
+ const callbackUrl =
1916
+ this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1917
+ 'http://localhost:5001/auth/outlook/callback';
1918
+
1919
+ // Exchange code for tokens
1920
+ const tokenResponse = await fetch(
1921
+ `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
1922
+ {
1923
+ method: 'POST',
1924
+ headers: {
1925
+ 'Content-Type': 'application/x-www-form-urlencoded',
1926
+ },
1927
+ body: new URLSearchParams({
1928
+ client_id: clientId!,
1929
+ client_secret: clientSecret!,
1930
+ code: code,
1931
+ redirect_uri: callbackUrl,
1932
+ grant_type: 'authorization_code',
1933
+ }),
1934
+ },
1935
+ );
1936
+
1937
+ const tokens = await tokenResponse.json();
1938
+
1939
+ if (!tokens.access_token) {
1940
+ throw new Error('Failed to obtain access token');
1941
+ }
1942
+
1943
+ // Get user info from Microsoft Graph
1944
+ const userResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
1945
+ headers: {
1946
+ Authorization: `Bearer ${tokens.access_token}`,
1947
+ },
1948
+ });
1949
+
1950
+ const userInfo = await userResponse.json();
1951
+ const email = userInfo.mail || userInfo.userPrincipalName;
1952
+
1953
+ if (!email) {
1954
+ throw new Error('Failed to get user email');
1955
+ }
1956
+
1957
+ // Validate that no active EMAIL configuration exists
1958
+ await this.validateUniqueActiveConfig(
1959
+ oauthState.levelId,
1960
+ oauthState.levelType,
1961
+ oauthState.app_code,
1962
+ 'EMAIL',
1963
+ 'outlook',
1964
+ );
1965
+
1966
+ const outlookConfig = {
1967
+ clientId,
1968
+ tenantId,
1969
+ email: email,
1970
+ accessToken: tokens.access_token,
1971
+ refreshToken: tokens.refresh_token,
1972
+ scope: tokens.scope,
1973
+ tokenType: tokens.token_type,
1974
+ expiresIn: tokens.expires_in,
1975
+ };
1976
+
1977
+ // Create integration config
1978
+ const config = this.configRepository.create({
1979
+ app_code: oauthState.app_code,
1980
+ integration_type: 'EMAIL',
1981
+ integration_provider: 'outlook',
1982
+ integration_source_id: 1, // Outlook source ID
1983
+ level_id: oauthState.levelId,
1984
+ level_type: oauthState.levelType,
1985
+ status: 1,
1986
+ priority: 1,
1987
+ is_default: false,
1988
+ config_json: outlookConfig as any,
1989
+ });
1990
+
1991
+ const savedConfig = await this.configRepository.save(config);
1992
+
1993
+ this.logger.log(
1994
+ `Outlook OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1995
+ );
1996
+
1997
+ return {
1998
+ hubId: savedConfig.id,
1999
+ configId: savedConfig.id,
2000
+ };
2001
+ } catch (error) {
2002
+ this.logger.error(
2003
+ 'Error handling Outlook OAuth callback:',
2004
+ error.message,
2005
+ );
2006
+ throw new Error(`Failed to complete Outlook OAuth: ${error.message}`);
2007
+ }
2008
+ }
2009
+
2010
+ async getIntegrationConfigById(hubId: number): Promise<
2011
+ | (IntegrationConfig & {
2012
+ config: IntegrationConfig;
2013
+ linkedSource?: string;
2014
+ configDetails?: any;
2015
+ })
2016
+ | null
2017
+ > {
2018
+ try {
2019
+ // Find the integration config by ID
2020
+ const integrationConfig = await this.configRepository.findOne({
2021
+ where: { id: hubId },
2022
+ });
2023
+
2024
+ if (!integrationConfig) {
2025
+ return null;
2026
+ }
2027
+
2028
+ // Extract linked source and config details
2029
+ const linkedSource = this.extractLinkedSource(
2030
+ integrationConfig.integration_type,
2031
+ integrationConfig.integration_provider,
2032
+ integrationConfig.config_json,
2033
+ );
2034
+
2035
+ const configDetails = this.extractConfigDetails(
2036
+ integrationConfig.integration_type,
2037
+ integrationConfig.integration_provider,
2038
+ integrationConfig.config_json,
2039
+ );
2040
+
2041
+ return {
2042
+ ...integrationConfig,
2043
+ config: integrationConfig,
2044
+ linkedSource,
2045
+ configDetails,
2046
+ };
2047
+ } catch (error) {
2048
+ this.logger.error(
2049
+ `Error fetching communication config by ID ${hubId}:`,
2050
+ error.message,
2051
+ );
2052
+ throw new Error(
2053
+ `Failed to fetch communication configuration: ${error.message}`,
2054
+ );
2055
+ }
2056
+ }
2057
+
2058
+ async getIntegrationTemplates(
2059
+ levelId: number,
2060
+ levelType: string,
2061
+ app_code: string,
2062
+ integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
2063
+ ): Promise<{
2064
+ success: boolean;
2065
+ data?: Array<{
2066
+ label: string;
2067
+ value: string;
2068
+ }>;
2069
+ error?: string;
2070
+ }> {
2071
+ try {
2072
+ // Get active configuration for the integration type
2073
+ const config = await this.getSingleActiveConfig(
2074
+ levelId,
2075
+ levelType,
2076
+ app_code,
2077
+ integration_type,
2078
+ );
2079
+
2080
+ if (!config) {
2081
+ return {
2082
+ success: false,
2083
+ error: `No active ${integration_type} configuration found for this level`,
2084
+ };
2085
+ }
2086
+
2087
+ // Create strategy instance
2088
+ const strategy = this.integrationFactory.create(
2089
+ config.integration_type,
2090
+ 'API',
2091
+ config.integration_provider,
2092
+ );
2093
+
2094
+ // Check if strategy supports getTemplates
2095
+ if (typeof (strategy as any).getTemplates !== 'function') {
2096
+ return {
2097
+ success: false,
2098
+ error: `Template retrieval not supported for provider: ${config.integration_provider}`,
2099
+ };
2100
+ }
2101
+
2102
+ // Call getTemplates method
2103
+ return await (strategy as any).getTemplates(config.config_json);
2104
+ } catch (error) {
2105
+ this.logger.error(
2106
+ `Error fetching templates for ${integration_type} level ${levelId}/${levelType}:`,
2107
+ error.message,
2108
+ );
2109
+ return {
2110
+ success: false,
2111
+ error: `Failed to fetch templates: ${error.message}`,
2112
+ };
2113
+ }
2114
+ }
2115
+
2116
+ async getSendGridTemplates(
2117
+ levelId: number,
2118
+ levelType: string,
2119
+ app_code: string,
2120
+ ): Promise<{
2121
+ success: boolean;
2122
+ data?: Array<{
2123
+ label: string;
2124
+ value: string;
2125
+ }>;
2126
+ error?: string;
2127
+ }> {
2128
+ try {
2129
+ // Find active SendGrid configurations for this level
2130
+ const hubs = await this.getActiveConfigs(
2131
+ levelId,
2132
+ levelType,
2133
+ app_code,
2134
+ 'EMAIL',
2135
+ );
2136
+
2137
+ // Look for SendGrid provider
2138
+ const sendGridHub = hubs.find(
2139
+ (hub) => hub.integration_provider === 'sendgrid',
2140
+ );
2141
+
2142
+ if (!sendGridHub) {
2143
+ return {
2144
+ success: false,
2145
+ error: 'No active SendGrid configuration found for this level',
2146
+ };
2147
+ }
2148
+
2149
+ // Extract API key from configuration
2150
+ const apiKey = sendGridHub.config_json?.apiKey;
2151
+
2152
+ if (!apiKey) {
2153
+ return {
2154
+ success: false,
2155
+ error: 'SendGrid API key not found in configuration',
2156
+ };
2157
+ }
2158
+
2159
+ // Use the SendGrid strategy to fetch templates
2160
+ return this.sendGridApiStrategy.getTemplates(apiKey);
2161
+ } catch (error) {
2162
+ this.logger.error(
2163
+ `Error fetching SendGrid templates for level ${levelId}/${levelType}:`,
2164
+ error.message,
2165
+ );
2166
+ return {
2167
+ success: false,
2168
+ error: `Failed to fetch SendGrid templates: ${error.message}`,
2169
+ };
2170
+ }
2171
+ }
2172
+
2173
+ async getSendGridVerifiedSenders(apiKey: string): Promise<{
2174
+ success: boolean;
2175
+ data?: Array<{
2176
+ label: string;
2177
+ value: string;
2178
+ }>;
2179
+ error?: string;
2180
+ }> {
2181
+ try {
2182
+ if (!apiKey) {
2183
+ return {
2184
+ success: false,
2185
+ error: 'SendGrid API key not found in configuration',
2186
+ };
2187
+ }
2188
+
2189
+ // Use the SendGrid strategy to fetch verified senders
2190
+ return this.sendGridApiStrategy.getVerifiedSenders(apiKey);
2191
+ } catch (error) {
2192
+ this.logger.error(
2193
+ `Error fetching SendGrid verified senders`,
2194
+ error.message,
2195
+ );
2196
+ return {
2197
+ success: false,
2198
+ error: `Failed to fetch SendGrid verified senders: ${error.message}`,
2199
+ };
2200
+ }
2201
+ }
2202
+
2203
+ // UserIntegration Management Methods
2204
+
2205
+ async createUserIntegration(
2206
+ createDto: CreateUserIntegrationDto,
2207
+ ): Promise<UserIntegration> {
2208
+ try {
2209
+ // Check if mapping already exists
2210
+ const existing = await this.userIntegrationRepository.findOne({
2211
+ where: {
2212
+ user_id: createDto.user_id,
2213
+ integration_config_id: createDto.integration_config_id,
2214
+ },
2215
+ });
2216
+
2217
+ if (existing) {
2218
+ throw new Error('User integration mapping already exists');
2219
+ }
2220
+
2221
+ // Verify integration config exists
2222
+ const config = await this.configRepository.findOne({
2223
+ where: { id: createDto.integration_config_id },
2224
+ });
2225
+
2226
+ if (!config) {
2227
+ throw new Error('Integration configuration not found');
2228
+ }
2229
+
2230
+ const userIntegration = this.userIntegrationRepository.create(createDto);
2231
+ return await this.userIntegrationRepository.save(userIntegration);
2232
+ } catch (error) {
2233
+ this.logger.error(
2234
+ `Error creating user integration mapping: ${error.message}`,
2235
+ );
2236
+ throw error;
2237
+ }
2238
+ }
2239
+
2240
+ async bulkCreateUserIntegration(
2241
+ bulkDto: BulkCreateUserIntegrationDto,
2242
+ ): Promise<{
2243
+ created: UserIntegration[];
2244
+ updated: UserIntegration[];
2245
+ failed: Array<{ data: CreateUserIntegrationDto; error: string }>;
2246
+ summary: {
2247
+ total: number;
2248
+ created: number;
2249
+ updated: number;
2250
+ failed: number;
2251
+ };
2252
+ }> {
2253
+ const created: UserIntegration[] = [];
2254
+ const updated: UserIntegration[] = [];
2255
+ const failed: Array<{ data: CreateUserIntegrationDto; error: string }> = [];
2256
+
2257
+ try {
2258
+ for (const createDto of bulkDto.user_integrations) {
2259
+ try {
2260
+ // Check if mapping already exists
2261
+ const existing = await this.userIntegrationRepository.findOne({
2262
+ where: {
2263
+ user_id: createDto.user_id,
2264
+ integration_config_id: createDto.integration_config_id,
2265
+ },
2266
+ });
2267
+
2268
+ if (existing) {
2269
+ // Update existing mapping
2270
+ if (createDto.external_user_id !== undefined) {
2271
+ existing.external_user_id = createDto.external_user_id;
2272
+ }
2273
+ if (createDto.external_user_data !== undefined) {
2274
+ existing.external_user_data = createDto.external_user_data;
2275
+ }
2276
+ if (createDto.is_active !== undefined) {
2277
+ existing.is_active = createDto.is_active;
2278
+ }
2279
+
2280
+ const updatedIntegration =
2281
+ await this.userIntegrationRepository.save(existing);
2282
+ updated.push(updatedIntegration);
2283
+
2284
+ this.logger.log(
2285
+ `Updated user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2286
+ );
2287
+ } else {
2288
+ // Verify integration config exists
2289
+ const config = await this.configRepository.findOne({
2290
+ where: { id: createDto.integration_config_id },
2291
+ });
2292
+
2293
+ if (!config) {
2294
+ failed.push({
2295
+ data: createDto,
2296
+ error: 'Integration configuration not found',
2297
+ });
2298
+ continue;
2299
+ }
2300
+
2301
+ // Create new mapping
2302
+ const userIntegration =
2303
+ this.userIntegrationRepository.create(createDto);
2304
+ const savedIntegration =
2305
+ await this.userIntegrationRepository.save(userIntegration);
2306
+ created.push(savedIntegration);
2307
+
2308
+ this.logger.log(
2309
+ `Created user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2310
+ );
2311
+ }
2312
+ } catch (error) {
2313
+ failed.push({
2314
+ data: createDto,
2315
+ error: error.message || 'Unknown error',
2316
+ });
2317
+ this.logger.error(
2318
+ `Error processing user integration for user ${createDto.user_id}: ${error.message}`,
2319
+ );
2320
+ }
2321
+ }
2322
+
2323
+ const summary = {
2324
+ total: bulkDto.user_integrations.length,
2325
+ created: created.length,
2326
+ updated: updated.length,
2327
+ failed: failed.length,
2328
+ };
2329
+
2330
+ this.logger.log(
2331
+ `Bulk user integration completed: ${summary.created} created, ${summary.updated} updated, ${summary.failed} failed`,
2332
+ );
2333
+
2334
+ return { created, updated, failed, summary };
2335
+ } catch (error) {
2336
+ this.logger.error(
2337
+ `Error in bulk user integration creation: ${error.message}`,
2338
+ );
2339
+ throw error;
2340
+ }
2341
+ }
2342
+
2343
+ async getUserIntegrations(userId: number): Promise<UserIntegration[]> {
2344
+ try {
2345
+ return await this.userIntegrationRepository.find({
2346
+ where: { user_id: userId, is_active: true },
2347
+ order: { created_at: 'DESC' },
2348
+ });
2349
+ } catch (error) {
2350
+ this.logger.error(
2351
+ `Error fetching user integrations for user ${userId}: ${error.message}`,
2352
+ );
2353
+ throw error;
2354
+ }
2355
+ }
2356
+
2357
+ async getConfigUserIntegrations(
2358
+ configId: number,
2359
+ ): Promise<UserIntegration[]> {
2360
+ try {
2361
+ return await this.userIntegrationRepository.find({
2362
+ where: { integration_config_id: configId, is_active: true },
2363
+ order: { created_at: 'DESC' },
2364
+ });
2365
+ } catch (error) {
2366
+ this.logger.error(
2367
+ `Error fetching user integrations for config ${configId}: ${error.message}`,
2368
+ );
2369
+ throw error;
2370
+ }
2371
+ }
2372
+
2373
+ async getUserIntegrationByUserAndConfig(
2374
+ userId: number,
2375
+ configId: number,
2376
+ ): Promise<UserIntegration | null> {
2377
+ try {
2378
+ return await this.userIntegrationRepository.findOne({
2379
+ where: {
2380
+ user_id: userId,
2381
+ integration_config_id: configId,
2382
+ is_active: true,
2383
+ },
2384
+ });
2385
+ } catch (error) {
2386
+ this.logger.error(
2387
+ `Error fetching user integration for user ${userId} and config ${configId}: ${error.message}`,
2388
+ );
2389
+ throw error;
2390
+ }
2391
+ }
2392
+
2393
+ async updateUserIntegration(
2394
+ id: number,
2395
+ updateDto: UpdateUserIntegrationDto,
2396
+ ): Promise<UserIntegration> {
2397
+ try {
2398
+ const userIntegration = await this.userIntegrationRepository.findOne({
2399
+ where: { id },
2400
+ });
2401
+
2402
+ if (!userIntegration) {
2403
+ throw new Error('User integration mapping not found');
2404
+ }
2405
+
2406
+ Object.assign(userIntegration, updateDto);
2407
+ return await this.userIntegrationRepository.save(userIntegration);
2408
+ } catch (error) {
2409
+ this.logger.error(
2410
+ `Error updating user integration ${id}: ${error.message}`,
2411
+ );
2412
+ throw error;
2413
+ }
2414
+ }
2415
+
2416
+ async deleteUserIntegration(id: number): Promise<void> {
2417
+ try {
2418
+ const userIntegration = await this.userIntegrationRepository.findOne({
2419
+ where: { id },
2420
+ });
2421
+
2422
+ if (!userIntegration) {
2423
+ throw new Error('User integration mapping not found');
2424
+ }
2425
+
2426
+ await this.userIntegrationRepository.remove(userIntegration);
2427
+ } catch (error) {
2428
+ this.logger.error(
2429
+ `Error deleting user integration ${id}: ${error.message}`,
2430
+ );
2431
+ throw error;
2432
+ }
2433
+ }
2434
+
2435
+ /**
2436
+ * Get user integration data for a specific integration strategy
2437
+ * This method is intended to be used by strategies that need user mapping
2438
+ */
2439
+ async getUserIntegrationForStrategy(
2440
+ userId: number,
2441
+ integrationConfigId: number,
2442
+ ): Promise<any | null> {
2443
+ try {
2444
+ const userIntegration = await this.getUserIntegrationByUserAndConfig(
2445
+ userId,
2446
+ integrationConfigId,
2447
+ );
2448
+
2449
+ if (!userIntegration) {
2450
+ return null;
2451
+ }
2452
+
2453
+ return {
2454
+ external_user_id: userIntegration.external_user_id,
2455
+ external_user_data: userIntegration.external_user_data,
2456
+ };
2457
+ } catch (error) {
2458
+ this.logger.error(
2459
+ `Error fetching user integration data for strategy: ${error.message}`,
2460
+ );
2461
+ return null;
2462
+ }
2463
+ }
2464
+
2465
+ /**
2466
+ * Check agent status for TELEPHONE integration
2467
+ * Works with any provider that implements checkAgentStatus method
2468
+ */
2469
+ async checkAgentStatus(
2470
+ levelId: number,
2471
+ levelType: string,
2472
+ appCode: string,
2473
+ userId: number,
2474
+ integrationType: 'TELEPHONE' = 'TELEPHONE',
2475
+ ): Promise<{
2476
+ success: boolean;
2477
+ isReady?: boolean;
2478
+ state?: string;
2479
+ agentInfo?: any;
2480
+ error?: string;
2481
+ }> {
2482
+ try {
2483
+ // Get the active configuration
2484
+ const config = await this.getSingleActiveConfig(
2485
+ levelId,
2486
+ levelType,
2487
+ appCode,
2488
+ integrationType,
2489
+ );
2490
+
2491
+ if (!config) {
2492
+ return {
2493
+ success: false,
2494
+ error: 'No active TELEPHONE configuration found',
2495
+ };
2496
+ }
2497
+
2498
+ // Get user integration mapping
2499
+ const userIntegration = await this.getUserIntegrationByUserAndConfig(
2500
+ userId,
2501
+ config.id,
2502
+ );
2503
+
2504
+ if (!userIntegration) {
2505
+ return {
2506
+ success: false,
2507
+ error: 'User integration mapping not found. Please configure agent details.',
2508
+ };
2509
+ }
2510
+
2511
+ // Create strategy instance
2512
+ const strategy = this.integrationFactory.create(
2513
+ config.integration_type,
2514
+ 'API', // service is deprecated, using default
2515
+ config.integration_provider,
2516
+ );
2517
+
2518
+ // Get the merged config with user data
2519
+ let mergedConfig = config.config_json;
2520
+
2521
+ if (strategy.createUserSpecificConfig) {
2522
+ mergedConfig = strategy.createUserSpecificConfig(
2523
+ config.config_json,
2524
+ userIntegration.external_user_id,
2525
+ );
2526
+ }
2527
+
2528
+ // Check if strategy supports agent status check
2529
+ if (typeof (strategy as any).checkAgentStatus !== 'function') {
2530
+ return {
2531
+ success: false,
2532
+ error: `Agent status check not supported for provider: ${config.integration_provider}`,
2533
+ };
2534
+ }
2535
+
2536
+ // Check agent status
2537
+ const statusResult = await (strategy as any).checkAgentStatus(
2538
+ mergedConfig,
2539
+ );
2540
+
2541
+ return {
2542
+ success: true,
2543
+ isReady: statusResult.isReady,
2544
+ state: statusResult.state,
2545
+ error: statusResult.error,
2546
+ };
2547
+ } catch (error) {
2548
+ this.logger.error(
2549
+ `Error checking agent status: ${error.message}`,
2550
+ error.stack,
2551
+ );
2552
+ return {
2553
+ success: false,
2554
+ error: error.message || 'Failed to check agent status',
2555
+ };
2556
+ }
2557
+ }
2558
+ }