rez_core 6.1.5 → 6.1.7

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