rez_core 5.0.38 → 5.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/.claude/settings.local.json +26 -0
  2. package/.idea/250218_nodejs_core.iml +8 -11
  3. package/.idea/codeStyles/Project.xml +58 -58
  4. package/.idea/codeStyles/codeStyleConfig.xml +4 -4
  5. package/.idea/copilot.data.migration.agent.xml +6 -0
  6. package/.idea/copilot.data.migration.ask.xml +6 -0
  7. package/.idea/copilot.data.migration.ask2agent.xml +6 -0
  8. package/.idea/copilot.data.migration.edit.xml +6 -0
  9. package/.idea/inspectionProfiles/Project_Default.xml +1 -1
  10. package/.idea/misc.xml +6 -0
  11. package/.idea/modules.xml +7 -7
  12. package/.idea/prettier.xml +5 -5
  13. package/.idea/vcs.xml +5 -5
  14. package/.prettierrc +3 -3
  15. package/README.md +99 -99
  16. package/dist/config/database.config.js +1 -1
  17. package/dist/config/database.config.js.map +1 -1
  18. package/dist/module/auth/guards/role.guard.js +3 -3
  19. package/dist/module/auth/services/auth.service.js +2 -2
  20. package/dist/module/filter/repository/saved-filter.repository.js +4 -4
  21. package/dist/module/filter/service/filter-evaluator.service.js +2 -2
  22. package/dist/module/filter/service/filter.service.js +22 -22
  23. package/dist/module/integration/examples/usage.example.js +9 -9
  24. package/dist/module/integration/service/integration.service.js +1 -1
  25. package/dist/module/integration/service/wrapper.service.js +26 -26
  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/meta/repository/entity-attribute-update.repository.js +3 -3
  29. package/dist/module/meta/repository/entity-master.repository.js +6 -6
  30. package/dist/module/meta/service/entity-dynamic.service.js +44 -44
  31. package/dist/module/meta/service/entity-list.service.js +3 -3
  32. package/dist/module/meta/service/entity-relation.service.js +9 -9
  33. package/dist/module/meta/service/entity-service-impl.service.js +3 -3
  34. package/dist/module/meta/service/resolver.service.js +3 -3
  35. package/dist/module/module/repository/menu.repository.js +12 -12
  36. package/dist/module/notification/service/notification.service.js +10 -10
  37. package/dist/module/user/controller/login.controller.js +18 -18
  38. package/dist/module/user/service/role.service.js +4 -4
  39. package/dist/module/user/service/user-session.service.js +2 -2
  40. package/dist/module/workflow/repository/action.repository.js +20 -20
  41. package/dist/module/workflow/repository/comm-template.repository.js +6 -6
  42. package/dist/module/workflow/repository/form-master.repository.js +2 -2
  43. package/dist/module/workflow/repository/stage-group.repository.js +20 -20
  44. package/dist/module/workflow/repository/stage-movement.repository.js +17 -17
  45. package/dist/module/workflow/repository/stage.repository.js +8 -8
  46. package/dist/module/workflow/service/action-template-mapping.service.js +13 -13
  47. package/dist/module/workflow/service/action.service.js +7 -7
  48. package/dist/module/workflow/service/entity-modification.service.js +2 -2
  49. package/dist/module/workflow/service/stage-group.service.js +2 -2
  50. package/dist/module/workflow/service/stage.service.js +2 -2
  51. package/dist/module/workflow/service/task.service.js +35 -35
  52. package/dist/module/workflow/service/workflow-list-master.service.js +15 -15
  53. package/dist/module/workflow/service/workflow-meta.service.js +26 -26
  54. package/dist/module/workflow/service/workflow.service.js +2 -2
  55. package/dist/module/workflow-automation/service/schedule-handler.service.js +9 -9
  56. package/dist/module/workflow-schedule/processors/schedule.processor.js +4 -4
  57. package/dist/module/workflow-schedule/service/workflow-schedule.service.js +9 -9
  58. package/dist/tsconfig.build.tsbuildinfo +1 -1
  59. package/dist/utils/service/reflection-helper.service.d.ts +1 -1
  60. package/dist/utils/service/reflection-helper.service.js +4 -4
  61. package/dist/utils/service/reflection-helper.service.js.map +1 -1
  62. package/docs/modules/event-driven-integration-design.md +91 -91
  63. package/docs/modules/integration.md +250 -250
  64. package/eslint.config.mjs +34 -34
  65. package/nest-cli.json +14 -14
  66. package/package.json +124 -124
  67. package/server.log +850 -0
  68. package/src/app.controller.ts +12 -12
  69. package/src/app.module.ts +66 -66
  70. package/src/app.service.ts +8 -8
  71. package/src/config/bull.config.ts +69 -69
  72. package/src/config/config.module.ts +17 -17
  73. package/src/config/database.config.ts +48 -48
  74. package/src/constant/global.constant.ts +67 -67
  75. package/src/core.module.ts +91 -91
  76. package/src/decorators/roles.decorator.ts +7 -7
  77. package/src/dtos/response.dto.ts +6 -6
  78. package/src/dtos/response.ts +5 -5
  79. package/src/index.ts +1 -1
  80. package/src/module/auth/auth.module.ts +49 -49
  81. package/src/module/auth/controller/auth.controller.ts +28 -28
  82. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  83. package/src/module/auth/guards/jwt.guard.ts +22 -22
  84. package/src/module/auth/guards/role.guard.ts +68 -68
  85. package/src/module/auth/services/auth.service.ts +50 -50
  86. package/src/module/auth/services/jwt.service.ts +11 -11
  87. package/src/module/auth/strategies/google.strategy.ts +54 -54
  88. package/src/module/auth/strategies/jwt.strategy.ts +58 -58
  89. package/src/module/auth/strategies/local.strategy.ts +13 -13
  90. package/src/module/dashboard/controller/dashboard.controller.ts +36 -36
  91. package/src/module/dashboard/dashboard.module.ts +21 -21
  92. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +27 -27
  93. package/src/module/dashboard/entity/widget_master.entity.ts +18 -18
  94. package/src/module/dashboard/repository/dashboard.repository.ts +42 -42
  95. package/src/module/dashboard/service/dashboard.service.ts +73 -73
  96. package/src/module/dev/dev.module.ts +12 -12
  97. package/src/module/dev/service/dev.service.ts +7 -7
  98. package/src/module/enterprise/controller/organization.controller.ts +36 -36
  99. package/src/module/enterprise/enterprise.module.ts +30 -30
  100. package/src/module/enterprise/entity/enterprise.entity.ts +37 -37
  101. package/src/module/enterprise/entity/organization-app-mapping.entity.ts +13 -13
  102. package/src/module/enterprise/entity/organization.entity.ts +92 -92
  103. package/src/module/enterprise/repository/enterprise.repository.ts +31 -31
  104. package/src/module/enterprise/repository/organization.repository.ts +26 -26
  105. package/src/module/enterprise/repository/school.repository.ts +278 -278
  106. package/src/module/enterprise/service/brand.service.ts +5 -5
  107. package/src/module/enterprise/service/enterprise.service.ts +16 -16
  108. package/src/module/enterprise/service/organization-app-mapping.service.ts +4 -4
  109. package/src/module/enterprise/service/organization.service.ts +145 -145
  110. package/src/module/entity_json/controller/entity_json.controller.ts +47 -47
  111. package/src/module/entity_json/entity/entityJson.entity.ts +39 -39
  112. package/src/module/entity_json/entity_json.module.ts +18 -18
  113. package/src/module/entity_json/service/entityJson.repository.ts +37 -37
  114. package/src/module/entity_json/service/entity_json.service.ts +234 -234
  115. package/src/module/filter/controller/filter.controller.ts +84 -84
  116. package/src/module/filter/dto/filter-request.dto.ts +38 -38
  117. package/src/module/filter/entity/saved-filter-detail.entity.ts +41 -41
  118. package/src/module/filter/entity/saved-filter-master.entity.ts +23 -23
  119. package/src/module/filter/filter.module.ts +31 -31
  120. package/src/module/filter/repository/saved-filter.repository.ts +168 -168
  121. package/src/module/filter/service/filter-evaluator.service.ts +86 -86
  122. package/src/module/filter/service/filter.service.ts +1144 -1144
  123. package/src/module/filter/service/saved-filter.service.ts +170 -170
  124. package/src/module/ics/controller/ics.controller.ts +21 -21
  125. package/src/module/ics/dto/ics.dto.ts +55 -55
  126. package/src/module/ics/ics.module.ts +13 -13
  127. package/src/module/ics/service/ics.service.ts +57 -57
  128. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  129. package/src/module/integration/controller/integration.controller.ts +662 -662
  130. package/src/module/integration/controller/wrapper.controller.ts +37 -37
  131. package/src/module/integration/dto/create-config.dto.ts +526 -526
  132. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  133. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  134. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  135. package/src/module/integration/entity/user-integration.entity.ts +71 -71
  136. package/src/module/integration/examples/usage.example.ts +338 -338
  137. package/src/module/integration/factories/base.factory.ts +7 -7
  138. package/src/module/integration/factories/email.factory.ts +49 -49
  139. package/src/module/integration/factories/integration.factory.ts +121 -121
  140. package/src/module/integration/factories/sms.factory.ts +51 -51
  141. package/src/module/integration/factories/telephone.factory.ts +41 -41
  142. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  143. package/src/module/integration/integration.module.ts +110 -110
  144. package/src/module/integration/service/calendar-event.service.ts +118 -118
  145. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  146. package/src/module/integration/service/integration-queue.service.ts +229 -229
  147. package/src/module/integration/service/integration.service.ts +2633 -2633
  148. package/src/module/integration/service/oauth.service.ts +224 -224
  149. package/src/module/integration/service/wrapper.service.ts +701 -701
  150. package/src/module/integration/strategies/email/gmail-api.strategy.ts +280 -280
  151. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  152. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  153. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +260 -260
  154. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  155. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  156. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  157. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  158. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  159. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  160. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  161. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -372
  162. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  163. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  164. package/src/module/layout/controller/layout.controller.ts +47 -47
  165. package/src/module/layout/entity/header-items.entity.ts +28 -28
  166. package/src/module/layout/entity/header-section.entity.ts +19 -19
  167. package/src/module/layout/layout.module.ts +21 -21
  168. package/src/module/layout/repository/header-items.repository.ts +18 -18
  169. package/src/module/layout/repository/header-section.repository.ts +22 -22
  170. package/src/module/layout/service/header-section.service.ts +25 -25
  171. package/src/module/layout_preference/controller/layout_preference.controller.ts +73 -73
  172. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  173. package/src/module/layout_preference/layout_preference.module.ts +22 -22
  174. package/src/module/layout_preference/repository/layout_preference.repository.ts +65 -65
  175. package/src/module/layout_preference/service/layout_preference.service.ts +191 -191
  176. package/src/module/lead/controller/lead.controller.ts +30 -30
  177. package/src/module/lead/lead.module.ts +14 -14
  178. package/src/module/lead/repository/lead.repository.ts +41 -41
  179. package/src/module/lead/service/lead.service.ts +54 -54
  180. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +37 -37
  181. package/src/module/linked_attributes/entity/linked_attribute.entity.ts +51 -51
  182. package/src/module/linked_attributes/linked_attributes.module.ts +16 -16
  183. package/src/module/linked_attributes/repository/linked_attribute.repository.ts +12 -12
  184. package/src/module/linked_attributes/service/linked_attributes.service.ts +75 -75
  185. package/src/module/listmaster/controller/list-master.controller.ts +230 -230
  186. package/src/module/listmaster/entity/list-master-items.entity.ts +43 -43
  187. package/src/module/listmaster/entity/list-master.entity.ts +33 -33
  188. package/src/module/listmaster/listmaster.module.ts +46 -46
  189. package/src/module/listmaster/repository/list-master-items.repository.ts +173 -173
  190. package/src/module/listmaster/repository/list-master.repository.ts +46 -46
  191. package/src/module/listmaster/service/list-master-engine.ts +19 -19
  192. package/src/module/listmaster/service/list-master-extension.interface.ts +4 -4
  193. package/src/module/listmaster/service/list-master-item.service.ts +292 -292
  194. package/src/module/listmaster/service/list-master-registry.ts +15 -15
  195. package/src/module/listmaster/service/list-master.service.ts +544 -544
  196. package/src/module/mapper/controller/field-mapper.controller.ts +76 -76
  197. package/src/module/mapper/controller/mapper.controller.ts +20 -20
  198. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  199. package/src/module/mapper/entity/field-lovs.entity.ts +19 -19
  200. package/src/module/mapper/entity/field-mapper.entity.ts +53 -53
  201. package/src/module/mapper/entity/mapper.entity.ts +16 -16
  202. package/src/module/mapper/mapper.module.ts +35 -35
  203. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  204. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  205. package/src/module/mapper/repository/mapper.repository.ts +32 -32
  206. package/src/module/mapper/service/field-mapper.service.ts +271 -271
  207. package/src/module/mapper/service/mapper.service.ts +81 -81
  208. package/src/module/master/controller/master.controller.ts +74 -74
  209. package/src/module/master/service/master.service.ts +483 -483
  210. package/src/module/meta/controller/app-master.controller.ts +38 -38
  211. package/src/module/meta/controller/attribute-master.controller.ts +84 -84
  212. package/src/module/meta/controller/entity-dynamic.controller.ts +125 -125
  213. package/src/module/meta/controller/entity-master.controller.ts +41 -41
  214. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  215. package/src/module/meta/controller/entity.controller.ts +392 -392
  216. package/src/module/meta/controller/entity.public.controller.ts +75 -75
  217. package/src/module/meta/controller/media.controller.ts +107 -107
  218. package/src/module/meta/controller/meta.controller.ts +96 -96
  219. package/src/module/meta/controller/view-master.controller.ts +86 -86
  220. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  221. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  222. package/src/module/meta/dto/entity-table.dto.ts +9 -9
  223. package/src/module/meta/entity/app-master.entity.ts +34 -34
  224. package/src/module/meta/entity/attribute-master.entity.ts +92 -92
  225. package/src/module/meta/entity/base-entity.entity.ts +75 -75
  226. package/src/module/meta/entity/entity-master.entity.ts +85 -85
  227. package/src/module/meta/entity/entity-relation-data.entity.ts +29 -29
  228. package/src/module/meta/entity/entity-relation.entity.ts +23 -23
  229. package/src/module/meta/entity/entity-table-column.entity.ts +61 -61
  230. package/src/module/meta/entity/entity-table.entity.ts +50 -50
  231. package/src/module/meta/entity/media-data.entity.ts +32 -32
  232. package/src/module/meta/entity/preference.entity.ts +62 -62
  233. package/src/module/meta/entity/view-master.entity.ts +41 -41
  234. package/src/module/meta/entity.module.ts +166 -166
  235. package/src/module/meta/repository/app-master.repository.ts +20 -20
  236. package/src/module/meta/repository/attribute-master.repository.ts +138 -138
  237. package/src/module/meta/repository/entity-attribute-update.repository.ts +44 -44
  238. package/src/module/meta/repository/entity-master.repository.ts +111 -111
  239. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  240. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  241. package/src/module/meta/repository/media-data.repository.ts +50 -50
  242. package/src/module/meta/repository/preference.repository.ts +20 -20
  243. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  244. package/src/module/meta/repository/view-master.repository.ts +42 -42
  245. package/src/module/meta/service/app-master.service.ts +37 -37
  246. package/src/module/meta/service/attribute-master.service.ts +130 -130
  247. package/src/module/meta/service/common.service.ts +9 -9
  248. package/src/module/meta/service/entity-attribute-update.service.ts +28 -28
  249. package/src/module/meta/service/entity-dynamic.service.ts +809 -809
  250. package/src/module/meta/service/entity-list.service.ts +205 -205
  251. package/src/module/meta/service/entity-master.service.ts +171 -171
  252. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  253. package/src/module/meta/service/entity-relation.service.ts +87 -87
  254. package/src/module/meta/service/entity-service-impl.service.ts +525 -525
  255. package/src/module/meta/service/entity-table-column.service.ts +39 -39
  256. package/src/module/meta/service/entity-table.service.ts +150 -150
  257. package/src/module/meta/service/entity-validation.service.ts +187 -187
  258. package/src/module/meta/service/entity.service.ts +67 -67
  259. package/src/module/meta/service/field-group.service.ts +103 -103
  260. package/src/module/meta/service/media-data.service.ts +507 -507
  261. package/src/module/meta/service/populate-meta.service.ts +193 -193
  262. package/src/module/meta/service/preference.service.ts +16 -16
  263. package/src/module/meta/service/resolver.service.ts +271 -271
  264. package/src/module/meta/service/section-master.service.ts +104 -104
  265. package/src/module/meta/service/update-form-json.service.ts +22 -22
  266. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  267. package/src/module/meta/service/view-master.service.ts +127 -127
  268. package/src/module/microservice-client/microservice-clients.module.ts +13 -13
  269. package/src/module/microservice-client/service/microservice-client-factory.ts +37 -37
  270. package/src/module/microservice-client/service/microservice-clients.ts +4 -4
  271. package/src/module/module/controller/menu.controller.ts +15 -15
  272. package/src/module/module/controller/module-access.controller.ts +134 -134
  273. package/src/module/module/entity/menu.entity.ts +43 -43
  274. package/src/module/module/entity/module-access.entity.ts +25 -25
  275. package/src/module/module/entity/module-action.entity.ts +17 -17
  276. package/src/module/module/entity/module.entity.ts +52 -52
  277. package/src/module/module/module.module.ts +42 -42
  278. package/src/module/module/repository/menu.repository.ts +184 -184
  279. package/src/module/module/repository/module-access.repository.ts +344 -344
  280. package/src/module/module/service/menu.service.ts +82 -82
  281. package/src/module/module/service/module-access.service.ts +194 -194
  282. package/src/module/notification/controller/notification.controller.ts +58 -58
  283. package/src/module/notification/controller/otp.controller.ts +117 -117
  284. package/src/module/notification/entity/notification.entity.ts +26 -26
  285. package/src/module/notification/entity/otp.entity.ts +28 -28
  286. package/src/module/notification/firebase-admin.config.ts +22 -22
  287. package/src/module/notification/notification.module.ts +69 -69
  288. package/src/module/notification/repository/otp.repository.ts +27 -27
  289. package/src/module/notification/service/email.service.ts +127 -127
  290. package/src/module/notification/service/notification.service.ts +160 -160
  291. package/src/module/notification/service/otp.service.ts +133 -133
  292. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  293. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  294. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  295. package/src/module/third-party-module/third-party.module.ts +12 -12
  296. package/src/module/user/controller/login.controller.ts +198 -198
  297. package/src/module/user/controller/user.controller.ts +40 -40
  298. package/src/module/user/dto/create-user.dto.ts +62 -62
  299. package/src/module/user/dto/update-user.dto.ts +4 -4
  300. package/src/module/user/entity/role.entity.ts +33 -33
  301. package/src/module/user/entity/user-role-mapping.entity.ts +38 -38
  302. package/src/module/user/entity/user-session.entity.ts +73 -73
  303. package/src/module/user/entity/user.entity.ts +59 -59
  304. package/src/module/user/repository/role.repository.ts +96 -96
  305. package/src/module/user/repository/user-role-mapping.repository.ts +126 -126
  306. package/src/module/user/repository/user.repository.ts +50 -50
  307. package/src/module/user/repository/userSession.repository.ts +33 -33
  308. package/src/module/user/service/login.service.ts +326 -326
  309. package/src/module/user/service/role.service.ts +189 -189
  310. package/src/module/user/service/user-role-mapping.service.ts +98 -98
  311. package/src/module/user/service/user-session.service.ts +168 -168
  312. package/src/module/user/service/user.service.ts +368 -368
  313. package/src/module/user/user.module.ts +65 -65
  314. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  315. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  316. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  317. package/src/module/workflow/controller/action.controller.ts +111 -111
  318. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  319. package/src/module/workflow/controller/comm-template.controller.ts +43 -43
  320. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  321. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  322. package/src/module/workflow/controller/stage-group.controller.ts +48 -48
  323. package/src/module/workflow/controller/stage.controller.ts +50 -50
  324. package/src/module/workflow/controller/task.controller.ts +77 -77
  325. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  326. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  327. package/src/module/workflow/controller/workflow.controller.ts +67 -67
  328. package/src/module/workflow/entity/action-category.entity.ts +38 -38
  329. package/src/module/workflow/entity/action-data.entity.ts +55 -55
  330. package/src/module/workflow/entity/action-resources-mapping.entity.ts +29 -29
  331. package/src/module/workflow/entity/action-template-mapping.entity.ts +17 -17
  332. package/src/module/workflow/entity/action.entity.ts +53 -53
  333. package/src/module/workflow/entity/activity-log.entity.ts +43 -43
  334. package/src/module/workflow/entity/comm-template.entity.ts +43 -43
  335. package/src/module/workflow/entity/entity-modification.entity.ts +38 -38
  336. package/src/module/workflow/entity/form.entity.ts +25 -25
  337. package/src/module/workflow/entity/stage-action-mapping.entity.ts +17 -17
  338. package/src/module/workflow/entity/stage-group.entity.ts +23 -23
  339. package/src/module/workflow/entity/stage-movement-data.entity.ts +38 -38
  340. package/src/module/workflow/entity/stage.entity.ts +20 -20
  341. package/src/module/workflow/entity/task-data.entity.ts +88 -88
  342. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  343. package/src/module/workflow/entity/workflow-data.entity.ts +11 -11
  344. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  345. package/src/module/workflow/entity/workflow.entity.ts +20 -20
  346. package/src/module/workflow/repository/action-category.repository.ts +79 -79
  347. package/src/module/workflow/repository/action-data.repository.ts +334 -334
  348. package/src/module/workflow/repository/action.repository.ts +324 -324
  349. package/src/module/workflow/repository/activity-log.repository.ts +148 -148
  350. package/src/module/workflow/repository/comm-template.repository.ts +149 -149
  351. package/src/module/workflow/repository/form-master.repository.ts +59 -59
  352. package/src/module/workflow/repository/stage-group.repository.ts +197 -197
  353. package/src/module/workflow/repository/stage-movement.repository.ts +246 -246
  354. package/src/module/workflow/repository/stage.repository.ts +172 -172
  355. package/src/module/workflow/repository/task.repository.ts +134 -134
  356. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  357. package/src/module/workflow/service/action-category.service.ts +33 -33
  358. package/src/module/workflow/service/action-data.service.ts +62 -62
  359. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  360. package/src/module/workflow/service/action-template-mapping.service.ts +131 -131
  361. package/src/module/workflow/service/action.service.ts +279 -279
  362. package/src/module/workflow/service/activity-log.service.ts +107 -107
  363. package/src/module/workflow/service/comm-template.service.ts +180 -180
  364. package/src/module/workflow/service/entity-modification.service.ts +61 -61
  365. package/src/module/workflow/service/form-master.service.ts +35 -35
  366. package/src/module/workflow/service/populate-workflow.service.ts +303 -303
  367. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  368. package/src/module/workflow/service/stage-group.service.ts +342 -342
  369. package/src/module/workflow/service/stage.service.ts +199 -199
  370. package/src/module/workflow/service/task.service.ts +558 -558
  371. package/src/module/workflow/service/workflow-list-master.service.ts +60 -60
  372. package/src/module/workflow/service/workflow-meta.service.ts +654 -654
  373. package/src/module/workflow/service/workflow.service.ts +205 -205
  374. package/src/module/workflow/workflow.module.ts +180 -180
  375. package/src/module/workflow-automation/SCHEDULING_GUIDE.md +145 -145
  376. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +43 -43
  377. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  378. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +40 -40
  379. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  380. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  381. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  382. package/src/module/workflow-automation/service/schedule-handler.service.ts +168 -168
  383. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +224 -224
  384. package/src/module/workflow-automation/service/workflow-automation.service.ts +515 -515
  385. package/src/module/workflow-automation/workflow-automation.module.ts +54 -54
  386. package/src/module/workflow-schedule/INSTALLATION.md +244 -244
  387. package/src/module/workflow-schedule/MULTI_PROJECT_GUIDE.md +196 -196
  388. package/src/module/workflow-schedule/README.md +422 -422
  389. package/src/module/workflow-schedule/constants/schedule.constants.ts +48 -48
  390. package/src/module/workflow-schedule/controller/workflow-schedule.controller.ts +255 -255
  391. package/src/module/workflow-schedule/docs/CLAUDE_CODE_GUIDE.md +510 -510
  392. package/src/module/workflow-schedule/docs/CLAUDE_CODE_PROMPT.md +362 -362
  393. package/src/module/workflow-schedule/docs/RUN_CLAUDE_CODE.sh +68 -68
  394. package/src/module/workflow-schedule/dto/create-schedule.dto.ts +147 -147
  395. package/src/module/workflow-schedule/dto/get-execution-logs.dto.ts +119 -119
  396. package/src/module/workflow-schedule/dto/update-schedule.dto.ts +96 -96
  397. package/src/module/workflow-schedule/entities/scheduled-workflow.entity.ts +148 -148
  398. package/src/module/workflow-schedule/entities/workflow-execution-log.entity.ts +154 -154
  399. package/src/module/workflow-schedule/interfaces/schedule-job-data.interface.ts +53 -53
  400. package/src/module/workflow-schedule/interfaces/workflow-schedule-options.interface.ts +12 -12
  401. package/src/module/workflow-schedule/processors/schedule.processor.ts +584 -584
  402. package/src/module/workflow-schedule/service/workflow-schedule.service.ts +600 -600
  403. package/src/module/workflow-schedule/workflow-schedule.module.ts +67 -67
  404. package/src/resources/dev.properties.yaml +31 -31
  405. package/src/resources/local.properties.yaml +27 -27
  406. package/src/resources/properties.module.ts +12 -12
  407. package/src/resources/properties.yaml.ts +11 -11
  408. package/src/resources/uat.properties.yaml +31 -31
  409. package/src/table.config.ts +133 -133
  410. package/src/utils/dto/excel-data.dto.ts +14 -14
  411. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  412. package/src/utils/service/base64util.service.ts +18 -18
  413. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  414. package/src/utils/service/codeGenerator.service.ts +22 -22
  415. package/src/utils/service/dateUtil.service.ts +17 -17
  416. package/src/utils/service/encryptUtil.service.ts +97 -97
  417. package/src/utils/service/excel-helper.service.ts +72 -72
  418. package/src/utils/service/excelUtil.service.ts +15 -15
  419. package/src/utils/service/file-util.service.ts +11 -11
  420. package/src/utils/service/json-util.service.ts +23 -23
  421. package/src/utils/service/loggingUtil.service.ts +88 -88
  422. package/src/utils/service/reflection-helper.service.ts +62 -62
  423. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  424. package/src/utils/utils.module.ts +27 -27
  425. package/tsconfig.build.json +4 -4
  426. package/tsconfig.json +24 -24
