rez_core 4.0.82 → 4.0.84

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