@@ -1,2633 +1,2633 @@
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
- const profile = this.configService.get('PROFILE');
967
- const subjectPrefix = this.configService.get('SUBJECT_PREFIX');
968
- if (templateId) {
969
- const templateData = await this.processTemplate(
970
- parseInt(templateId, 10),
971
- entity_type,
972
- entity_id,
973
- loggedInUser,
974
- mapped_entities,
975
- );
976
- variables = templateData.variables;
977
- externalTemplateId = templateData.externalTemplateId;
978
- richText = templateData.rich_text;
979
- subject = templateData.subject;
980
- }
981
-
982
- if (subjectPrefix) {
983
- const updatedSubject =
984
- profile?.charAt(0).toUpperCase() +
985
- profile?.slice(1) +
986
- ' : ' +
987
- subject; // << use current subject
988
-
989
- subject = updatedSubject;
990
- }
991
-
992
- // Merge config with enhanced parameters
993
- let finalConfig = {
994
- ...hub.config_json,
995
- ...enhancedConfig,
996
- templateId: externalTemplateId,
997
- variables,
998
- richText,
999
- subject,
1000
- };
1001
-
1002
- // Handle user integration if user_id provided
1003
- if (user_id) {
1004
- const userIntegrationData =
1005
- await this.getUserIntegrationForStrategy(user_id, hub.id);
1006
-
1007
- if (userIntegrationData) {
1008
- finalConfig = {
1009
- ...finalConfig,
1010
- external_user_id: userIntegrationData.external_user_id,
1011
- };
1012
- }
1013
- }
1014
-
1015
- const result = await strategy.sendMessage(
1016
- recipient,
1017
- message,
1018
- finalConfig,
1019
- );
1020
-
1021
- if (result.success) {
1022
- this.logger.log(
1023
- `Generic message sent successfully via ${hub.integration_provider} to ${recipient}`,
1024
- );
1025
- results.push(result);
1026
- hasSuccess = true;
1027
- break; // Move to next recipient
1028
- }
1029
-
1030
- this.logger.warn(
1031
- `Failed to send via ${hub.integration_provider} to ${recipient}: ${result.error}`,
1032
- );
1033
- } catch (error) {
1034
- this.logger.error(
1035
- `Error sending via ${hub.integration_provider} to ${recipient}:`,
1036
- error.message,
1037
- );
1038
- continue;
1039
- }
1040
- }
1041
- }
1042
-
1043
- if (hasSuccess) {
1044
- return {
1045
- success: true,
1046
- messageId: results.map((r) => r.messageId).join(','),
1047
- provider: 'multiple',
1048
- service: 'multiple',
1049
- timestamp: new Date(),
1050
- message: results.map((r) => r.message).join(','),
1051
- };
1052
- }
1053
- } else {
1054
- // Handle single recipient
1055
- for (const hub of sortedConfigs) {
1056
- try {
1057
- const serviceType = this.deriveServiceType(
1058
- hub.integration_type,
1059
- hub.integration_provider,
1060
- hub.config_json,
1061
- );
1062
- const strategy = this.integrationFactory.create(
1063
- hub.integration_type,
1064
- serviceType,
1065
- hub.integration_provider,
1066
- );
1067
-
1068
- // Process template if provided
1069
- let variables;
1070
- let externalTemplateId: string | undefined = undefined;
1071
- let richText;
1072
- if (templateId) {
1073
- const templateData = await this.processTemplate(
1074
- parseInt(templateId, 10),
1075
- entity_type,
1076
- entity_id,
1077
- loggedInUser,
1078
- mapped_entities,
1079
- );
1080
- variables = templateData.variables;
1081
- externalTemplateId = templateData.externalTemplateId;
1082
- richText = templateData.rich_text;
1083
- subject = templateData.subject;
1084
- }
1085
-
1086
- // Merge config with enhanced parameters
1087
- let finalConfig = {
1088
- ...hub.config_json,
1089
- ...enhancedConfig,
1090
- templateId: externalTemplateId,
1091
- variables,
1092
- richText,
1093
- };
1094
-
1095
- // Handle user integration if user_id provided
1096
- if (user_id) {
1097
- const userIntegrationData =
1098
- await this.getUserIntegrationForStrategy(user_id, hub.id);
1099
-
1100
- if (userIntegrationData) {
1101
- finalConfig = {
1102
- ...finalConfig,
1103
- external_user_id: userIntegrationData.external_user_id,
1104
- };
1105
- }
1106
- }
1107
-
1108
- const result = await strategy.sendMessage(to, message, finalConfig);
1109
-
1110
- if (result.success) {
1111
- this.logger.log(
1112
- `Generic message sent successfully via ${hub.integration_provider} to ${to}`,
1113
- );
1114
- return result;
1115
- }
1116
-
1117
- this.logger.warn(
1118
- `Failed to send via ${hub.integration_provider}: ${result.error}`,
1119
- );
1120
- } catch (error) {
1121
- this.logger.error(
1122
- `Error sending via ${hub.integration_provider}:`,
1123
- error.message,
1124
- );
1125
- continue;
1126
- }
1127
- }
1128
- }
1129
-
1130
- throw new Error('All communication providers failed');
1131
- } catch (error) {
1132
- this.logger.error('Generic communication service error:', error.message);
1133
- throw error;
1134
- }
1135
- }
1136
-
1137
- async sendBulkMessage(
1138
- bulkDto: BulkMessageDto,
1139
- ): Promise<{ results: IntegrationResult[]; summary: any }> {
1140
- try {
1141
- const {
1142
- levelId,
1143
- levelType,
1144
- app_code,
1145
- recipients,
1146
- message,
1147
- type,
1148
- priority = 'low',
1149
- subject,
1150
- html,
1151
- templateId,
1152
- variables,
1153
- batchSize = 10,
1154
- } = bulkDto;
1155
-
1156
- const results: IntegrationResult[] = [];
1157
- const batches = this.chunkArray(recipients, batchSize);
1158
-
1159
- for (let i = 0; i < batches.length; i++) {
1160
- const batch = batches[i];
1161
- this.logger.log(
1162
- `Processing batch ${i + 1}/${batches.length} with ${batch.length} recipients`,
1163
- );
1164
-
1165
- const batchPromises = batch.map(async (recipient) => {
1166
- try {
1167
- const messageDto: GenericMessageDto = {
1168
- levelId,
1169
- levelType,
1170
- app_code,
1171
- to: recipient,
1172
- message,
1173
- type,
1174
- priority,
1175
- subject,
1176
- html,
1177
- templateId,
1178
- variables,
1179
- };
1180
-
1181
- return await this.sendGenericMessage(messageDto);
1182
- } catch (error) {
1183
- return {
1184
- success: false,
1185
- provider: 'unknown',
1186
- service: 'unknown',
1187
- error: error.message,
1188
- timestamp: new Date(),
1189
- } as IntegrationResult;
1190
- }
1191
- });
1192
-
1193
- const batchResults = await Promise.allSettled(batchPromises);
1194
- const processedResults = batchResults.map((result) => {
1195
- if (result.status === 'fulfilled') {
1196
- return result.value;
1197
- } else {
1198
- return {
1199
- success: false,
1200
- provider: 'unknown',
1201
- service: 'unknown',
1202
- error: result.reason?.message || 'Unknown error',
1203
- timestamp: new Date(),
1204
- } as IntegrationResult;
1205
- }
1206
- });
1207
-
1208
- results.push(...processedResults);
1209
-
1210
- // Rate limiting delay between batches
1211
- if (i < batches.length - 1) {
1212
- await new Promise((resolve) => setTimeout(resolve, 1000));
1213
- }
1214
- }
1215
-
1216
- const summary = {
1217
- total: results.length,
1218
- successful: results.filter((r) => r.success).length,
1219
- failed: results.filter((r) => !r.success).length,
1220
- successRate:
1221
- (
1222
- (results.filter((r) => r.success).length / results.length) *
1223
- 100
1224
- ).toFixed(2) + '%',
1225
- };
1226
-
1227
- this.logger.log(
1228
- `Bulk message completed: ${summary.successful}/${summary.total} successful`,
1229
- );
1230
-
1231
- return { results, summary };
1232
- } catch (error) {
1233
- this.logger.error('Bulk communication service error:', error.message);
1234
- throw error;
1235
- }
1236
- }
1237
-
1238
- async scheduleMessage(
1239
- scheduledDto: any,
1240
- ): Promise<{ scheduled: boolean; scheduleId?: string }> {
1241
- // For now, return a placeholder. In production, integrate with a job queue like Bull or Agenda
1242
- this.logger.log(`Message scheduled for ${scheduledDto.scheduleFor}`);
1243
-
1244
- return {
1245
- scheduled: true,
1246
- scheduleId: `sched_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
1247
- };
1248
- }
1249
-
1250
- async sendTemplateMessage(templateDto: any): Promise<IntegrationResult> {
1251
- // Get template content (integrate with your template system)
1252
- const template = await this.getTemplate(templateDto.templateId);
1253
-
1254
- const processedMessage = this.replaceTemplateVariables(
1255
- template.content,
1256
- templateDto.variables,
1257
- );
1258
- const processedSubject = template.subject
1259
- ? this.replaceTemplateVariables(template.subject, templateDto.variables)
1260
- : undefined;
1261
-
1262
- const messageDto: GenericMessageDto = {
1263
- levelId: templateDto.levelId,
1264
- levelType: templateDto.levelType,
1265
- app_code: templateDto.app_code,
1266
- to: templateDto.to,
1267
- message: processedMessage,
1268
- subject: processedSubject,
1269
- type: templateDto.type,
1270
- templateId: templateDto.templateId,
1271
- variables: templateDto.variables,
1272
- };
1273
-
1274
- return this.sendGenericMessage(messageDto);
1275
- }
1276
-
1277
- private detectCommunicationType(
1278
- to: string | string[],
1279
- type?: string,
1280
- ): 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE' {
1281
- if (type) {
1282
- return type as 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
1283
- }
1284
-
1285
- const recipient = Array.isArray(to) ? to[0] : to;
1286
-
1287
- // Email detection
1288
- if (recipient.includes('@')) {
1289
- return 'EMAIL';
1290
- }
1291
-
1292
- // Phone number detection (basic)
1293
- if (/^\+?[\d\s\-\(\)]+$/.test(recipient)) {
1294
- // Could be SMS or WhatsApp, default to SMS
1295
- return 'SMS';
1296
- }
1297
-
1298
- // Default to EMAIL if unsure
1299
- return 'EMAIL';
1300
- }
1301
-
1302
- private sortConfigsByPriorityAndDefault(
1303
- configs: IntegrationConfigWithConfig[],
1304
- _priority: string,
1305
- ): IntegrationConfigWithConfig[] {
1306
- return configs.sort((a, b) => {
1307
- // First sort by default (true comes first)
1308
- if (a.is_default !== b.is_default) {
1309
- return b.is_default ? 1 : -1;
1310
- }
1311
-
1312
- // Then sort by priority (lower number = higher priority)
1313
- if (a.priority !== b.priority) {
1314
- return a.priority - b.priority;
1315
- }
1316
-
1317
- // Finally sort by created_at descending (newest first)
1318
- return (
1319
- new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
1320
- );
1321
- });
1322
- }
1323
-
1324
- public async processTemplate(
1325
- templateId: number,
1326
- entity_type: any,
1327
- entity_id: any,
1328
- loggedInUser?: any,
1329
- mappedEntities?: Record<string, any>,
1330
- ): Promise<{
1331
- variables?: Record<string, any>;
1332
- externalTemplateId?: string;
1333
- rich_text?: string;
1334
- subject?: string;
1335
- }> {
1336
- const commTemplate: any = await this.entityService.getEntityData(
1337
- COMM_TEMPLATE,
1338
- templateId,
1339
- {} as any,
1340
- );
1341
- if (!commTemplate) {
1342
- return {
1343
- variables: {},
1344
- externalTemplateId: undefined,
1345
- };
1346
- }
1347
-
1348
- let variables = {};
1349
- if (commTemplate.mapper_id) {
1350
- variables = await this.fieldMapperService.resolveData(
1351
- commTemplate.mapper_id,
1352
- 'LOOKUP',
1353
- entity_type,
1354
- entity_id,
1355
- loggedInUser,
1356
- {} as any,
1357
- mappedEntities,
1358
- );
1359
- }
1360
-
1361
- if (!commTemplate.template_id) {
1362
- let richText = commTemplate.rich_text;
1363
-
1364
- if (!richText) {
1365
- if (commTemplate.markup_id) {
1366
- let url = await this.mediaService.getMediaDownloadUrl(
1367
- commTemplate.markup_id,
1368
- {},
1369
- 60000,
1370
- );
1371
- if (url) {
1372
- let response = await axios.get(url.signedUrl, {
1373
- responseType: 'text',
1374
- });
1375
- richText = response.data;
1376
- }
1377
- }
1378
- }
1379
-
1380
- richText = richText.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1381
- const value = variables[key];
1382
- if (value === undefined) return match;
1383
-
1384
- // If value is an object with signedUrl, use only the signedUrl
1385
- if (
1386
- typeof value === 'object' &&
1387
- value !== null &&
1388
- 'signedUrl' in value
1389
- ) {
1390
- return String(value.signedUrl);
1391
- }
1392
-
1393
- return String(value);
1394
- });
1395
-
1396
- return {
1397
- rich_text: richText,
1398
- subject: commTemplate.subject,
1399
- };
1400
- }
1401
-
1402
- return {
1403
- variables,
1404
- externalTemplateId: commTemplate.template_id,
1405
- };
1406
- }
1407
-
1408
- private replaceTemplateVariables(
1409
- template: string,
1410
- variables: Record<string, any>,
1411
- ): string {
1412
- return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1413
- const value = variables[key];
1414
- return value !== undefined ? String(value) : match;
1415
- });
1416
- }
1417
-
1418
- private async getTemplate(templateId: string) {
1419
- // Placeholder for template system integration
1420
- // In production, this would connect to your template database/service
1421
- return {
1422
- id: templateId,
1423
- subject: 'Default Subject {{variable}}',
1424
- content: 'Hello {{name}}, this is a template message with {{variable}}.',
1425
- };
1426
- }
1427
-
1428
- private chunkArray<T>(array: T[], chunkSize: number): T[][] {
1429
- const chunks: T[][] = [];
1430
- for (let i = 0; i < array.length; i += chunkSize) {
1431
- chunks.push(array.slice(i, i + chunkSize));
1432
- }
1433
- return chunks;
1434
- }
1435
-
1436
- async initGmailOAuth(
1437
- levelId: number,
1438
- levelType: string,
1439
- app_code: string,
1440
- email?: string,
1441
- ): Promise<{ authUrl: string; state: string }> {
1442
- try {
1443
- // Get system OAuth credentials from config
1444
- const clientId = this.configService.get<string>('CLIENT_ID');
1445
- const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1446
-
1447
- if (!clientId || !clientSecret) {
1448
- throw new Error('Gmail OAuth credentials not configured');
1449
- }
1450
-
1451
- const state = this.generateSecureState();
1452
- // Use the existing registered callback URL
1453
- const callbackUrl =
1454
- this.configService.get<string>('CALLBACK_URL') ||
1455
- 'http://localhost:5001/auth/google/callback';
1456
-
1457
- this.gmailOAuthStates.set(state, {
1458
- levelId,
1459
- levelType,
1460
- app_code,
1461
- email,
1462
- timestamp: Date.now(),
1463
- });
1464
-
1465
- // Auto-cleanup after 10 minutes
1466
- setTimeout(
1467
- () => {
1468
- this.gmailOAuthStates.delete(state);
1469
- },
1470
- 10 * 60 * 1000,
1471
- );
1472
-
1473
- const oauth2Client = new google.auth.OAuth2(
1474
- clientId,
1475
- clientSecret,
1476
- callbackUrl,
1477
- );
1478
-
1479
- const scopes = [
1480
- 'https://www.googleapis.com/auth/gmail.send',
1481
- 'https://www.googleapis.com/auth/gmail.readonly',
1482
- 'https://www.googleapis.com/auth/userinfo.email',
1483
- 'https://www.googleapis.com/auth/calendar',
1484
- ];
1485
-
1486
- const authUrl = oauth2Client.generateAuthUrl({
1487
- access_type: 'offline',
1488
- scope: scopes,
1489
- state: `gmail_config:${state}`, // Prefix to identify Gmail config requests
1490
- prompt: 'consent',
1491
- login_hint: email,
1492
- });
1493
-
1494
- return { authUrl, state };
1495
- } catch (error) {
1496
- this.logger.error('Error initializing Gmail OAuth:', error.message);
1497
- throw new Error('Failed to initialize Gmail OAuth');
1498
- }
1499
- }
1500
-
1501
- async handleGmailOAuthCallback(
1502
- code: string,
1503
- state: string,
1504
- ): Promise<GmailSSOResult> {
1505
- try {
1506
- const oauthState = this.gmailOAuthStates.get(state);
1507
- if (!oauthState) {
1508
- throw new Error('Invalid or expired OAuth state');
1509
- }
1510
-
1511
- this.gmailOAuthStates.delete(state);
1512
-
1513
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1514
- throw new Error('OAuth state expired');
1515
- }
1516
-
1517
- // Get system OAuth credentials
1518
- const clientId = this.configService.get<string>('CLIENT_ID');
1519
- const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1520
- const callbackUrl =
1521
- this.configService.get<string>('CALLBACK_URL') ||
1522
- 'http://localhost:5001/auth/google/callback';
1523
-
1524
- const oauth2Client = new google.auth.OAuth2(
1525
- clientId,
1526
- clientSecret,
1527
- callbackUrl,
1528
- );
1529
-
1530
- const { tokens } = await oauth2Client.getToken(code);
1531
-
1532
- if (!tokens.access_token) {
1533
- throw new Error('Failed to obtain access token');
1534
- }
1535
-
1536
- // Get user email from Google
1537
- oauth2Client.setCredentials(tokens);
1538
- const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client });
1539
- const userInfo = await oauth2.userinfo.get();
1540
- const email = userInfo.data.email;
1541
-
1542
- if (!email) {
1543
- throw new Error('Failed to get user email');
1544
- }
1545
-
1546
- // Verify email matches if hint was provided
1547
- if (oauthState.email && oauthState.email !== email) {
1548
- throw new Error('Email mismatch with OAuth hint');
1549
- }
1550
-
1551
- const gmailConfig = {
1552
- clientId,
1553
- clientSecret,
1554
- email: email,
1555
- accessToken: tokens.access_token,
1556
- refreshToken: tokens.refresh_token,
1557
- scope: tokens.scope,
1558
- tokenType: tokens.token_type,
1559
- expiryDate: tokens.expiry_date,
1560
- };
1561
-
1562
- // Validate that no active EMAIL configuration exists
1563
- await this.validateUniqueActiveConfig(
1564
- oauthState.levelId,
1565
- oauthState.levelType,
1566
- oauthState.app_code,
1567
- 'EMAIL',
1568
- 'gmail',
1569
- );
1570
-
1571
- // Create integration config
1572
- const config = this.configRepository.create({
1573
- app_code: oauthState.app_code,
1574
- integration_type: 'EMAIL',
1575
- integration_provider: 'gmail',
1576
- integration_source_id: 1, // Gmail source ID
1577
- level_id: oauthState.levelId,
1578
- level_type: oauthState.levelType,
1579
- status: 1,
1580
- priority: 1,
1581
- is_default: false,
1582
- config_json: gmailConfig as any,
1583
- });
1584
-
1585
- const savedConfig = await this.configRepository.save(config);
1586
-
1587
- this.logger.log(
1588
- `Gmail OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1589
- );
1590
-
1591
- return {
1592
- hubId: savedConfig.id,
1593
- configId: savedConfig.id,
1594
- };
1595
- } catch (error) {
1596
- this.logger.error('Error handling Gmail OAuth callback:', error.message);
1597
- throw new Error(`Failed to complete Gmail OAuth: ${error.message}`);
1598
- }
1599
- }
1600
-
1601
- async handleGmailTokensCallback(
1602
- email: string,
1603
- accessToken: string,
1604
- refreshToken: string,
1605
- state: string,
1606
- ): Promise<GmailSSOResult> {
1607
- try {
1608
- const oauthState = this.gmailOAuthStates.get(state);
1609
- if (!oauthState) {
1610
- throw new Error('Invalid or expired OAuth state');
1611
- }
1612
-
1613
- this.gmailOAuthStates.delete(state);
1614
-
1615
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1616
- throw new Error('OAuth state expired');
1617
- }
1618
-
1619
- // Verify email matches if hint was provided
1620
- if (oauthState.email && oauthState.email !== email) {
1621
- throw new Error('Email mismatch with OAuth hint');
1622
- }
1623
-
1624
- // Validate that no active EMAIL configuration exists
1625
- await this.validateUniqueActiveConfig(
1626
- oauthState.levelId,
1627
- oauthState.levelType,
1628
- oauthState.app_code,
1629
- 'EMAIL',
1630
- 'gmail',
1631
- );
1632
-
1633
- // Pure SSO configuration - no client credentials stored per user
1634
- const gmailConfig = {
1635
- email: email,
1636
- accessToken: accessToken,
1637
- refreshToken: refreshToken,
1638
- authMethod: 'GOOGLE_SSO',
1639
- scopes: [
1640
- 'https://www.googleapis.com/auth/gmail.send',
1641
- 'https://www.googleapis.com/auth/userinfo.email',
1642
- ],
1643
- };
1644
-
1645
- // Create integration config
1646
- const config = this.configRepository.create({
1647
- app_code: oauthState.app_code,
1648
- integration_type: 'EMAIL',
1649
- integration_provider: 'gmail',
1650
- integration_source_id: 1, // Gmail source ID
1651
- level_id: oauthState.levelId,
1652
- level_type: oauthState.levelType,
1653
- status: 1,
1654
- priority: 1,
1655
- is_default: false,
1656
- config_json: gmailConfig as any,
1657
- });
1658
-
1659
- const savedConfig = await this.configRepository.save(config);
1660
-
1661
- this.logger.log(
1662
- `Gmail tokens configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1663
- );
1664
-
1665
- return {
1666
- hubId: savedConfig.id,
1667
- configId: savedConfig.id,
1668
- };
1669
- } catch (error) {
1670
- this.logger.error('Error handling Gmail tokens callback:', error.message);
1671
- throw new Error(
1672
- `Failed to complete Gmail tokens callback: ${error.message}`,
1673
- );
1674
- }
1675
- }
1676
-
1677
- async testGmailConfig(
1678
- hubId: number,
1679
- ): Promise<{ success: boolean; error?: string }> {
1680
- try {
1681
- const integrationConfig = await this.configRepository.findOne({
1682
- where: { id: hubId },
1683
- });
1684
-
1685
- if (!integrationConfig) {
1686
- throw new Error('Integration config not found');
1687
- }
1688
-
1689
- const isValid = await this.gmailApiStrategy.validateConnection(
1690
- integrationConfig.config_json,
1691
- );
1692
-
1693
- if (!isValid) {
1694
- return {
1695
- success: false,
1696
- error: 'Gmail configuration is invalid or expired',
1697
- };
1698
- }
1699
-
1700
- return { success: true };
1701
- } catch (error) {
1702
- this.logger.error('Error testing Gmail config:', error.message);
1703
- return { success: false, error: error.message };
1704
- }
1705
- }
1706
-
1707
- private generateSecureState(): string {
1708
- return Math.random().toString(36).substring(2) + Date.now().toString(36);
1709
- }
1710
-
1711
- private async validateUniqueActiveConfig(
1712
- levelId: number,
1713
- levelType: string,
1714
- app_code: string,
1715
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1716
- provider: string,
1717
- excludeHubId?: number,
1718
- ): Promise<void> {
1719
- // Find all active configurations of the same provider for this level and app_code
1720
- const query = this.configRepository
1721
- .createQueryBuilder('hub')
1722
- .where('hub.level_id = :levelId', { levelId })
1723
- .andWhere('hub.level_type = :levelType', { levelType })
1724
- .andWhere('hub.app_code = :app_code', { app_code })
1725
- .andWhere('hub.integration_type = :configType', { configType })
1726
- .andWhere('hub.integration_provider = :provider', { provider })
1727
- .andWhere('hub.status = :status', { status: 1 });
1728
-
1729
- // Exclude current hub if updating
1730
- if (excludeHubId) {
1731
- query.andWhere('hub.id != :excludeHubId', { excludeHubId });
1732
- }
1733
-
1734
- const existingActiveConfigs = await query.getMany();
1735
-
1736
- // If there are existing active configurations of the same provider, throw error
1737
- if (existingActiveConfigs.length > 0) {
1738
- throw new Error(
1739
- `A ${provider} configuration already exists for ${configType} in app_code ${app_code}, ${levelType} ${levelId}. Only one configuration per provider is allowed.`,
1740
- );
1741
- }
1742
- }
1743
-
1744
- private requiresOAuthFlow(
1745
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1746
- provider: string,
1747
- config: any,
1748
- ): boolean {
1749
- // Check if config indicates OAuth is needed (missing tokens or explicit OAuth request)
1750
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1751
-
1752
- switch (key) {
1753
- case 'email_gmail':
1754
- // Requires OAuth if no access token provided or OAuth explicitly requested
1755
- return !config.accessToken || config.useOAuth === true;
1756
-
1757
- case 'email_outlook':
1758
- // Requires OAuth if no access token provided or OAuth explicitly requested
1759
- return !config.accessToken || config.useOAuth === true;
1760
-
1761
- default:
1762
- // Most other providers don't require OAuth
1763
- return false;
1764
- }
1765
- }
1766
-
1767
- private async generateOAuthUrl(
1768
- levelId: number,
1769
- levelType: string,
1770
- app_code: string,
1771
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1772
- provider: string,
1773
- integration_source_id: number,
1774
- config: any,
1775
- priority?: number,
1776
- is_default?: boolean,
1777
- ): Promise<{ authUrl: string; state: string; message: string }> {
1778
- const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1779
-
1780
- switch (key) {
1781
- case 'email_gmail':
1782
- const gmailResult = await this.initGmailOAuth(
1783
- levelId,
1784
- levelType,
1785
- app_code,
1786
- config.email,
1787
- );
1788
- return {
1789
- authUrl: gmailResult.authUrl,
1790
- state: gmailResult.state,
1791
- message:
1792
- 'Please complete Gmail OAuth authorization. Configuration will be created automatically after authorization.',
1793
- };
1794
-
1795
- case 'email_outlook':
1796
- const outlookResult = await this.initOutlookOAuth(
1797
- levelId,
1798
- levelType,
1799
- app_code,
1800
- config.email,
1801
- );
1802
- return {
1803
- authUrl: outlookResult.authUrl,
1804
- state: outlookResult.state,
1805
- message:
1806
- 'Please complete Outlook OAuth authorization. Configuration will be created automatically after authorization.',
1807
- };
1808
-
1809
- default:
1810
- throw new Error(`OAuth not supported for ${configType}/${provider}`);
1811
- }
1812
- }
1813
-
1814
- private async createDirectConfig(
1815
- levelId: number,
1816
- levelType: string,
1817
- app_code: string,
1818
- configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1819
- provider: string,
1820
- integration_source_id: number,
1821
- config: any,
1822
- priority?: number,
1823
- is_default?: boolean,
1824
- ): Promise<IntegrationConfig> {
1825
- // Validate that no duplicate provider configurations exist
1826
- await this.validateUniqueActiveConfig(
1827
- levelId,
1828
- levelType,
1829
- app_code,
1830
- configType,
1831
- provider,
1832
- );
1833
-
1834
- // Deactivate all other configurations of the same integration type
1835
- await this.configRepository.update(
1836
- {
1837
- level_id: levelId,
1838
- level_type: levelType,
1839
- app_code: app_code,
1840
- integration_type: configType,
1841
- status: 1,
1842
- },
1843
- { status: 0 },
1844
- );
1845
-
1846
- // If setting as default, remove default from other configurations of same type and app_code
1847
- if (is_default) {
1848
- await this.configRepository.update(
1849
- {
1850
- level_id: levelId,
1851
- level_type: levelType,
1852
- app_code: app_code,
1853
- integration_type: configType,
1854
- },
1855
- { is_default: false },
1856
- );
1857
- }
1858
-
1859
- // Create integration config
1860
- const integrationConfig = this.configRepository.create({
1861
- app_code: app_code,
1862
- integration_type: configType,
1863
- integration_provider: provider,
1864
- integration_source_id: integration_source_id,
1865
- level_id: levelId,
1866
- level_type: levelType,
1867
- status: 1,
1868
- priority: priority || 1,
1869
- is_default: is_default || false,
1870
- config_json: config,
1871
- });
1872
-
1873
- const savedConfig = await this.configRepository.save(integrationConfig);
1874
- this.logger.log(
1875
- `Communication config created: ${configType}/${provider} for ${levelType} ${levelId}`,
1876
- );
1877
-
1878
- // Store DID mapping for TELEPHONE integration
1879
- if (configType === 'TELEPHONE') {
1880
- try {
1881
- // Extract DID from config (could be did, callerNumber, or fromNumber)
1882
- const did = config.did || config.callerNumber || config.fromNumber;
1883
-
1884
- if (did) {
1885
- const entityMapper = this.entityMapperRepository.create({
1886
- integration_config_id: savedConfig.id,
1887
- level_id: String(levelId),
1888
- level_type: levelType,
1889
- appcode: app_code,
1890
- did: did,
1891
- campaign_name: config.campaignName || null,
1892
- });
1893
-
1894
- await this.entityMapperRepository.save(entityMapper);
1895
- this.logger.log(
1896
- `DID mapping created for TELEPHONE integration: ${did} for ${levelType} ${levelId}`,
1897
- );
1898
- }
1899
- } catch (error) {
1900
- this.logger.warn(
1901
- `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
1902
- );
1903
- }
1904
- }
1905
-
1906
- return Array.isArray(savedConfig) ? savedConfig[0] : savedConfig;
1907
- }
1908
-
1909
- async initOutlookOAuth(
1910
- levelId: number,
1911
- levelType: string,
1912
- app_code: string,
1913
- email?: string,
1914
- ): Promise<{ authUrl: string; state: string }> {
1915
- try {
1916
- // Get system OAuth credentials from config
1917
- const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1918
- const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1919
-
1920
- if (!clientId || !tenantId) {
1921
- throw new Error('Outlook OAuth credentials not configured');
1922
- }
1923
-
1924
- const state = this.generateSecureState();
1925
- const callbackUrl =
1926
- this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1927
- 'http://localhost:5001/auth/outlook/callback';
1928
-
1929
- this.gmailOAuthStates.set(state, {
1930
- levelId,
1931
- levelType,
1932
- app_code,
1933
- email,
1934
- timestamp: Date.now(),
1935
- });
1936
-
1937
- // Auto-cleanup after 10 minutes
1938
- setTimeout(
1939
- () => {
1940
- this.gmailOAuthStates.delete(state);
1941
- },
1942
- 10 * 60 * 1000,
1943
- );
1944
-
1945
- const scopes = [
1946
- 'https://graph.microsoft.com/Mail.Send',
1947
- 'https://graph.microsoft.com/User.Read',
1948
- ];
1949
-
1950
- const authUrl =
1951
- `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
1952
- `client_id=${clientId}&` +
1953
- `response_type=code&` +
1954
- `redirect_uri=${encodeURIComponent(callbackUrl)}&` +
1955
- `scope=${encodeURIComponent(scopes.join(' '))}&` +
1956
- `state=outlook_config:${state}&` +
1957
- `response_mode=query&` +
1958
- `prompt=consent` +
1959
- (email ? `&login_hint=${encodeURIComponent(email)}` : '');
1960
-
1961
- return { authUrl, state };
1962
- } catch (error) {
1963
- this.logger.error('Error initializing Outlook OAuth:', error.message);
1964
- throw new Error('Failed to initialize Outlook OAuth');
1965
- }
1966
- }
1967
-
1968
- async handleOutlookOAuthCallback(
1969
- code: string,
1970
- state: string,
1971
- ): Promise<GmailSSOResult> {
1972
- try {
1973
- const oauthState = this.gmailOAuthStates.get(state);
1974
- if (!oauthState) {
1975
- throw new Error('Invalid or expired OAuth state');
1976
- }
1977
-
1978
- this.gmailOAuthStates.delete(state);
1979
-
1980
- if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1981
- throw new Error('OAuth state expired');
1982
- }
1983
-
1984
- const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1985
- const clientSecret = this.configService.get<string>(
1986
- 'OUTLOOK_CLIENT_SECRET',
1987
- );
1988
- const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1989
- const callbackUrl =
1990
- this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1991
- 'http://localhost:5001/auth/outlook/callback';
1992
-
1993
- // Exchange code for tokens
1994
- const tokenResponse = await fetch(
1995
- `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
1996
- {
1997
- method: 'POST',
1998
- headers: {
1999
- 'Content-Type': 'application/x-www-form-urlencoded',
2000
- },
2001
- body: new URLSearchParams({
2002
- client_id: clientId!,
2003
- client_secret: clientSecret!,
2004
- code: code,
2005
- redirect_uri: callbackUrl,
2006
- grant_type: 'authorization_code',
2007
- }),
2008
- },
2009
- );
2010
-
2011
- const tokens = await tokenResponse.json();
2012
-
2013
- if (!tokens.access_token) {
2014
- throw new Error('Failed to obtain access token');
2015
- }
2016
-
2017
- // Get user info from Microsoft Graph
2018
- const userResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
2019
- headers: {
2020
- Authorization: `Bearer ${tokens.access_token}`,
2021
- },
2022
- });
2023
-
2024
- const userInfo = await userResponse.json();
2025
- const email = userInfo.mail || userInfo.userPrincipalName;
2026
-
2027
- if (!email) {
2028
- throw new Error('Failed to get user email');
2029
- }
2030
-
2031
- // Validate that no active EMAIL configuration exists
2032
- await this.validateUniqueActiveConfig(
2033
- oauthState.levelId,
2034
- oauthState.levelType,
2035
- oauthState.app_code,
2036
- 'EMAIL',
2037
- 'outlook',
2038
- );
2039
-
2040
- const outlookConfig = {
2041
- clientId,
2042
- tenantId,
2043
- email: email,
2044
- accessToken: tokens.access_token,
2045
- refreshToken: tokens.refresh_token,
2046
- scope: tokens.scope,
2047
- tokenType: tokens.token_type,
2048
- expiresIn: tokens.expires_in,
2049
- };
2050
-
2051
- // Create integration config
2052
- const config = this.configRepository.create({
2053
- app_code: oauthState.app_code,
2054
- integration_type: 'EMAIL',
2055
- integration_provider: 'outlook',
2056
- integration_source_id: 1, // Outlook source ID
2057
- level_id: oauthState.levelId,
2058
- level_type: oauthState.levelType,
2059
- status: 1,
2060
- priority: 1,
2061
- is_default: false,
2062
- config_json: outlookConfig as any,
2063
- });
2064
-
2065
- const savedConfig = await this.configRepository.save(config);
2066
-
2067
- this.logger.log(
2068
- `Outlook OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
2069
- );
2070
-
2071
- return {
2072
- hubId: savedConfig.id,
2073
- configId: savedConfig.id,
2074
- };
2075
- } catch (error) {
2076
- this.logger.error(
2077
- 'Error handling Outlook OAuth callback:',
2078
- error.message,
2079
- );
2080
- throw new Error(`Failed to complete Outlook OAuth: ${error.message}`);
2081
- }
2082
- }
2083
-
2084
- async getIntegrationConfigById(hubId: number): Promise<
2085
- | (IntegrationConfig & {
2086
- config: IntegrationConfig;
2087
- linkedSource?: string;
2088
- configDetails?: any;
2089
- })
2090
- | null
2091
- > {
2092
- try {
2093
- // Find the integration config by ID
2094
- const integrationConfig = await this.configRepository.findOne({
2095
- where: { id: hubId },
2096
- });
2097
-
2098
- if (!integrationConfig) {
2099
- return null;
2100
- }
2101
-
2102
- // Extract linked source and config details
2103
- const linkedSource = this.extractLinkedSource(
2104
- integrationConfig.integration_type,
2105
- integrationConfig.integration_provider,
2106
- integrationConfig.config_json,
2107
- );
2108
-
2109
- const configDetails = this.extractConfigDetails(
2110
- integrationConfig.integration_type,
2111
- integrationConfig.integration_provider,
2112
- integrationConfig.config_json,
2113
- );
2114
-
2115
- return {
2116
- ...integrationConfig,
2117
- config: integrationConfig,
2118
- linkedSource,
2119
- configDetails,
2120
- };
2121
- } catch (error) {
2122
- this.logger.error(
2123
- `Error fetching communication config by ID ${hubId}:`,
2124
- error.message,
2125
- );
2126
- throw new Error(
2127
- `Failed to fetch communication configuration: ${error.message}`,
2128
- );
2129
- }
2130
- }
2131
-
2132
- async getIntegrationTemplates(
2133
- levelId: number,
2134
- levelType: string,
2135
- app_code: string,
2136
- integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
2137
- ): Promise<{
2138
- success: boolean;
2139
- data?: Array<{
2140
- label: string;
2141
- value: string;
2142
- }>;
2143
- error?: string;
2144
- }> {
2145
- try {
2146
- // Get active configuration for the integration type
2147
- const config = await this.getSingleActiveConfig(
2148
- levelId,
2149
- levelType,
2150
- app_code,
2151
- integration_type,
2152
- );
2153
-
2154
- if (!config) {
2155
- return {
2156
- success: false,
2157
- error: `No active ${integration_type} configuration found for this level`,
2158
- };
2159
- }
2160
-
2161
- // Create strategy instance
2162
- const strategy = this.integrationFactory.create(
2163
- config.integration_type,
2164
- 'API',
2165
- config.integration_provider,
2166
- );
2167
-
2168
- // Check if strategy supports getTemplates
2169
- if (typeof (strategy as any).getTemplates !== 'function') {
2170
- return {
2171
- success: false,
2172
- error: `Template retrieval not supported for provider: ${config.integration_provider}`,
2173
- };
2174
- }
2175
-
2176
- // Call getTemplates method
2177
- return await (strategy as any).getTemplates(config.config_json);
2178
- } catch (error) {
2179
- this.logger.error(
2180
- `Error fetching templates for ${integration_type} level ${levelId}/${levelType}:`,
2181
- error.message,
2182
- );
2183
- return {
2184
- success: false,
2185
- error: `Failed to fetch templates: ${error.message}`,
2186
- };
2187
- }
2188
- }
2189
-
2190
- async getSendGridTemplates(
2191
- levelId: number,
2192
- levelType: string,
2193
- app_code: string,
2194
- ): Promise<{
2195
- success: boolean;
2196
- data?: Array<{
2197
- label: string;
2198
- value: string;
2199
- }>;
2200
- error?: string;
2201
- }> {
2202
- try {
2203
- // Find active SendGrid configurations for this level
2204
- const hubs = await this.getActiveConfigs(
2205
- levelId,
2206
- levelType,
2207
- app_code,
2208
- 'EMAIL',
2209
- );
2210
-
2211
- // Look for SendGrid provider
2212
- const sendGridHub = hubs.find(
2213
- (hub) => hub.integration_provider === 'sendgrid',
2214
- );
2215
-
2216
- if (!sendGridHub) {
2217
- return {
2218
- success: false,
2219
- error: 'No active SendGrid configuration found for this level',
2220
- };
2221
- }
2222
-
2223
- // Extract API key from configuration
2224
- const apiKey = sendGridHub.config_json?.apiKey;
2225
-
2226
- if (!apiKey) {
2227
- return {
2228
- success: false,
2229
- error: 'SendGrid API key not found in configuration',
2230
- };
2231
- }
2232
-
2233
- // Use the SendGrid strategy to fetch templates
2234
- return this.sendGridApiStrategy.getTemplates(apiKey);
2235
- } catch (error) {
2236
- this.logger.error(
2237
- `Error fetching SendGrid templates for level ${levelId}/${levelType}:`,
2238
- error.message,
2239
- );
2240
- return {
2241
- success: false,
2242
- error: `Failed to fetch SendGrid templates: ${error.message}`,
2243
- };
2244
- }
2245
- }
2246
-
2247
- async getSendGridVerifiedSenders(apiKey: string): Promise<{
2248
- success: boolean;
2249
- data?: Array<{
2250
- label: string;
2251
- value: string;
2252
- }>;
2253
- error?: string;
2254
- }> {
2255
- try {
2256
- if (!apiKey) {
2257
- return {
2258
- success: false,
2259
- error: 'SendGrid API key not found in configuration',
2260
- };
2261
- }
2262
-
2263
- // Use the SendGrid strategy to fetch verified senders
2264
- return this.sendGridApiStrategy.getVerifiedSenders(apiKey);
2265
- } catch (error) {
2266
- this.logger.error(
2267
- `Error fetching SendGrid verified senders`,
2268
- error.message,
2269
- );
2270
- return {
2271
- success: false,
2272
- error: `Failed to fetch SendGrid verified senders: ${error.message}`,
2273
- };
2274
- }
2275
- }
2276
-
2277
- // UserIntegration Management Methods
2278
-
2279
- async createUserIntegration(
2280
- createDto: CreateUserIntegrationDto,
2281
- ): Promise<UserIntegration> {
2282
- try {
2283
- // Check if mapping already exists
2284
- const existing = await this.userIntegrationRepository.findOne({
2285
- where: {
2286
- user_id: createDto.user_id,
2287
- integration_config_id: createDto.integration_config_id,
2288
- },
2289
- });
2290
-
2291
- if (existing) {
2292
- throw new Error('User integration mapping already exists');
2293
- }
2294
-
2295
- // Verify integration config exists
2296
- const config = await this.configRepository.findOne({
2297
- where: { id: createDto.integration_config_id },
2298
- });
2299
-
2300
- if (!config) {
2301
- throw new Error('Integration configuration not found');
2302
- }
2303
-
2304
- const userIntegration = this.userIntegrationRepository.create(createDto);
2305
- return await this.userIntegrationRepository.save(userIntegration);
2306
- } catch (error) {
2307
- this.logger.error(
2308
- `Error creating user integration mapping: ${error.message}`,
2309
- );
2310
- throw error;
2311
- }
2312
- }
2313
-
2314
- async bulkCreateUserIntegration(
2315
- bulkDto: BulkCreateUserIntegrationDto,
2316
- ): Promise<{
2317
- created: UserIntegration[];
2318
- updated: UserIntegration[];
2319
- failed: Array<{ data: CreateUserIntegrationDto; error: string }>;
2320
- summary: {
2321
- total: number;
2322
- created: number;
2323
- updated: number;
2324
- failed: number;
2325
- };
2326
- }> {
2327
- const created: UserIntegration[] = [];
2328
- const updated: UserIntegration[] = [];
2329
- const failed: Array<{ data: CreateUserIntegrationDto; error: string }> = [];
2330
-
2331
- try {
2332
- for (const createDto of bulkDto.user_integrations) {
2333
- try {
2334
- // Check if mapping already exists
2335
- const existing = await this.userIntegrationRepository.findOne({
2336
- where: {
2337
- user_id: createDto.user_id,
2338
- integration_config_id: createDto.integration_config_id,
2339
- },
2340
- });
2341
-
2342
- if (existing) {
2343
- // Update existing mapping
2344
- if (createDto.external_user_id !== undefined) {
2345
- existing.external_user_id = createDto.external_user_id;
2346
- }
2347
- if (createDto.external_user_data !== undefined) {
2348
- existing.external_user_data = createDto.external_user_data;
2349
- }
2350
- if (createDto.is_active !== undefined) {
2351
- existing.is_active = createDto.is_active;
2352
- }
2353
-
2354
- const updatedIntegration =
2355
- await this.userIntegrationRepository.save(existing);
2356
- updated.push(updatedIntegration);
2357
-
2358
- this.logger.log(
2359
- `Updated user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2360
- );
2361
- } else {
2362
- // Verify integration config exists
2363
- const config = await this.configRepository.findOne({
2364
- where: { id: createDto.integration_config_id },
2365
- });
2366
-
2367
- if (!config) {
2368
- failed.push({
2369
- data: createDto,
2370
- error: 'Integration configuration not found',
2371
- });
2372
- continue;
2373
- }
2374
-
2375
- // Create new mapping
2376
- const userIntegration =
2377
- this.userIntegrationRepository.create(createDto);
2378
- const savedIntegration =
2379
- await this.userIntegrationRepository.save(userIntegration);
2380
- created.push(savedIntegration);
2381
-
2382
- this.logger.log(
2383
- `Created user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2384
- );
2385
- }
2386
- } catch (error) {
2387
- failed.push({
2388
- data: createDto,
2389
- error: error.message || 'Unknown error',
2390
- });
2391
- this.logger.error(
2392
- `Error processing user integration for user ${createDto.user_id}: ${error.message}`,
2393
- );
2394
- }
2395
- }
2396
-
2397
- const summary = {
2398
- total: bulkDto.user_integrations.length,
2399
- created: created.length,
2400
- updated: updated.length,
2401
- failed: failed.length,
2402
- };
2403
-
2404
- this.logger.log(
2405
- `Bulk user integration completed: ${summary.created} created, ${summary.updated} updated, ${summary.failed} failed`,
2406
- );
2407
-
2408
- return { created, updated, failed, summary };
2409
- } catch (error) {
2410
- this.logger.error(
2411
- `Error in bulk user integration creation: ${error.message}`,
2412
- );
2413
- throw error;
2414
- }
2415
- }
2416
-
2417
- async getUserIntegrations(userId: number): Promise<UserIntegration[]> {
2418
- try {
2419
- return await this.userIntegrationRepository.find({
2420
- where: { user_id: userId, is_active: true },
2421
- order: { created_at: 'DESC' },
2422
- });
2423
- } catch (error) {
2424
- this.logger.error(
2425
- `Error fetching user integrations for user ${userId}: ${error.message}`,
2426
- );
2427
- throw error;
2428
- }
2429
- }
2430
-
2431
- async getConfigUserIntegrations(
2432
- configId: number,
2433
- ): Promise<UserIntegration[]> {
2434
- try {
2435
- return await this.userIntegrationRepository.find({
2436
- where: { integration_config_id: configId, is_active: true },
2437
- order: { created_at: 'DESC' },
2438
- });
2439
- } catch (error) {
2440
- this.logger.error(
2441
- `Error fetching user integrations for config ${configId}: ${error.message}`,
2442
- );
2443
- throw error;
2444
- }
2445
- }
2446
-
2447
- async getUserIntegrationByUserAndConfig(
2448
- userId: number,
2449
- configId: number,
2450
- ): Promise<UserIntegration | null> {
2451
- try {
2452
- return await this.userIntegrationRepository.findOne({
2453
- where: {
2454
- user_id: userId,
2455
- integration_config_id: configId,
2456
- is_active: true,
2457
- },
2458
- });
2459
- } catch (error) {
2460
- this.logger.error(
2461
- `Error fetching user integration for user ${userId} and config ${configId}: ${error.message}`,
2462
- );
2463
- throw error;
2464
- }
2465
- }
2466
-
2467
- async updateUserIntegration(
2468
- id: number,
2469
- updateDto: UpdateUserIntegrationDto,
2470
- ): Promise<UserIntegration> {
2471
- try {
2472
- const userIntegration = await this.userIntegrationRepository.findOne({
2473
- where: { id },
2474
- });
2475
-
2476
- if (!userIntegration) {
2477
- throw new Error('User integration mapping not found');
2478
- }
2479
-
2480
- Object.assign(userIntegration, updateDto);
2481
- return await this.userIntegrationRepository.save(userIntegration);
2482
- } catch (error) {
2483
- this.logger.error(
2484
- `Error updating user integration ${id}: ${error.message}`,
2485
- );
2486
- throw error;
2487
- }
2488
- }
2489
-
2490
- async deleteUserIntegration(id: number): Promise<void> {
2491
- try {
2492
- const userIntegration = await this.userIntegrationRepository.findOne({
2493
- where: { id },
2494
- });
2495
-
2496
- if (!userIntegration) {
2497
- throw new Error('User integration mapping not found');
2498
- }
2499
-
2500
- await this.userIntegrationRepository.remove(userIntegration);
2501
- } catch (error) {
2502
- this.logger.error(
2503
- `Error deleting user integration ${id}: ${error.message}`,
2504
- );
2505
- throw error;
2506
- }
2507
- }
2508
-
2509
- /**
2510
- * Get user integration data for a specific integration strategy
2511
- * This method is intended to be used by strategies that need user mapping
2512
- */
2513
- async getUserIntegrationForStrategy(
2514
- userId: number,
2515
- integrationConfigId: number,
2516
- ): Promise<any | null> {
2517
- try {
2518
- const userIntegration = await this.getUserIntegrationByUserAndConfig(
2519
- userId,
2520
- integrationConfigId,
2521
- );
2522
-
2523
- if (!userIntegration) {
2524
- return null;
2525
- }
2526
-
2527
- return {
2528
- external_user_id: userIntegration.external_user_id,
2529
- external_user_data: userIntegration.external_user_data,
2530
- };
2531
- } catch (error) {
2532
- this.logger.error(
2533
- `Error fetching user integration data for strategy: ${error.message}`,
2534
- );
2535
- return null;
2536
- }
2537
- }
2538
-
2539
- /**
2540
- * Check agent status for TELEPHONE integration
2541
- * Works with any provider that implements checkAgentStatus method
2542
- */
2543
- async checkAgentStatus(
2544
- levelId: number,
2545
- levelType: string,
2546
- appCode: string,
2547
- userId: number,
2548
- integrationType: 'TELEPHONE' = 'TELEPHONE',
2549
- ): Promise<{
2550
- success: boolean;
2551
- isReady?: boolean;
2552
- state?: string;
2553
- agentInfo?: any;
2554
- error?: string;
2555
- }> {
2556
- try {
2557
- // Get the active configuration
2558
- const config = await this.getSingleActiveConfig(
2559
- levelId,
2560
- levelType,
2561
- appCode,
2562
- integrationType,
2563
- );
2564
-
2565
- if (!config) {
2566
- return {
2567
- success: false,
2568
- error: 'No active TELEPHONE configuration found',
2569
- };
2570
- }
2571
-
2572
- // Get user integration mapping
2573
- const userIntegration = await this.getUserIntegrationByUserAndConfig(
2574
- userId,
2575
- config.id,
2576
- );
2577
-
2578
- if (!userIntegration) {
2579
- return {
2580
- success: false,
2581
- error:
2582
- 'User integration mapping not found. Please configure agent details.',
2583
- };
2584
- }
2585
-
2586
- // Create strategy instance
2587
- const strategy = this.integrationFactory.create(
2588
- config.integration_type,
2589
- 'API', // service is deprecated, using default
2590
- config.integration_provider,
2591
- );
2592
-
2593
- // Get the merged config with user data
2594
- let mergedConfig = config.config_json;
2595
-
2596
- if (strategy.createUserSpecificConfig) {
2597
- mergedConfig = strategy.createUserSpecificConfig(
2598
- config.config_json,
2599
- userIntegration.external_user_id,
2600
- );
2601
- }
2602
-
2603
- // Check if strategy supports agent status check
2604
- if (typeof (strategy as any).checkAgentStatus !== 'function') {
2605
- return {
2606
- success: false,
2607
- error: `Agent status check not supported for provider: ${config.integration_provider}`,
2608
- };
2609
- }
2610
-
2611
- // Check agent status
2612
- const statusResult = await (strategy as any).checkAgentStatus(
2613
- mergedConfig,
2614
- );
2615
-
2616
- return {
2617
- success: true,
2618
- isReady: statusResult.isReady,
2619
- state: statusResult.state,
2620
- error: statusResult.error,
2621
- };
2622
- } catch (error) {
2623
- this.logger.error(
2624
- `Error checking agent status: ${error.message}`,
2625
- error.stack,
2626
- );
2627
- return {
2628
- success: false,
2629
- error: error.message || 'Failed to check agent status',
2630
- };
2631
- }
2632
- }
2633
- }
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
+ const profile = this.configService.get('PROFILE');
967
+ const subjectPrefix = this.configService.get('SUBJECT_PREFIX');
968
+ if (templateId) {
969
+ const templateData = await this.processTemplate(
970
+ parseInt(templateId, 10),
971
+ entity_type,
972
+ entity_id,
973
+ loggedInUser,
974
+ mapped_entities,
975
+ );
976
+ variables = templateData.variables;
977
+ externalTemplateId = templateData.externalTemplateId;
978
+ richText = templateData.rich_text;
979
+ subject = templateData.subject;
980
+ }
981
+
982
+ if (subjectPrefix) {
983
+ const updatedSubject =
984
+ profile?.charAt(0).toUpperCase() +
985
+ profile?.slice(1) +
986
+ ' : ' +
987
+ subject; // << use current subject
988
+
989
+ subject = updatedSubject;
990
+ }
991
+
992
+ // Merge config with enhanced parameters
993
+ let finalConfig = {
994
+ ...hub.config_json,
995
+ ...enhancedConfig,
996
+ templateId: externalTemplateId,
997
+ variables,
998
+ richText,
999
+ subject,
1000
+ };
1001
+
1002
+ // Handle user integration if user_id provided
1003
+ if (user_id) {
1004
+ const userIntegrationData =
1005
+ await this.getUserIntegrationForStrategy(user_id, hub.id);
1006
+
1007
+ if (userIntegrationData) {
1008
+ finalConfig = {
1009
+ ...finalConfig,
1010
+ external_user_id: userIntegrationData.external_user_id,
1011
+ };
1012
+ }
1013
+ }
1014
+
1015
+ const result = await strategy.sendMessage(
1016
+ recipient,
1017
+ message,
1018
+ finalConfig,
1019
+ );
1020
+
1021
+ if (result.success) {
1022
+ this.logger.log(
1023
+ `Generic message sent successfully via ${hub.integration_provider} to ${recipient}`,
1024
+ );
1025
+ results.push(result);
1026
+ hasSuccess = true;
1027
+ break; // Move to next recipient
1028
+ }
1029
+
1030
+ this.logger.warn(
1031
+ `Failed to send via ${hub.integration_provider} to ${recipient}: ${result.error}`,
1032
+ );
1033
+ } catch (error) {
1034
+ this.logger.error(
1035
+ `Error sending via ${hub.integration_provider} to ${recipient}:`,
1036
+ error.message,
1037
+ );
1038
+ continue;
1039
+ }
1040
+ }
1041
+ }
1042
+
1043
+ if (hasSuccess) {
1044
+ return {
1045
+ success: true,
1046
+ messageId: results.map((r) => r.messageId).join(','),
1047
+ provider: 'multiple',
1048
+ service: 'multiple',
1049
+ timestamp: new Date(),
1050
+ message: results.map((r) => r.message).join(','),
1051
+ };
1052
+ }
1053
+ } else {
1054
+ // Handle single recipient
1055
+ for (const hub of sortedConfigs) {
1056
+ try {
1057
+ const serviceType = this.deriveServiceType(
1058
+ hub.integration_type,
1059
+ hub.integration_provider,
1060
+ hub.config_json,
1061
+ );
1062
+ const strategy = this.integrationFactory.create(
1063
+ hub.integration_type,
1064
+ serviceType,
1065
+ hub.integration_provider,
1066
+ );
1067
+
1068
+ // Process template if provided
1069
+ let variables;
1070
+ let externalTemplateId: string | undefined = undefined;
1071
+ let richText;
1072
+ if (templateId) {
1073
+ const templateData = await this.processTemplate(
1074
+ parseInt(templateId, 10),
1075
+ entity_type,
1076
+ entity_id,
1077
+ loggedInUser,
1078
+ mapped_entities,
1079
+ );
1080
+ variables = templateData.variables;
1081
+ externalTemplateId = templateData.externalTemplateId;
1082
+ richText = templateData.rich_text;
1083
+ subject = templateData.subject;
1084
+ }
1085
+
1086
+ // Merge config with enhanced parameters
1087
+ let finalConfig = {
1088
+ ...hub.config_json,
1089
+ ...enhancedConfig,
1090
+ templateId: externalTemplateId,
1091
+ variables,
1092
+ richText,
1093
+ };
1094
+
1095
+ // Handle user integration if user_id provided
1096
+ if (user_id) {
1097
+ const userIntegrationData =
1098
+ await this.getUserIntegrationForStrategy(user_id, hub.id);
1099
+
1100
+ if (userIntegrationData) {
1101
+ finalConfig = {
1102
+ ...finalConfig,
1103
+ external_user_id: userIntegrationData.external_user_id,
1104
+ };
1105
+ }
1106
+ }
1107
+
1108
+ const result = await strategy.sendMessage(to, message, finalConfig);
1109
+
1110
+ if (result.success) {
1111
+ this.logger.log(
1112
+ `Generic message sent successfully via ${hub.integration_provider} to ${to}`,
1113
+ );
1114
+ return result;
1115
+ }
1116
+
1117
+ this.logger.warn(
1118
+ `Failed to send via ${hub.integration_provider}: ${result.error}`,
1119
+ );
1120
+ } catch (error) {
1121
+ this.logger.error(
1122
+ `Error sending via ${hub.integration_provider}:`,
1123
+ error.message,
1124
+ );
1125
+ continue;
1126
+ }
1127
+ }
1128
+ }
1129
+
1130
+ throw new Error('All communication providers failed');
1131
+ } catch (error) {
1132
+ this.logger.error('Generic communication service error:', error.message);
1133
+ throw error;
1134
+ }
1135
+ }
1136
+
1137
+ async sendBulkMessage(
1138
+ bulkDto: BulkMessageDto,
1139
+ ): Promise<{ results: IntegrationResult[]; summary: any }> {
1140
+ try {
1141
+ const {
1142
+ levelId,
1143
+ levelType,
1144
+ app_code,
1145
+ recipients,
1146
+ message,
1147
+ type,
1148
+ priority = 'low',
1149
+ subject,
1150
+ html,
1151
+ templateId,
1152
+ variables,
1153
+ batchSize = 10,
1154
+ } = bulkDto;
1155
+
1156
+ const results: IntegrationResult[] = [];
1157
+ const batches = this.chunkArray(recipients, batchSize);
1158
+
1159
+ for (let i = 0; i < batches.length; i++) {
1160
+ const batch = batches[i];
1161
+ this.logger.log(
1162
+ `Processing batch ${i + 1}/${batches.length} with ${batch.length} recipients`,
1163
+ );
1164
+
1165
+ const batchPromises = batch.map(async (recipient) => {
1166
+ try {
1167
+ const messageDto: GenericMessageDto = {
1168
+ levelId,
1169
+ levelType,
1170
+ app_code,
1171
+ to: recipient,
1172
+ message,
1173
+ type,
1174
+ priority,
1175
+ subject,
1176
+ html,
1177
+ templateId,
1178
+ variables,
1179
+ };
1180
+
1181
+ return await this.sendGenericMessage(messageDto);
1182
+ } catch (error) {
1183
+ return {
1184
+ success: false,
1185
+ provider: 'unknown',
1186
+ service: 'unknown',
1187
+ error: error.message,
1188
+ timestamp: new Date(),
1189
+ } as IntegrationResult;
1190
+ }
1191
+ });
1192
+
1193
+ const batchResults = await Promise.allSettled(batchPromises);
1194
+ const processedResults = batchResults.map((result) => {
1195
+ if (result.status === 'fulfilled') {
1196
+ return result.value;
1197
+ } else {
1198
+ return {
1199
+ success: false,
1200
+ provider: 'unknown',
1201
+ service: 'unknown',
1202
+ error: result.reason?.message || 'Unknown error',
1203
+ timestamp: new Date(),
1204
+ } as IntegrationResult;
1205
+ }
1206
+ });
1207
+
1208
+ results.push(...processedResults);
1209
+
1210
+ // Rate limiting delay between batches
1211
+ if (i < batches.length - 1) {
1212
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1213
+ }
1214
+ }
1215
+
1216
+ const summary = {
1217
+ total: results.length,
1218
+ successful: results.filter((r) => r.success).length,
1219
+ failed: results.filter((r) => !r.success).length,
1220
+ successRate:
1221
+ (
1222
+ (results.filter((r) => r.success).length / results.length) *
1223
+ 100
1224
+ ).toFixed(2) + '%',
1225
+ };
1226
+
1227
+ this.logger.log(
1228
+ `Bulk message completed: ${summary.successful}/${summary.total} successful`,
1229
+ );
1230
+
1231
+ return { results, summary };
1232
+ } catch (error) {
1233
+ this.logger.error('Bulk communication service error:', error.message);
1234
+ throw error;
1235
+ }
1236
+ }
1237
+
1238
+ async scheduleMessage(
1239
+ scheduledDto: any,
1240
+ ): Promise<{ scheduled: boolean; scheduleId?: string }> {
1241
+ // For now, return a placeholder. In production, integrate with a job queue like Bull or Agenda
1242
+ this.logger.log(`Message scheduled for ${scheduledDto.scheduleFor}`);
1243
+
1244
+ return {
1245
+ scheduled: true,
1246
+ scheduleId: `sched_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`,
1247
+ };
1248
+ }
1249
+
1250
+ async sendTemplateMessage(templateDto: any): Promise<IntegrationResult> {
1251
+ // Get template content (integrate with your template system)
1252
+ const template = await this.getTemplate(templateDto.templateId);
1253
+
1254
+ const processedMessage = this.replaceTemplateVariables(
1255
+ template.content,
1256
+ templateDto.variables,
1257
+ );
1258
+ const processedSubject = template.subject
1259
+ ? this.replaceTemplateVariables(template.subject, templateDto.variables)
1260
+ : undefined;
1261
+
1262
+ const messageDto: GenericMessageDto = {
1263
+ levelId: templateDto.levelId,
1264
+ levelType: templateDto.levelType,
1265
+ app_code: templateDto.app_code,
1266
+ to: templateDto.to,
1267
+ message: processedMessage,
1268
+ subject: processedSubject,
1269
+ type: templateDto.type,
1270
+ templateId: templateDto.templateId,
1271
+ variables: templateDto.variables,
1272
+ };
1273
+
1274
+ return this.sendGenericMessage(messageDto);
1275
+ }
1276
+
1277
+ private detectCommunicationType(
1278
+ to: string | string[],
1279
+ type?: string,
1280
+ ): 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE' {
1281
+ if (type) {
1282
+ return type as 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE';
1283
+ }
1284
+
1285
+ const recipient = Array.isArray(to) ? to[0] : to;
1286
+
1287
+ // Email detection
1288
+ if (recipient.includes('@')) {
1289
+ return 'EMAIL';
1290
+ }
1291
+
1292
+ // Phone number detection (basic)
1293
+ if (/^\+?[\d\s\-\(\)]+$/.test(recipient)) {
1294
+ // Could be SMS or WhatsApp, default to SMS
1295
+ return 'SMS';
1296
+ }
1297
+
1298
+ // Default to EMAIL if unsure
1299
+ return 'EMAIL';
1300
+ }
1301
+
1302
+ private sortConfigsByPriorityAndDefault(
1303
+ configs: IntegrationConfigWithConfig[],
1304
+ _priority: string,
1305
+ ): IntegrationConfigWithConfig[] {
1306
+ return configs.sort((a, b) => {
1307
+ // First sort by default (true comes first)
1308
+ if (a.is_default !== b.is_default) {
1309
+ return b.is_default ? 1 : -1;
1310
+ }
1311
+
1312
+ // Then sort by priority (lower number = higher priority)
1313
+ if (a.priority !== b.priority) {
1314
+ return a.priority - b.priority;
1315
+ }
1316
+
1317
+ // Finally sort by created_at descending (newest first)
1318
+ return (
1319
+ new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
1320
+ );
1321
+ });
1322
+ }
1323
+
1324
+ public async processTemplate(
1325
+ templateId: number,
1326
+ entity_type: any,
1327
+ entity_id: any,
1328
+ loggedInUser?: any,
1329
+ mappedEntities?: Record<string, any>,
1330
+ ): Promise<{
1331
+ variables?: Record<string, any>;
1332
+ externalTemplateId?: string;
1333
+ rich_text?: string;
1334
+ subject?: string;
1335
+ }> {
1336
+ const commTemplate: any = await this.entityService.getEntityData(
1337
+ COMM_TEMPLATE,
1338
+ templateId,
1339
+ {} as any,
1340
+ );
1341
+ if (!commTemplate) {
1342
+ return {
1343
+ variables: {},
1344
+ externalTemplateId: undefined,
1345
+ };
1346
+ }
1347
+
1348
+ let variables = {};
1349
+ if (commTemplate.mapper_id) {
1350
+ variables = await this.fieldMapperService.resolveData(
1351
+ commTemplate.mapper_id,
1352
+ 'LOOKUP',
1353
+ entity_type,
1354
+ entity_id,
1355
+ loggedInUser,
1356
+ {} as any,
1357
+ mappedEntities,
1358
+ );
1359
+ }
1360
+
1361
+ if (!commTemplate.template_id) {
1362
+ let richText = commTemplate.rich_text;
1363
+
1364
+ if (!richText) {
1365
+ if (commTemplate.markup_id) {
1366
+ let url = await this.mediaService.getMediaDownloadUrl(
1367
+ commTemplate.markup_id,
1368
+ {},
1369
+ 60000,
1370
+ );
1371
+ if (url) {
1372
+ let response = await axios.get(url.signedUrl, {
1373
+ responseType: 'text',
1374
+ });
1375
+ richText = response.data;
1376
+ }
1377
+ }
1378
+ }
1379
+
1380
+ richText = richText.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1381
+ const value = variables[key];
1382
+ if (value === undefined) return match;
1383
+
1384
+ // If value is an object with signedUrl, use only the signedUrl
1385
+ if (
1386
+ typeof value === 'object' &&
1387
+ value !== null &&
1388
+ 'signedUrl' in value
1389
+ ) {
1390
+ return String(value.signedUrl);
1391
+ }
1392
+
1393
+ return String(value);
1394
+ });
1395
+
1396
+ return {
1397
+ rich_text: richText,
1398
+ subject: commTemplate.subject,
1399
+ };
1400
+ }
1401
+
1402
+ return {
1403
+ variables,
1404
+ externalTemplateId: commTemplate.template_id,
1405
+ };
1406
+ }
1407
+
1408
+ private replaceTemplateVariables(
1409
+ template: string,
1410
+ variables: Record<string, any>,
1411
+ ): string {
1412
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
1413
+ const value = variables[key];
1414
+ return value !== undefined ? String(value) : match;
1415
+ });
1416
+ }
1417
+
1418
+ private async getTemplate(templateId: string) {
1419
+ // Placeholder for template system integration
1420
+ // In production, this would connect to your template database/service
1421
+ return {
1422
+ id: templateId,
1423
+ subject: 'Default Subject {{variable}}',
1424
+ content: 'Hello {{name}}, this is a template message with {{variable}}.',
1425
+ };
1426
+ }
1427
+
1428
+ private chunkArray<T>(array: T[], chunkSize: number): T[][] {
1429
+ const chunks: T[][] = [];
1430
+ for (let i = 0; i < array.length; i += chunkSize) {
1431
+ chunks.push(array.slice(i, i + chunkSize));
1432
+ }
1433
+ return chunks;
1434
+ }
1435
+
1436
+ async initGmailOAuth(
1437
+ levelId: number,
1438
+ levelType: string,
1439
+ app_code: string,
1440
+ email?: string,
1441
+ ): Promise<{ authUrl: string; state: string }> {
1442
+ try {
1443
+ // Get system OAuth credentials from config
1444
+ const clientId = this.configService.get<string>('CLIENT_ID');
1445
+ const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1446
+
1447
+ if (!clientId || !clientSecret) {
1448
+ throw new Error('Gmail OAuth credentials not configured');
1449
+ }
1450
+
1451
+ const state = this.generateSecureState();
1452
+ // Use the existing registered callback URL
1453
+ const callbackUrl =
1454
+ this.configService.get<string>('CALLBACK_URL') ||
1455
+ 'http://localhost:5001/auth/google/callback';
1456
+
1457
+ this.gmailOAuthStates.set(state, {
1458
+ levelId,
1459
+ levelType,
1460
+ app_code,
1461
+ email,
1462
+ timestamp: Date.now(),
1463
+ });
1464
+
1465
+ // Auto-cleanup after 10 minutes
1466
+ setTimeout(
1467
+ () => {
1468
+ this.gmailOAuthStates.delete(state);
1469
+ },
1470
+ 10 * 60 * 1000,
1471
+ );
1472
+
1473
+ const oauth2Client = new google.auth.OAuth2(
1474
+ clientId,
1475
+ clientSecret,
1476
+ callbackUrl,
1477
+ );
1478
+
1479
+ const scopes = [
1480
+ 'https://www.googleapis.com/auth/gmail.send',
1481
+ 'https://www.googleapis.com/auth/gmail.readonly',
1482
+ 'https://www.googleapis.com/auth/userinfo.email',
1483
+ 'https://www.googleapis.com/auth/calendar',
1484
+ ];
1485
+
1486
+ const authUrl = oauth2Client.generateAuthUrl({
1487
+ access_type: 'offline',
1488
+ scope: scopes,
1489
+ state: `gmail_config:${state}`, // Prefix to identify Gmail config requests
1490
+ prompt: 'consent',
1491
+ login_hint: email,
1492
+ });
1493
+
1494
+ return { authUrl, state };
1495
+ } catch (error) {
1496
+ this.logger.error('Error initializing Gmail OAuth:', error.message);
1497
+ throw new Error('Failed to initialize Gmail OAuth');
1498
+ }
1499
+ }
1500
+
1501
+ async handleGmailOAuthCallback(
1502
+ code: string,
1503
+ state: string,
1504
+ ): Promise<GmailSSOResult> {
1505
+ try {
1506
+ const oauthState = this.gmailOAuthStates.get(state);
1507
+ if (!oauthState) {
1508
+ throw new Error('Invalid or expired OAuth state');
1509
+ }
1510
+
1511
+ this.gmailOAuthStates.delete(state);
1512
+
1513
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1514
+ throw new Error('OAuth state expired');
1515
+ }
1516
+
1517
+ // Get system OAuth credentials
1518
+ const clientId = this.configService.get<string>('CLIENT_ID');
1519
+ const clientSecret = this.configService.get<string>('CLIENT_SECRET');
1520
+ const callbackUrl =
1521
+ this.configService.get<string>('CALLBACK_URL') ||
1522
+ 'http://localhost:5001/auth/google/callback';
1523
+
1524
+ const oauth2Client = new google.auth.OAuth2(
1525
+ clientId,
1526
+ clientSecret,
1527
+ callbackUrl,
1528
+ );
1529
+
1530
+ const { tokens } = await oauth2Client.getToken(code);
1531
+
1532
+ if (!tokens.access_token) {
1533
+ throw new Error('Failed to obtain access token');
1534
+ }
1535
+
1536
+ // Get user email from Google
1537
+ oauth2Client.setCredentials(tokens);
1538
+ const oauth2 = google.oauth2({ version: 'v2', auth: oauth2Client });
1539
+ const userInfo = await oauth2.userinfo.get();
1540
+ const email = userInfo.data.email;
1541
+
1542
+ if (!email) {
1543
+ throw new Error('Failed to get user email');
1544
+ }
1545
+
1546
+ // Verify email matches if hint was provided
1547
+ if (oauthState.email && oauthState.email !== email) {
1548
+ throw new Error('Email mismatch with OAuth hint');
1549
+ }
1550
+
1551
+ const gmailConfig = {
1552
+ clientId,
1553
+ clientSecret,
1554
+ email: email,
1555
+ accessToken: tokens.access_token,
1556
+ refreshToken: tokens.refresh_token,
1557
+ scope: tokens.scope,
1558
+ tokenType: tokens.token_type,
1559
+ expiryDate: tokens.expiry_date,
1560
+ };
1561
+
1562
+ // Validate that no active EMAIL configuration exists
1563
+ await this.validateUniqueActiveConfig(
1564
+ oauthState.levelId,
1565
+ oauthState.levelType,
1566
+ oauthState.app_code,
1567
+ 'EMAIL',
1568
+ 'gmail',
1569
+ );
1570
+
1571
+ // Create integration config
1572
+ const config = this.configRepository.create({
1573
+ app_code: oauthState.app_code,
1574
+ integration_type: 'EMAIL',
1575
+ integration_provider: 'gmail',
1576
+ integration_source_id: 1, // Gmail source ID
1577
+ level_id: oauthState.levelId,
1578
+ level_type: oauthState.levelType,
1579
+ status: 1,
1580
+ priority: 1,
1581
+ is_default: false,
1582
+ config_json: gmailConfig as any,
1583
+ });
1584
+
1585
+ const savedConfig = await this.configRepository.save(config);
1586
+
1587
+ this.logger.log(
1588
+ `Gmail OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1589
+ );
1590
+
1591
+ return {
1592
+ hubId: savedConfig.id,
1593
+ configId: savedConfig.id,
1594
+ };
1595
+ } catch (error) {
1596
+ this.logger.error('Error handling Gmail OAuth callback:', error.message);
1597
+ throw new Error(`Failed to complete Gmail OAuth: ${error.message}`);
1598
+ }
1599
+ }
1600
+
1601
+ async handleGmailTokensCallback(
1602
+ email: string,
1603
+ accessToken: string,
1604
+ refreshToken: string,
1605
+ state: string,
1606
+ ): Promise<GmailSSOResult> {
1607
+ try {
1608
+ const oauthState = this.gmailOAuthStates.get(state);
1609
+ if (!oauthState) {
1610
+ throw new Error('Invalid or expired OAuth state');
1611
+ }
1612
+
1613
+ this.gmailOAuthStates.delete(state);
1614
+
1615
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1616
+ throw new Error('OAuth state expired');
1617
+ }
1618
+
1619
+ // Verify email matches if hint was provided
1620
+ if (oauthState.email && oauthState.email !== email) {
1621
+ throw new Error('Email mismatch with OAuth hint');
1622
+ }
1623
+
1624
+ // Validate that no active EMAIL configuration exists
1625
+ await this.validateUniqueActiveConfig(
1626
+ oauthState.levelId,
1627
+ oauthState.levelType,
1628
+ oauthState.app_code,
1629
+ 'EMAIL',
1630
+ 'gmail',
1631
+ );
1632
+
1633
+ // Pure SSO configuration - no client credentials stored per user
1634
+ const gmailConfig = {
1635
+ email: email,
1636
+ accessToken: accessToken,
1637
+ refreshToken: refreshToken,
1638
+ authMethod: 'GOOGLE_SSO',
1639
+ scopes: [
1640
+ 'https://www.googleapis.com/auth/gmail.send',
1641
+ 'https://www.googleapis.com/auth/userinfo.email',
1642
+ ],
1643
+ };
1644
+
1645
+ // Create integration config
1646
+ const config = this.configRepository.create({
1647
+ app_code: oauthState.app_code,
1648
+ integration_type: 'EMAIL',
1649
+ integration_provider: 'gmail',
1650
+ integration_source_id: 1, // Gmail source ID
1651
+ level_id: oauthState.levelId,
1652
+ level_type: oauthState.levelType,
1653
+ status: 1,
1654
+ priority: 1,
1655
+ is_default: false,
1656
+ config_json: gmailConfig as any,
1657
+ });
1658
+
1659
+ const savedConfig = await this.configRepository.save(config);
1660
+
1661
+ this.logger.log(
1662
+ `Gmail tokens configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
1663
+ );
1664
+
1665
+ return {
1666
+ hubId: savedConfig.id,
1667
+ configId: savedConfig.id,
1668
+ };
1669
+ } catch (error) {
1670
+ this.logger.error('Error handling Gmail tokens callback:', error.message);
1671
+ throw new Error(
1672
+ `Failed to complete Gmail tokens callback: ${error.message}`,
1673
+ );
1674
+ }
1675
+ }
1676
+
1677
+ async testGmailConfig(
1678
+ hubId: number,
1679
+ ): Promise<{ success: boolean; error?: string }> {
1680
+ try {
1681
+ const integrationConfig = await this.configRepository.findOne({
1682
+ where: { id: hubId },
1683
+ });
1684
+
1685
+ if (!integrationConfig) {
1686
+ throw new Error('Integration config not found');
1687
+ }
1688
+
1689
+ const isValid = await this.gmailApiStrategy.validateConnection(
1690
+ integrationConfig.config_json,
1691
+ );
1692
+
1693
+ if (!isValid) {
1694
+ return {
1695
+ success: false,
1696
+ error: 'Gmail configuration is invalid or expired',
1697
+ };
1698
+ }
1699
+
1700
+ return { success: true };
1701
+ } catch (error) {
1702
+ this.logger.error('Error testing Gmail config:', error.message);
1703
+ return { success: false, error: error.message };
1704
+ }
1705
+ }
1706
+
1707
+ private generateSecureState(): string {
1708
+ return Math.random().toString(36).substring(2) + Date.now().toString(36);
1709
+ }
1710
+
1711
+ private async validateUniqueActiveConfig(
1712
+ levelId: number,
1713
+ levelType: string,
1714
+ app_code: string,
1715
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1716
+ provider: string,
1717
+ excludeHubId?: number,
1718
+ ): Promise<void> {
1719
+ // Find all active configurations of the same provider for this level and app_code
1720
+ const query = this.configRepository
1721
+ .createQueryBuilder('hub')
1722
+ .where('hub.level_id = :levelId', { levelId })
1723
+ .andWhere('hub.level_type = :levelType', { levelType })
1724
+ .andWhere('hub.app_code = :app_code', { app_code })
1725
+ .andWhere('hub.integration_type = :configType', { configType })
1726
+ .andWhere('hub.integration_provider = :provider', { provider })
1727
+ .andWhere('hub.status = :status', { status: 1 });
1728
+
1729
+ // Exclude current hub if updating
1730
+ if (excludeHubId) {
1731
+ query.andWhere('hub.id != :excludeHubId', { excludeHubId });
1732
+ }
1733
+
1734
+ const existingActiveConfigs = await query.getMany();
1735
+
1736
+ // If there are existing active configurations of the same provider, throw error
1737
+ if (existingActiveConfigs.length > 0) {
1738
+ throw new Error(
1739
+ `A ${provider} configuration already exists for ${configType} in app_code ${app_code}, ${levelType} ${levelId}. Only one configuration per provider is allowed.`,
1740
+ );
1741
+ }
1742
+ }
1743
+
1744
+ private requiresOAuthFlow(
1745
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1746
+ provider: string,
1747
+ config: any,
1748
+ ): boolean {
1749
+ // Check if config indicates OAuth is needed (missing tokens or explicit OAuth request)
1750
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1751
+
1752
+ switch (key) {
1753
+ case 'email_gmail':
1754
+ // Requires OAuth if no access token provided or OAuth explicitly requested
1755
+ return !config.accessToken || config.useOAuth === true;
1756
+
1757
+ case 'email_outlook':
1758
+ // Requires OAuth if no access token provided or OAuth explicitly requested
1759
+ return !config.accessToken || config.useOAuth === true;
1760
+
1761
+ default:
1762
+ // Most other providers don't require OAuth
1763
+ return false;
1764
+ }
1765
+ }
1766
+
1767
+ private async generateOAuthUrl(
1768
+ levelId: number,
1769
+ levelType: string,
1770
+ app_code: string,
1771
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1772
+ provider: string,
1773
+ integration_source_id: number,
1774
+ config: any,
1775
+ priority?: number,
1776
+ is_default?: boolean,
1777
+ ): Promise<{ authUrl: string; state: string; message: string }> {
1778
+ const key = `${configType.toLowerCase()}_${provider.toLowerCase()}`;
1779
+
1780
+ switch (key) {
1781
+ case 'email_gmail':
1782
+ const gmailResult = await this.initGmailOAuth(
1783
+ levelId,
1784
+ levelType,
1785
+ app_code,
1786
+ config.email,
1787
+ );
1788
+ return {
1789
+ authUrl: gmailResult.authUrl,
1790
+ state: gmailResult.state,
1791
+ message:
1792
+ 'Please complete Gmail OAuth authorization. Configuration will be created automatically after authorization.',
1793
+ };
1794
+
1795
+ case 'email_outlook':
1796
+ const outlookResult = await this.initOutlookOAuth(
1797
+ levelId,
1798
+ levelType,
1799
+ app_code,
1800
+ config.email,
1801
+ );
1802
+ return {
1803
+ authUrl: outlookResult.authUrl,
1804
+ state: outlookResult.state,
1805
+ message:
1806
+ 'Please complete Outlook OAuth authorization. Configuration will be created automatically after authorization.',
1807
+ };
1808
+
1809
+ default:
1810
+ throw new Error(`OAuth not supported for ${configType}/${provider}`);
1811
+ }
1812
+ }
1813
+
1814
+ private async createDirectConfig(
1815
+ levelId: number,
1816
+ levelType: string,
1817
+ app_code: string,
1818
+ configType: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
1819
+ provider: string,
1820
+ integration_source_id: number,
1821
+ config: any,
1822
+ priority?: number,
1823
+ is_default?: boolean,
1824
+ ): Promise<IntegrationConfig> {
1825
+ // Validate that no duplicate provider configurations exist
1826
+ await this.validateUniqueActiveConfig(
1827
+ levelId,
1828
+ levelType,
1829
+ app_code,
1830
+ configType,
1831
+ provider,
1832
+ );
1833
+
1834
+ // Deactivate all other configurations of the same integration type
1835
+ await this.configRepository.update(
1836
+ {
1837
+ level_id: levelId,
1838
+ level_type: levelType,
1839
+ app_code: app_code,
1840
+ integration_type: configType,
1841
+ status: 1,
1842
+ },
1843
+ { status: 0 },
1844
+ );
1845
+
1846
+ // If setting as default, remove default from other configurations of same type and app_code
1847
+ if (is_default) {
1848
+ await this.configRepository.update(
1849
+ {
1850
+ level_id: levelId,
1851
+ level_type: levelType,
1852
+ app_code: app_code,
1853
+ integration_type: configType,
1854
+ },
1855
+ { is_default: false },
1856
+ );
1857
+ }
1858
+
1859
+ // Create integration config
1860
+ const integrationConfig = this.configRepository.create({
1861
+ app_code: app_code,
1862
+ integration_type: configType,
1863
+ integration_provider: provider,
1864
+ integration_source_id: integration_source_id,
1865
+ level_id: levelId,
1866
+ level_type: levelType,
1867
+ status: 1,
1868
+ priority: priority || 1,
1869
+ is_default: is_default || false,
1870
+ config_json: config,
1871
+ });
1872
+
1873
+ const savedConfig = await this.configRepository.save(integrationConfig);
1874
+ this.logger.log(
1875
+ `Communication config created: ${configType}/${provider} for ${levelType} ${levelId}`,
1876
+ );
1877
+
1878
+ // Store DID mapping for TELEPHONE integration
1879
+ if (configType === 'TELEPHONE') {
1880
+ try {
1881
+ // Extract DID from config (could be did, callerNumber, or fromNumber)
1882
+ const did = config.did || config.callerNumber || config.fromNumber;
1883
+
1884
+ if (did) {
1885
+ const entityMapper = this.entityMapperRepository.create({
1886
+ integration_config_id: savedConfig.id,
1887
+ level_id: String(levelId),
1888
+ level_type: levelType,
1889
+ appcode: app_code,
1890
+ did: did,
1891
+ campaign_name: config.campaignName || null,
1892
+ });
1893
+
1894
+ await this.entityMapperRepository.save(entityMapper);
1895
+ this.logger.log(
1896
+ `DID mapping created for TELEPHONE integration: ${did} for ${levelType} ${levelId}`,
1897
+ );
1898
+ }
1899
+ } catch (error) {
1900
+ this.logger.warn(
1901
+ `Failed to create DID mapping for TELEPHONE integration: ${error.message}`,
1902
+ );
1903
+ }
1904
+ }
1905
+
1906
+ return Array.isArray(savedConfig) ? savedConfig[0] : savedConfig;
1907
+ }
1908
+
1909
+ async initOutlookOAuth(
1910
+ levelId: number,
1911
+ levelType: string,
1912
+ app_code: string,
1913
+ email?: string,
1914
+ ): Promise<{ authUrl: string; state: string }> {
1915
+ try {
1916
+ // Get system OAuth credentials from config
1917
+ const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1918
+ const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1919
+
1920
+ if (!clientId || !tenantId) {
1921
+ throw new Error('Outlook OAuth credentials not configured');
1922
+ }
1923
+
1924
+ const state = this.generateSecureState();
1925
+ const callbackUrl =
1926
+ this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1927
+ 'http://localhost:5001/auth/outlook/callback';
1928
+
1929
+ this.gmailOAuthStates.set(state, {
1930
+ levelId,
1931
+ levelType,
1932
+ app_code,
1933
+ email,
1934
+ timestamp: Date.now(),
1935
+ });
1936
+
1937
+ // Auto-cleanup after 10 minutes
1938
+ setTimeout(
1939
+ () => {
1940
+ this.gmailOAuthStates.delete(state);
1941
+ },
1942
+ 10 * 60 * 1000,
1943
+ );
1944
+
1945
+ const scopes = [
1946
+ 'https://graph.microsoft.com/Mail.Send',
1947
+ 'https://graph.microsoft.com/User.Read',
1948
+ ];
1949
+
1950
+ const authUrl =
1951
+ `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/authorize?` +
1952
+ `client_id=${clientId}&` +
1953
+ `response_type=code&` +
1954
+ `redirect_uri=${encodeURIComponent(callbackUrl)}&` +
1955
+ `scope=${encodeURIComponent(scopes.join(' '))}&` +
1956
+ `state=outlook_config:${state}&` +
1957
+ `response_mode=query&` +
1958
+ `prompt=consent` +
1959
+ (email ? `&login_hint=${encodeURIComponent(email)}` : '');
1960
+
1961
+ return { authUrl, state };
1962
+ } catch (error) {
1963
+ this.logger.error('Error initializing Outlook OAuth:', error.message);
1964
+ throw new Error('Failed to initialize Outlook OAuth');
1965
+ }
1966
+ }
1967
+
1968
+ async handleOutlookOAuthCallback(
1969
+ code: string,
1970
+ state: string,
1971
+ ): Promise<GmailSSOResult> {
1972
+ try {
1973
+ const oauthState = this.gmailOAuthStates.get(state);
1974
+ if (!oauthState) {
1975
+ throw new Error('Invalid or expired OAuth state');
1976
+ }
1977
+
1978
+ this.gmailOAuthStates.delete(state);
1979
+
1980
+ if (Date.now() - oauthState.timestamp > 10 * 60 * 1000) {
1981
+ throw new Error('OAuth state expired');
1982
+ }
1983
+
1984
+ const clientId = this.configService.get<string>('OUTLOOK_CLIENT_ID');
1985
+ const clientSecret = this.configService.get<string>(
1986
+ 'OUTLOOK_CLIENT_SECRET',
1987
+ );
1988
+ const tenantId = this.configService.get<string>('OUTLOOK_TENANT_ID');
1989
+ const callbackUrl =
1990
+ this.configService.get<string>('OUTLOOK_CALLBACK_URL') ||
1991
+ 'http://localhost:5001/auth/outlook/callback';
1992
+
1993
+ // Exchange code for tokens
1994
+ const tokenResponse = await fetch(
1995
+ `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
1996
+ {
1997
+ method: 'POST',
1998
+ headers: {
1999
+ 'Content-Type': 'application/x-www-form-urlencoded',
2000
+ },
2001
+ body: new URLSearchParams({
2002
+ client_id: clientId!,
2003
+ client_secret: clientSecret!,
2004
+ code: code,
2005
+ redirect_uri: callbackUrl,
2006
+ grant_type: 'authorization_code',
2007
+ }),
2008
+ },
2009
+ );
2010
+
2011
+ const tokens = await tokenResponse.json();
2012
+
2013
+ if (!tokens.access_token) {
2014
+ throw new Error('Failed to obtain access token');
2015
+ }
2016
+
2017
+ // Get user info from Microsoft Graph
2018
+ const userResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
2019
+ headers: {
2020
+ Authorization: `Bearer ${tokens.access_token}`,
2021
+ },
2022
+ });
2023
+
2024
+ const userInfo = await userResponse.json();
2025
+ const email = userInfo.mail || userInfo.userPrincipalName;
2026
+
2027
+ if (!email) {
2028
+ throw new Error('Failed to get user email');
2029
+ }
2030
+
2031
+ // Validate that no active EMAIL configuration exists
2032
+ await this.validateUniqueActiveConfig(
2033
+ oauthState.levelId,
2034
+ oauthState.levelType,
2035
+ oauthState.app_code,
2036
+ 'EMAIL',
2037
+ 'outlook',
2038
+ );
2039
+
2040
+ const outlookConfig = {
2041
+ clientId,
2042
+ tenantId,
2043
+ email: email,
2044
+ accessToken: tokens.access_token,
2045
+ refreshToken: tokens.refresh_token,
2046
+ scope: tokens.scope,
2047
+ tokenType: tokens.token_type,
2048
+ expiresIn: tokens.expires_in,
2049
+ };
2050
+
2051
+ // Create integration config
2052
+ const config = this.configRepository.create({
2053
+ app_code: oauthState.app_code,
2054
+ integration_type: 'EMAIL',
2055
+ integration_provider: 'outlook',
2056
+ integration_source_id: 1, // Outlook source ID
2057
+ level_id: oauthState.levelId,
2058
+ level_type: oauthState.levelType,
2059
+ status: 1,
2060
+ priority: 1,
2061
+ is_default: false,
2062
+ config_json: outlookConfig as any,
2063
+ });
2064
+
2065
+ const savedConfig = await this.configRepository.save(config);
2066
+
2067
+ this.logger.log(
2068
+ `Outlook OAuth configuration created successfully for ${oauthState.levelType} ${oauthState.levelId} and email ${email}`,
2069
+ );
2070
+
2071
+ return {
2072
+ hubId: savedConfig.id,
2073
+ configId: savedConfig.id,
2074
+ };
2075
+ } catch (error) {
2076
+ this.logger.error(
2077
+ 'Error handling Outlook OAuth callback:',
2078
+ error.message,
2079
+ );
2080
+ throw new Error(`Failed to complete Outlook OAuth: ${error.message}`);
2081
+ }
2082
+ }
2083
+
2084
+ async getIntegrationConfigById(hubId: number): Promise<
2085
+ | (IntegrationConfig & {
2086
+ config: IntegrationConfig;
2087
+ linkedSource?: string;
2088
+ configDetails?: any;
2089
+ })
2090
+ | null
2091
+ > {
2092
+ try {
2093
+ // Find the integration config by ID
2094
+ const integrationConfig = await this.configRepository.findOne({
2095
+ where: { id: hubId },
2096
+ });
2097
+
2098
+ if (!integrationConfig) {
2099
+ return null;
2100
+ }
2101
+
2102
+ // Extract linked source and config details
2103
+ const linkedSource = this.extractLinkedSource(
2104
+ integrationConfig.integration_type,
2105
+ integrationConfig.integration_provider,
2106
+ integrationConfig.config_json,
2107
+ );
2108
+
2109
+ const configDetails = this.extractConfigDetails(
2110
+ integrationConfig.integration_type,
2111
+ integrationConfig.integration_provider,
2112
+ integrationConfig.config_json,
2113
+ );
2114
+
2115
+ return {
2116
+ ...integrationConfig,
2117
+ config: integrationConfig,
2118
+ linkedSource,
2119
+ configDetails,
2120
+ };
2121
+ } catch (error) {
2122
+ this.logger.error(
2123
+ `Error fetching communication config by ID ${hubId}:`,
2124
+ error.message,
2125
+ );
2126
+ throw new Error(
2127
+ `Failed to fetch communication configuration: ${error.message}`,
2128
+ );
2129
+ }
2130
+ }
2131
+
2132
+ async getIntegrationTemplates(
2133
+ levelId: number,
2134
+ levelType: string,
2135
+ app_code: string,
2136
+ integration_type: 'EMAIL' | 'SMS' | 'WA' | 'TELEPHONE',
2137
+ ): Promise<{
2138
+ success: boolean;
2139
+ data?: Array<{
2140
+ label: string;
2141
+ value: string;
2142
+ }>;
2143
+ error?: string;
2144
+ }> {
2145
+ try {
2146
+ // Get active configuration for the integration type
2147
+ const config = await this.getSingleActiveConfig(
2148
+ levelId,
2149
+ levelType,
2150
+ app_code,
2151
+ integration_type,
2152
+ );
2153
+
2154
+ if (!config) {
2155
+ return {
2156
+ success: false,
2157
+ error: `No active ${integration_type} configuration found for this level`,
2158
+ };
2159
+ }
2160
+
2161
+ // Create strategy instance
2162
+ const strategy = this.integrationFactory.create(
2163
+ config.integration_type,
2164
+ 'API',
2165
+ config.integration_provider,
2166
+ );
2167
+
2168
+ // Check if strategy supports getTemplates
2169
+ if (typeof (strategy as any).getTemplates !== 'function') {
2170
+ return {
2171
+ success: false,
2172
+ error: `Template retrieval not supported for provider: ${config.integration_provider}`,
2173
+ };
2174
+ }
2175
+
2176
+ // Call getTemplates method
2177
+ return await (strategy as any).getTemplates(config.config_json);
2178
+ } catch (error) {
2179
+ this.logger.error(
2180
+ `Error fetching templates for ${integration_type} level ${levelId}/${levelType}:`,
2181
+ error.message,
2182
+ );
2183
+ return {
2184
+ success: false,
2185
+ error: `Failed to fetch templates: ${error.message}`,
2186
+ };
2187
+ }
2188
+ }
2189
+
2190
+ async getSendGridTemplates(
2191
+ levelId: number,
2192
+ levelType: string,
2193
+ app_code: string,
2194
+ ): Promise<{
2195
+ success: boolean;
2196
+ data?: Array<{
2197
+ label: string;
2198
+ value: string;
2199
+ }>;
2200
+ error?: string;
2201
+ }> {
2202
+ try {
2203
+ // Find active SendGrid configurations for this level
2204
+ const hubs = await this.getActiveConfigs(
2205
+ levelId,
2206
+ levelType,
2207
+ app_code,
2208
+ 'EMAIL',
2209
+ );
2210
+
2211
+ // Look for SendGrid provider
2212
+ const sendGridHub = hubs.find(
2213
+ (hub) => hub.integration_provider === 'sendgrid',
2214
+ );
2215
+
2216
+ if (!sendGridHub) {
2217
+ return {
2218
+ success: false,
2219
+ error: 'No active SendGrid configuration found for this level',
2220
+ };
2221
+ }
2222
+
2223
+ // Extract API key from configuration
2224
+ const apiKey = sendGridHub.config_json?.apiKey;
2225
+
2226
+ if (!apiKey) {
2227
+ return {
2228
+ success: false,
2229
+ error: 'SendGrid API key not found in configuration',
2230
+ };
2231
+ }
2232
+
2233
+ // Use the SendGrid strategy to fetch templates
2234
+ return this.sendGridApiStrategy.getTemplates(apiKey);
2235
+ } catch (error) {
2236
+ this.logger.error(
2237
+ `Error fetching SendGrid templates for level ${levelId}/${levelType}:`,
2238
+ error.message,
2239
+ );
2240
+ return {
2241
+ success: false,
2242
+ error: `Failed to fetch SendGrid templates: ${error.message}`,
2243
+ };
2244
+ }
2245
+ }
2246
+
2247
+ async getSendGridVerifiedSenders(apiKey: string): Promise<{
2248
+ success: boolean;
2249
+ data?: Array<{
2250
+ label: string;
2251
+ value: string;
2252
+ }>;
2253
+ error?: string;
2254
+ }> {
2255
+ try {
2256
+ if (!apiKey) {
2257
+ return {
2258
+ success: false,
2259
+ error: 'SendGrid API key not found in configuration',
2260
+ };
2261
+ }
2262
+
2263
+ // Use the SendGrid strategy to fetch verified senders
2264
+ return this.sendGridApiStrategy.getVerifiedSenders(apiKey);
2265
+ } catch (error) {
2266
+ this.logger.error(
2267
+ `Error fetching SendGrid verified senders`,
2268
+ error.message,
2269
+ );
2270
+ return {
2271
+ success: false,
2272
+ error: `Failed to fetch SendGrid verified senders: ${error.message}`,
2273
+ };
2274
+ }
2275
+ }
2276
+
2277
+ // UserIntegration Management Methods
2278
+
2279
+ async createUserIntegration(
2280
+ createDto: CreateUserIntegrationDto,
2281
+ ): Promise<UserIntegration> {
2282
+ try {
2283
+ // Check if mapping already exists
2284
+ const existing = await this.userIntegrationRepository.findOne({
2285
+ where: {
2286
+ user_id: createDto.user_id,
2287
+ integration_config_id: createDto.integration_config_id,
2288
+ },
2289
+ });
2290
+
2291
+ if (existing) {
2292
+ throw new Error('User integration mapping already exists');
2293
+ }
2294
+
2295
+ // Verify integration config exists
2296
+ const config = await this.configRepository.findOne({
2297
+ where: { id: createDto.integration_config_id },
2298
+ });
2299
+
2300
+ if (!config) {
2301
+ throw new Error('Integration configuration not found');
2302
+ }
2303
+
2304
+ const userIntegration = this.userIntegrationRepository.create(createDto);
2305
+ return await this.userIntegrationRepository.save(userIntegration);
2306
+ } catch (error) {
2307
+ this.logger.error(
2308
+ `Error creating user integration mapping: ${error.message}`,
2309
+ );
2310
+ throw error;
2311
+ }
2312
+ }
2313
+
2314
+ async bulkCreateUserIntegration(
2315
+ bulkDto: BulkCreateUserIntegrationDto,
2316
+ ): Promise<{
2317
+ created: UserIntegration[];
2318
+ updated: UserIntegration[];
2319
+ failed: Array<{ data: CreateUserIntegrationDto; error: string }>;
2320
+ summary: {
2321
+ total: number;
2322
+ created: number;
2323
+ updated: number;
2324
+ failed: number;
2325
+ };
2326
+ }> {
2327
+ const created: UserIntegration[] = [];
2328
+ const updated: UserIntegration[] = [];
2329
+ const failed: Array<{ data: CreateUserIntegrationDto; error: string }> = [];
2330
+
2331
+ try {
2332
+ for (const createDto of bulkDto.user_integrations) {
2333
+ try {
2334
+ // Check if mapping already exists
2335
+ const existing = await this.userIntegrationRepository.findOne({
2336
+ where: {
2337
+ user_id: createDto.user_id,
2338
+ integration_config_id: createDto.integration_config_id,
2339
+ },
2340
+ });
2341
+
2342
+ if (existing) {
2343
+ // Update existing mapping
2344
+ if (createDto.external_user_id !== undefined) {
2345
+ existing.external_user_id = createDto.external_user_id;
2346
+ }
2347
+ if (createDto.external_user_data !== undefined) {
2348
+ existing.external_user_data = createDto.external_user_data;
2349
+ }
2350
+ if (createDto.is_active !== undefined) {
2351
+ existing.is_active = createDto.is_active;
2352
+ }
2353
+
2354
+ const updatedIntegration =
2355
+ await this.userIntegrationRepository.save(existing);
2356
+ updated.push(updatedIntegration);
2357
+
2358
+ this.logger.log(
2359
+ `Updated user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2360
+ );
2361
+ } else {
2362
+ // Verify integration config exists
2363
+ const config = await this.configRepository.findOne({
2364
+ where: { id: createDto.integration_config_id },
2365
+ });
2366
+
2367
+ if (!config) {
2368
+ failed.push({
2369
+ data: createDto,
2370
+ error: 'Integration configuration not found',
2371
+ });
2372
+ continue;
2373
+ }
2374
+
2375
+ // Create new mapping
2376
+ const userIntegration =
2377
+ this.userIntegrationRepository.create(createDto);
2378
+ const savedIntegration =
2379
+ await this.userIntegrationRepository.save(userIntegration);
2380
+ created.push(savedIntegration);
2381
+
2382
+ this.logger.log(
2383
+ `Created user integration mapping for user ${createDto.user_id} and config ${createDto.integration_config_id}`,
2384
+ );
2385
+ }
2386
+ } catch (error) {
2387
+ failed.push({
2388
+ data: createDto,
2389
+ error: error.message || 'Unknown error',
2390
+ });
2391
+ this.logger.error(
2392
+ `Error processing user integration for user ${createDto.user_id}: ${error.message}`,
2393
+ );
2394
+ }
2395
+ }
2396
+
2397
+ const summary = {
2398
+ total: bulkDto.user_integrations.length,
2399
+ created: created.length,
2400
+ updated: updated.length,
2401
+ failed: failed.length,
2402
+ };
2403
+
2404
+ this.logger.log(
2405
+ `Bulk user integration completed: ${summary.created} created, ${summary.updated} updated, ${summary.failed} failed`,
2406
+ );
2407
+
2408
+ return { created, updated, failed, summary };
2409
+ } catch (error) {
2410
+ this.logger.error(
2411
+ `Error in bulk user integration creation: ${error.message}`,
2412
+ );
2413
+ throw error;
2414
+ }
2415
+ }
2416
+
2417
+ async getUserIntegrations(userId: number): Promise<UserIntegration[]> {
2418
+ try {
2419
+ return await this.userIntegrationRepository.find({
2420
+ where: { user_id: userId, is_active: true },
2421
+ order: { created_at: 'DESC' },
2422
+ });
2423
+ } catch (error) {
2424
+ this.logger.error(
2425
+ `Error fetching user integrations for user ${userId}: ${error.message}`,
2426
+ );
2427
+ throw error;
2428
+ }
2429
+ }
2430
+
2431
+ async getConfigUserIntegrations(
2432
+ configId: number,
2433
+ ): Promise<UserIntegration[]> {
2434
+ try {
2435
+ return await this.userIntegrationRepository.find({
2436
+ where: { integration_config_id: configId, is_active: true },
2437
+ order: { created_at: 'DESC' },
2438
+ });
2439
+ } catch (error) {
2440
+ this.logger.error(
2441
+ `Error fetching user integrations for config ${configId}: ${error.message}`,
2442
+ );
2443
+ throw error;
2444
+ }
2445
+ }
2446
+
2447
+ async getUserIntegrationByUserAndConfig(
2448
+ userId: number,
2449
+ configId: number,
2450
+ ): Promise<UserIntegration | null> {
2451
+ try {
2452
+ return await this.userIntegrationRepository.findOne({
2453
+ where: {
2454
+ user_id: userId,
2455
+ integration_config_id: configId,
2456
+ is_active: true,
2457
+ },
2458
+ });
2459
+ } catch (error) {
2460
+ this.logger.error(
2461
+ `Error fetching user integration for user ${userId} and config ${configId}: ${error.message}`,
2462
+ );
2463
+ throw error;
2464
+ }
2465
+ }
2466
+
2467
+ async updateUserIntegration(
2468
+ id: number,
2469
+ updateDto: UpdateUserIntegrationDto,
2470
+ ): Promise<UserIntegration> {
2471
+ try {
2472
+ const userIntegration = await this.userIntegrationRepository.findOne({
2473
+ where: { id },
2474
+ });
2475
+
2476
+ if (!userIntegration) {
2477
+ throw new Error('User integration mapping not found');
2478
+ }
2479
+
2480
+ Object.assign(userIntegration, updateDto);
2481
+ return await this.userIntegrationRepository.save(userIntegration);
2482
+ } catch (error) {
2483
+ this.logger.error(
2484
+ `Error updating user integration ${id}: ${error.message}`,
2485
+ );
2486
+ throw error;
2487
+ }
2488
+ }
2489
+
2490
+ async deleteUserIntegration(id: number): Promise<void> {
2491
+ try {
2492
+ const userIntegration = await this.userIntegrationRepository.findOne({
2493
+ where: { id },
2494
+ });
2495
+
2496
+ if (!userIntegration) {
2497
+ throw new Error('User integration mapping not found');
2498
+ }
2499
+
2500
+ await this.userIntegrationRepository.remove(userIntegration);
2501
+ } catch (error) {
2502
+ this.logger.error(
2503
+ `Error deleting user integration ${id}: ${error.message}`,
2504
+ );
2505
+ throw error;
2506
+ }
2507
+ }
2508
+
2509
+ /**
2510
+ * Get user integration data for a specific integration strategy
2511
+ * This method is intended to be used by strategies that need user mapping
2512
+ */
2513
+ async getUserIntegrationForStrategy(
2514
+ userId: number,
2515
+ integrationConfigId: number,
2516
+ ): Promise<any | null> {
2517
+ try {
2518
+ const userIntegration = await this.getUserIntegrationByUserAndConfig(
2519
+ userId,
2520
+ integrationConfigId,
2521
+ );
2522
+
2523
+ if (!userIntegration) {
2524
+ return null;
2525
+ }
2526
+
2527
+ return {
2528
+ external_user_id: userIntegration.external_user_id,
2529
+ external_user_data: userIntegration.external_user_data,
2530
+ };
2531
+ } catch (error) {
2532
+ this.logger.error(
2533
+ `Error fetching user integration data for strategy: ${error.message}`,
2534
+ );
2535
+ return null;
2536
+ }
2537
+ }
2538
+
2539
+ /**
2540
+ * Check agent status for TELEPHONE integration
2541
+ * Works with any provider that implements checkAgentStatus method
2542
+ */
2543
+ async checkAgentStatus(
2544
+ levelId: number,
2545
+ levelType: string,
2546
+ appCode: string,
2547
+ userId: number,
2548
+ integrationType: 'TELEPHONE' = 'TELEPHONE',
2549
+ ): Promise<{
2550
+ success: boolean;
2551
+ isReady?: boolean;
2552
+ state?: string;
2553
+ agentInfo?: any;
2554
+ error?: string;
2555
+ }> {
2556
+ try {
2557
+ // Get the active configuration
2558
+ const config = await this.getSingleActiveConfig(
2559
+ levelId,
2560
+ levelType,
2561
+ appCode,
2562
+ integrationType,
2563
+ );
2564
+
2565
+ if (!config) {
2566
+ return {
2567
+ success: false,
2568
+ error: 'No active TELEPHONE configuration found',
2569
+ };
2570
+ }
2571
+
2572
+ // Get user integration mapping
2573
+ const userIntegration = await this.getUserIntegrationByUserAndConfig(
2574
+ userId,
2575
+ config.id,
2576
+ );
2577
+
2578
+ if (!userIntegration) {
2579
+ return {
2580
+ success: false,
2581
+ error:
2582
+ 'User integration mapping not found. Please configure agent details.',
2583
+ };
2584
+ }
2585
+
2586
+ // Create strategy instance
2587
+ const strategy = this.integrationFactory.create(
2588
+ config.integration_type,
2589
+ 'API', // service is deprecated, using default
2590
+ config.integration_provider,
2591
+ );
2592
+
2593
+ // Get the merged config with user data
2594
+ let mergedConfig = config.config_json;
2595
+
2596
+ if (strategy.createUserSpecificConfig) {
2597
+ mergedConfig = strategy.createUserSpecificConfig(
2598
+ config.config_json,
2599
+ userIntegration.external_user_id,
2600
+ );
2601
+ }
2602
+
2603
+ // Check if strategy supports agent status check
2604
+ if (typeof (strategy as any).checkAgentStatus !== 'function') {
2605
+ return {
2606
+ success: false,
2607
+ error: `Agent status check not supported for provider: ${config.integration_provider}`,
2608
+ };
2609
+ }
2610
+
2611
+ // Check agent status
2612
+ const statusResult = await (strategy as any).checkAgentStatus(
2613
+ mergedConfig,
2614
+ );
2615
+
2616
+ return {
2617
+ success: true,
2618
+ isReady: statusResult.isReady,
2619
+ state: statusResult.state,
2620
+ error: statusResult.error,
2621
+ };
2622
+ } catch (error) {
2623
+ this.logger.error(
2624
+ `Error checking agent status: ${error.message}`,
2625
+ error.stack,
2626
+ );
2627
+ return {
2628
+ success: false,
2629
+ error: error.message || 'Failed to check agent status',
2630
+ };
2631
+ }
2632
+ }
2633
+ }