rez_core 5.0.211 → 6.1.1

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 (458) hide show
  1. package/.prettierrc +3 -3
  2. package/README.md +99 -99
  3. package/dist/config/database.config.js +1 -1
  4. package/dist/config/database.config.js.map +1 -1
  5. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.d.ts +6 -0
  6. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js +32 -0
  7. package/dist/migrations/1732612800000-AddEntityJsonGinIndex.js.map +1 -0
  8. package/dist/module/auth/guards/role.guard.js +3 -3
  9. package/dist/module/entity_json/controller/entity_json.controller.d.ts +2 -9
  10. package/dist/module/entity_json/controller/entity_json.controller.js.map +1 -1
  11. package/dist/module/entity_json/entity/entityJson.entity.d.ts +2 -1
  12. package/dist/module/entity_json/entity/entityJson.entity.js +5 -1
  13. package/dist/module/entity_json/entity/entityJson.entity.js.map +1 -1
  14. package/dist/module/entity_json/entity_json.module.js +7 -2
  15. package/dist/module/entity_json/entity_json.module.js.map +1 -1
  16. package/dist/module/entity_json/service/entity_json.service.d.ts +5 -12
  17. package/dist/module/entity_json/service/entity_json.service.js +111 -29
  18. package/dist/module/entity_json/service/entity_json.service.js.map +1 -1
  19. package/dist/module/filter/controller/filter.controller.d.ts +12 -0
  20. package/dist/module/filter/controller/filter.controller.js +1 -1
  21. package/dist/module/filter/controller/filter.controller.js.map +1 -1
  22. package/dist/module/filter/filter.module.js +11 -2
  23. package/dist/module/filter/filter.module.js.map +1 -1
  24. package/dist/module/filter/service/filter.service.d.ts +38 -2
  25. package/dist/module/filter/service/filter.service.js +61 -68
  26. package/dist/module/filter/service/filter.service.js.map +1 -1
  27. package/dist/module/filter/service/flatjson-filter.service.d.ts +32 -0
  28. package/dist/module/filter/service/flatjson-filter.service.js +632 -0
  29. package/dist/module/filter/service/flatjson-filter.service.js.map +1 -0
  30. package/dist/module/filter/service/saved-filter.service.d.ts +3 -2
  31. package/dist/module/filter/service/saved-filter.service.js +14 -18
  32. package/dist/module/filter/service/saved-filter.service.js.map +1 -1
  33. package/dist/module/integration/examples/usage.example.js +9 -9
  34. package/dist/module/linked_attributes/controller/linked_attributes.controller.d.ts +19 -0
  35. package/dist/module/linked_attributes/controller/linked_attributes.controller.js +77 -0
  36. package/dist/module/linked_attributes/controller/linked_attributes.controller.js.map +1 -1
  37. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.d.ts +13 -0
  38. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js +64 -0
  39. package/dist/module/linked_attributes/dto/create-linked-attribute-smart.dto.js.map +1 -0
  40. package/dist/module/linked_attributes/linked_attributes.module.js +4 -2
  41. package/dist/module/linked_attributes/linked_attributes.module.js.map +1 -1
  42. package/dist/module/linked_attributes/service/linked_attributes.service.d.ts +41 -1
  43. package/dist/module/linked_attributes/service/linked_attributes.service.js +265 -1
  44. package/dist/module/linked_attributes/service/linked_attributes.service.js.map +1 -1
  45. package/dist/module/meta/controller/attribute-master.controller.d.ts +3 -0
  46. package/dist/module/meta/controller/attribute-master.controller.js +12 -0
  47. package/dist/module/meta/controller/attribute-master.controller.js.map +1 -1
  48. package/dist/module/meta/entity.module.js +2 -2
  49. package/dist/module/meta/entity.module.js.map +1 -1
  50. package/dist/module/meta/repository/attribute-master.repository.js +8 -8
  51. package/dist/module/meta/service/attribute-master.service.d.ts +6 -1
  52. package/dist/module/meta/service/attribute-master.service.js +20 -2
  53. package/dist/module/meta/service/attribute-master.service.js.map +1 -1
  54. package/dist/module/meta/service/entity-dynamic.service.js +16 -16
  55. package/dist/module/meta/service/entity-master.service.js +1 -0
  56. package/dist/module/meta/service/entity-master.service.js.map +1 -1
  57. package/dist/module/meta/service/entity-relation.service.d.ts +4 -3
  58. package/dist/module/meta/service/entity-relation.service.js +10 -4
  59. package/dist/module/meta/service/entity-relation.service.js.map +1 -1
  60. package/dist/module/meta/service/entity-service-impl.service.d.ts +1 -1
  61. package/dist/module/meta/service/entity-service-impl.service.js +2 -2
  62. package/dist/module/meta/service/entity-service-impl.service.js.map +1 -1
  63. package/dist/module/meta/service/entity-table.service.d.ts +5 -4
  64. package/dist/module/meta/service/entity-table.service.js +45 -24
  65. package/dist/module/meta/service/entity-table.service.js.map +1 -1
  66. package/dist/module/meta/service/media-data.service.js +6 -6
  67. package/dist/module/meta/service/resolver.service.d.ts +1 -1
  68. package/dist/module/meta/service/resolver.service.js +11 -8
  69. package/dist/module/meta/service/resolver.service.js.map +1 -1
  70. package/dist/module/module/repository/menu.repository.js +4 -4
  71. package/dist/module/user/controller/login.controller.js +18 -18
  72. package/dist/module/workflow/repository/action.repository.js +2 -2
  73. package/dist/module/workflow/repository/stage.repository.js +8 -8
  74. package/dist/module/workflow/service/action-template-mapping.service.js +2 -2
  75. package/dist/module/workflow/service/action.service.js +5 -5
  76. package/dist/module/workflow/service/entity-modification.service.js +2 -2
  77. package/dist/module/workflow/service/task.service.js +8 -8
  78. package/dist/module/workflow-automation/service/schedule-handler.service.js +9 -9
  79. package/dist/module/workflow-automation/service/workflow-automation.service.js +2 -3
  80. package/dist/module/workflow-automation/service/workflow-automation.service.js.map +1 -1
  81. package/dist/table.config.d.ts +2 -1
  82. package/dist/table.config.js +2 -0
  83. package/dist/table.config.js.map +1 -1
  84. package/dist/tsconfig.build.tsbuildinfo +1 -1
  85. package/dist/utils/service/reflection-helper.service.js +2 -2
  86. package/docs/modules/event-driven-integration-design.md +91 -91
  87. package/docs/modules/integration.md +250 -250
  88. package/eslint.config.mjs +34 -34
  89. package/nest-cli.json +14 -14
  90. package/package.json +125 -125
  91. package/src/app.controller.ts +12 -12
  92. package/src/app.module.ts +68 -68
  93. package/src/app.service.ts +8 -8
  94. package/src/config/bull.config.ts +69 -69
  95. package/src/config/config.module.ts +17 -17
  96. package/src/config/database.config.ts +48 -48
  97. package/src/constant/global.constant.ts +67 -67
  98. package/src/core.module.ts +94 -94
  99. package/src/decorators/roles.decorator.ts +7 -7
  100. package/src/dtos/response.dto.ts +6 -6
  101. package/src/dtos/response.ts +5 -5
  102. package/src/index.ts +1 -1
  103. package/src/migrations/1732612800000-AddEntityJsonGinIndex.ts +41 -0
  104. package/src/module/auth/auth.module.ts +49 -49
  105. package/src/module/auth/controller/auth.controller.ts +28 -28
  106. package/src/module/auth/guards/google-auth.guard.ts +9 -9
  107. package/src/module/auth/guards/jwt.guard.ts +22 -22
  108. package/src/module/auth/guards/role.guard.ts +68 -68
  109. package/src/module/auth/services/auth.service.ts +56 -56
  110. package/src/module/auth/services/jwt.service.ts +11 -11
  111. package/src/module/auth/strategies/google.strategy.ts +54 -54
  112. package/src/module/auth/strategies/jwt.strategy.ts +58 -58
  113. package/src/module/auth/strategies/local.strategy.ts +13 -13
  114. package/src/module/dashboard/controller/dashboard.controller.ts +38 -38
  115. package/src/module/dashboard/dashboard.module.ts +21 -21
  116. package/src/module/dashboard/entity/dashboard_page_data.entity.ts +27 -27
  117. package/src/module/dashboard/entity/widget_master.entity.ts +18 -18
  118. package/src/module/dashboard/repository/dashboard.repository.ts +49 -49
  119. package/src/module/dashboard/service/dashboard.service.ts +72 -72
  120. package/src/module/enterprise/controller/organization.controller.ts +36 -36
  121. package/src/module/enterprise/enterprise.module.ts +45 -45
  122. package/src/module/enterprise/entity/enterprise.entity.ts +37 -37
  123. package/src/module/enterprise/entity/organization-app-mapping.entity.ts +13 -13
  124. package/src/module/enterprise/entity/organization.entity.ts +92 -92
  125. package/src/module/enterprise/repository/enterprise.repository.ts +31 -31
  126. package/src/module/enterprise/repository/organization.repository.ts +26 -26
  127. package/src/module/enterprise/repository/school.repository.ts +289 -289
  128. package/src/module/enterprise/service/brand.service.ts +5 -5
  129. package/src/module/enterprise/service/enterprise.service.ts +16 -16
  130. package/src/module/enterprise/service/organization-app-mapping.service.ts +4 -4
  131. package/src/module/enterprise/service/organization.service.ts +145 -145
  132. package/src/module/entity_json/controller/entity_json.controller.ts +60 -47
  133. package/src/module/entity_json/docs/FlatJson_Filterin_System.md +2804 -0
  134. package/src/module/entity_json/entity/entityJson.entity.ts +42 -39
  135. package/src/module/entity_json/entity_json.module.ts +22 -18
  136. package/src/module/entity_json/service/entityJson.repository.ts +37 -37
  137. package/src/module/entity_json/service/entity_json.service.ts +428 -241
  138. package/src/module/export/controller/export.controller.ts +83 -83
  139. package/src/module/export/export.module.ts +14 -14
  140. package/src/module/export/service/export.service.ts +105 -105
  141. package/src/module/filter/controller/filter.controller.ts +87 -87
  142. package/src/module/filter/dto/filter-request.dto.ts +39 -39
  143. package/src/module/filter/entity/saved-filter-detail.entity.ts +41 -41
  144. package/src/module/filter/entity/saved-filter-master.entity.ts +35 -35
  145. package/src/module/filter/filter.module.ts +42 -33
  146. package/src/module/filter/repository/saved-filter.repository.ts +247 -247
  147. package/src/module/filter/repository/saved.filter-detail.repository.ts +19 -19
  148. package/src/module/filter/service/filter-evaluator.service.ts +82 -82
  149. package/src/module/filter/service/filter.service.ts +1369 -1310
  150. package/src/module/filter/service/flatjson-filter.service.ts +903 -0
  151. package/src/module/filter/service/saved-filter.service.ts +154 -164
  152. package/src/module/filter/test/flatjson-filter.service.spec.ts +415 -0
  153. package/src/module/ics/controller/ics.controller.ts +21 -21
  154. package/src/module/ics/dto/ics.dto.ts +55 -55
  155. package/src/module/ics/ics.module.ts +13 -13
  156. package/src/module/ics/service/ics.service.ts +57 -57
  157. package/src/module/integration/controller/calender-event.controller.ts +31 -31
  158. package/src/module/integration/controller/integration.controller.ts +662 -662
  159. package/src/module/integration/controller/wrapper.controller.ts +37 -37
  160. package/src/module/integration/dto/create-config.dto.ts +526 -526
  161. package/src/module/integration/entity/integration-config.entity.ts +112 -112
  162. package/src/module/integration/entity/integration-entity-mapper.entity.ts +14 -14
  163. package/src/module/integration/entity/integration-source.entity.ts +17 -17
  164. package/src/module/integration/entity/user-integration.entity.ts +71 -71
  165. package/src/module/integration/examples/usage.example.ts +338 -338
  166. package/src/module/integration/factories/base.factory.ts +7 -7
  167. package/src/module/integration/factories/email.factory.ts +49 -49
  168. package/src/module/integration/factories/integration.factory.ts +121 -121
  169. package/src/module/integration/factories/sms.factory.ts +51 -51
  170. package/src/module/integration/factories/telephone.factory.ts +41 -41
  171. package/src/module/integration/factories/whatsapp.factory.ts +56 -56
  172. package/src/module/integration/integration.module.ts +110 -110
  173. package/src/module/integration/service/calendar-event.service.ts +118 -118
  174. package/src/module/integration/service/integration-entity-mapper.service.ts +17 -17
  175. package/src/module/integration/service/integration-queue.service.ts +229 -229
  176. package/src/module/integration/service/integration.service.ts +2639 -2639
  177. package/src/module/integration/service/oauth.service.ts +224 -224
  178. package/src/module/integration/service/wrapper.service.ts +754 -754
  179. package/src/module/integration/strategies/email/gmail-api.strategy.ts +280 -280
  180. package/src/module/integration/strategies/email/outlook-api.strategy.ts +44 -44
  181. package/src/module/integration/strategies/email/outlook.strategy.ts +64 -64
  182. package/src/module/integration/strategies/email/sendgrid-api.strategy.ts +260 -260
  183. package/src/module/integration/strategies/integration.strategy.ts +97 -97
  184. package/src/module/integration/strategies/sms/gupshup-sms.strategy.ts +146 -146
  185. package/src/module/integration/strategies/sms/msg91-sms.strategy.ts +164 -164
  186. package/src/module/integration/strategies/sms/tubelight-sms.strategy.ts +163 -163
  187. package/src/module/integration/strategies/telephone/ozonetel-voice.strategy.ts +238 -238
  188. package/src/module/integration/strategies/telephone/tubelight-voice.strategy.ts +210 -210
  189. package/src/module/integration/strategies/whatsapp/gupshup-whatsapp.strategy.ts +359 -359
  190. package/src/module/integration/strategies/whatsapp/tubelight-whatsapp.strategy.ts +372 -372
  191. package/src/module/integration/strategies/whatsapp/whatsapp-cloud.strategy.ts +403 -403
  192. package/src/module/integration/strategies/whatsapp/whatsapp.strategy.ts +57 -57
  193. package/src/module/layout/controller/layout.controller.ts +47 -47
  194. package/src/module/layout/entity/header-items.entity.ts +28 -28
  195. package/src/module/layout/entity/header-section.entity.ts +19 -19
  196. package/src/module/layout/layout.module.ts +21 -21
  197. package/src/module/layout/repository/header-items.repository.ts +18 -18
  198. package/src/module/layout/repository/header-section.repository.ts +22 -22
  199. package/src/module/layout/service/header-section.service.ts +25 -25
  200. package/src/module/layout_preference/controller/layout_preference.controller.ts +76 -76
  201. package/src/module/layout_preference/entity/layout_preference.entity.ts +28 -28
  202. package/src/module/layout_preference/layout_preference.module.ts +22 -22
  203. package/src/module/layout_preference/repository/layout_preference.repository.ts +65 -65
  204. package/src/module/layout_preference/service/layout_preference.service.ts +191 -191
  205. package/src/module/lead/controller/lead.controller.ts +30 -30
  206. package/src/module/lead/lead.module.ts +14 -14
  207. package/src/module/lead/repository/lead.repository.ts +41 -41
  208. package/src/module/lead/service/lead.service.ts +54 -54
  209. package/src/module/linked_attributes/controller/linked_attributes.controller.ts +137 -52
  210. package/src/module/linked_attributes/dto/create-linked-attribute-smart.dto.ts +54 -0
  211. package/src/module/linked_attributes/entity/linked_attribute.entity.ts +51 -51
  212. package/src/module/linked_attributes/linked_attributes.module.ts +23 -21
  213. package/src/module/linked_attributes/repository/linked_attribute.repository.ts +12 -12
  214. package/src/module/linked_attributes/service/linked_attributes.service.ts +648 -105
  215. package/src/module/linked_attributes/test/linked-attributes.service.spec.ts +244 -0
  216. package/src/module/listmaster/controller/list-master.controller.ts +230 -230
  217. package/src/module/listmaster/entity/list-master-items.entity.ts +43 -43
  218. package/src/module/listmaster/entity/list-master.entity.ts +33 -33
  219. package/src/module/listmaster/listmaster.module.ts +46 -46
  220. package/src/module/listmaster/repository/list-master-items.repository.ts +173 -173
  221. package/src/module/listmaster/repository/list-master.repository.ts +56 -56
  222. package/src/module/listmaster/service/list-master-engine.ts +19 -19
  223. package/src/module/listmaster/service/list-master-extension.interface.ts +4 -4
  224. package/src/module/listmaster/service/list-master-item.service.ts +280 -280
  225. package/src/module/listmaster/service/list-master-registry.ts +15 -15
  226. package/src/module/listmaster/service/list-master.service.ts +527 -527
  227. package/src/module/mapper/controller/field-mapper.controller.ts +76 -76
  228. package/src/module/mapper/controller/mapper.controller.ts +20 -20
  229. package/src/module/mapper/dto/field-mapper.dto.ts +14 -14
  230. package/src/module/mapper/entity/field-lovs.entity.ts +19 -19
  231. package/src/module/mapper/entity/field-mapper.entity.ts +53 -53
  232. package/src/module/mapper/entity/mapper.entity.ts +16 -16
  233. package/src/module/mapper/mapper.module.ts +35 -35
  234. package/src/module/mapper/repository/field-lovs.repository.ts +35 -35
  235. package/src/module/mapper/repository/field-mapper.repository.ts +42 -42
  236. package/src/module/mapper/repository/mapper.repository.ts +32 -32
  237. package/src/module/mapper/service/field-mapper.service.ts +269 -269
  238. package/src/module/mapper/service/mapper.service.ts +80 -80
  239. package/src/module/master/controller/master.controller.ts +74 -74
  240. package/src/module/master/service/master.service.ts +484 -484
  241. package/src/module/meta/controller/app-master.controller.ts +38 -38
  242. package/src/module/meta/controller/attribute-master.controller.ts +96 -84
  243. package/src/module/meta/controller/entity-dynamic.controller.ts +125 -125
  244. package/src/module/meta/controller/entity-master.controller.ts +41 -41
  245. package/src/module/meta/controller/entity-relation.controller.ts +36 -36
  246. package/src/module/meta/controller/entity.controller.ts +308 -308
  247. package/src/module/meta/controller/entity.public.controller.ts +75 -75
  248. package/src/module/meta/controller/media.controller.ts +135 -135
  249. package/src/module/meta/controller/meta.controller.ts +101 -101
  250. package/src/module/meta/controller/view-master.controller.ts +79 -79
  251. package/src/module/meta/dto/entity-list-data.dto.ts +6 -6
  252. package/src/module/meta/dto/entity-tab.dto.ts +4 -4
  253. package/src/module/meta/dto/entity-table.dto.ts +12 -12
  254. package/src/module/meta/entity/app-master.entity.ts +37 -37
  255. package/src/module/meta/entity/attribute-master.entity.ts +92 -92
  256. package/src/module/meta/entity/base-entity.entity.ts +75 -75
  257. package/src/module/meta/entity/entity-master.entity.ts +91 -91
  258. package/src/module/meta/entity/entity-relation-data.entity.ts +29 -29
  259. package/src/module/meta/entity/entity-relation.entity.ts +23 -23
  260. package/src/module/meta/entity/entity-table-column.entity.ts +61 -61
  261. package/src/module/meta/entity/entity-table.entity.ts +50 -50
  262. package/src/module/meta/entity/media-data.entity.ts +32 -32
  263. package/src/module/meta/entity/preference.entity.ts +62 -62
  264. package/src/module/meta/entity/view-master.entity.ts +41 -41
  265. package/src/module/meta/entity.module.ts +165 -165
  266. package/src/module/meta/repository/app-master.repository.ts +20 -20
  267. package/src/module/meta/repository/attribute-master.repository.ts +164 -164
  268. package/src/module/meta/repository/entity-attribute-update.repository.ts +48 -48
  269. package/src/module/meta/repository/entity-master.repository.ts +120 -120
  270. package/src/module/meta/repository/entity-relation.repository.ts +22 -22
  271. package/src/module/meta/repository/entity-table-column.repository.ts +39 -39
  272. package/src/module/meta/repository/entity-table.repository.ts +53 -53
  273. package/src/module/meta/repository/media-data.repository.ts +50 -50
  274. package/src/module/meta/repository/preference.repository.ts +20 -20
  275. package/src/module/meta/repository/user-app-mapping.repository.ts +28 -28
  276. package/src/module/meta/repository/view-master.repository.ts +42 -42
  277. package/src/module/meta/service/app-master.service.ts +37 -37
  278. package/src/module/meta/service/attribute-master.service.ts +160 -132
  279. package/src/module/meta/service/common.service.ts +9 -9
  280. package/src/module/meta/service/entity-attribute-update.service.ts +26 -26
  281. package/src/module/meta/service/entity-dynamic.service.ts +824 -824
  282. package/src/module/meta/service/entity-master.service.ts +172 -171
  283. package/src/module/meta/service/entity-realation-data.service.ts +9 -9
  284. package/src/module/meta/service/entity-relation.service.ts +78 -74
  285. package/src/module/meta/service/entity-service-impl.service.ts +389 -388
  286. package/src/module/meta/service/entity-table-column.service.ts +26 -26
  287. package/src/module/meta/service/entity-table.service.ts +171 -157
  288. package/src/module/meta/service/entity-validation.service.ts +188 -188
  289. package/src/module/meta/service/entity.service.ts +48 -49
  290. package/src/module/meta/service/field-group.service.ts +103 -103
  291. package/src/module/meta/service/media-data.service.ts +591 -591
  292. package/src/module/meta/service/populate-meta.service.ts +222 -222
  293. package/src/module/meta/service/preference.service.ts +16 -16
  294. package/src/module/meta/service/resolver.service.ts +319 -315
  295. package/src/module/meta/service/section-master.service.ts +104 -104
  296. package/src/module/meta/service/update-form-json.service.ts +22 -22
  297. package/src/module/meta/service/user-app-mapping.service.ts +17 -17
  298. package/src/module/meta/service/view-master.service.ts +127 -127
  299. package/src/module/microservice-client/microservice-clients.module.ts +13 -13
  300. package/src/module/microservice-client/service/microservice-client-factory.ts +37 -37
  301. package/src/module/microservice-client/service/microservice-clients.ts +4 -4
  302. package/src/module/module/controller/menu.controller.ts +15 -15
  303. package/src/module/module/controller/module-access.controller.ts +133 -133
  304. package/src/module/module/entity/menu.entity.ts +43 -43
  305. package/src/module/module/entity/module-access.entity.ts +25 -25
  306. package/src/module/module/entity/module-action.entity.ts +17 -17
  307. package/src/module/module/entity/module.entity.ts +52 -52
  308. package/src/module/module/module.module.ts +42 -42
  309. package/src/module/module/repository/menu.repository.ts +186 -186
  310. package/src/module/module/repository/module-access.repository.ts +344 -344
  311. package/src/module/module/service/menu.service.ts +82 -82
  312. package/src/module/module/service/module-access.service.ts +189 -189
  313. package/src/module/notification/controller/notification.controller.ts +58 -58
  314. package/src/module/notification/controller/otp.controller.ts +117 -117
  315. package/src/module/notification/entity/notification.entity.ts +26 -26
  316. package/src/module/notification/entity/otp.entity.ts +28 -28
  317. package/src/module/notification/firebase-admin.config.ts +22 -22
  318. package/src/module/notification/notification.module.ts +71 -71
  319. package/src/module/notification/repository/notification.repository.ts +33 -33
  320. package/src/module/notification/repository/otp.repository.ts +27 -27
  321. package/src/module/notification/service/email.service.ts +127 -127
  322. package/src/module/notification/service/notification.service.ts +146 -146
  323. package/src/module/notification/service/otp.service.ts +133 -133
  324. package/src/module/third-party-module/entity/third-party-api-registry.entity.ts +52 -52
  325. package/src/module/third-party-module/repository/third-party-api-registry.repository.ts +20 -20
  326. package/src/module/third-party-module/service/api-registry.service.ts +13 -13
  327. package/src/module/third-party-module/third-party.module.ts +12 -12
  328. package/src/module/user/controller/login.controller.ts +198 -198
  329. package/src/module/user/controller/user.controller.ts +40 -40
  330. package/src/module/user/dto/create-user.dto.ts +62 -62
  331. package/src/module/user/dto/update-user.dto.ts +4 -4
  332. package/src/module/user/entity/role.entity.ts +33 -33
  333. package/src/module/user/entity/user-role-mapping.entity.ts +38 -38
  334. package/src/module/user/entity/user-session.entity.ts +73 -73
  335. package/src/module/user/entity/user.entity.ts +62 -62
  336. package/src/module/user/repository/role.repository.ts +96 -96
  337. package/src/module/user/repository/user-role-mapping.repository.ts +126 -126
  338. package/src/module/user/repository/user.repository.ts +50 -50
  339. package/src/module/user/repository/userSession.repository.ts +33 -33
  340. package/src/module/user/service/login.service.ts +326 -326
  341. package/src/module/user/service/role.service.ts +197 -197
  342. package/src/module/user/service/user-role-mapping.service.ts +98 -98
  343. package/src/module/user/service/user-session.service.ts +200 -200
  344. package/src/module/user/service/user.service.ts +368 -368
  345. package/src/module/user/user.module.ts +65 -65
  346. package/src/module/workflow/controller/action-category.controller.ts +54 -54
  347. package/src/module/workflow/controller/action-resource-mapping.controller.ts +23 -23
  348. package/src/module/workflow/controller/action-template-mapping.controller.ts +35 -35
  349. package/src/module/workflow/controller/action.controller.ts +111 -111
  350. package/src/module/workflow/controller/activity-log.controller.ts +55 -55
  351. package/src/module/workflow/controller/comm-template.controller.ts +43 -43
  352. package/src/module/workflow/controller/entity-modification.controller.ts +35 -35
  353. package/src/module/workflow/controller/form-master.controller.ts +43 -43
  354. package/src/module/workflow/controller/stage-group.controller.ts +49 -49
  355. package/src/module/workflow/controller/stage.controller.ts +51 -51
  356. package/src/module/workflow/controller/task.controller.ts +77 -77
  357. package/src/module/workflow/controller/workflow-list-master.controller.ts +44 -44
  358. package/src/module/workflow/controller/workflow-meta.controller.ts +80 -80
  359. package/src/module/workflow/controller/workflow.controller.ts +67 -67
  360. package/src/module/workflow/entity/action-category.entity.ts +38 -38
  361. package/src/module/workflow/entity/action-data.entity.ts +55 -55
  362. package/src/module/workflow/entity/action-resources-mapping.entity.ts +29 -29
  363. package/src/module/workflow/entity/action-template-mapping.entity.ts +17 -17
  364. package/src/module/workflow/entity/action.entity.ts +53 -53
  365. package/src/module/workflow/entity/activity-log.entity.ts +43 -43
  366. package/src/module/workflow/entity/comm-template.entity.ts +43 -43
  367. package/src/module/workflow/entity/entity-modification.entity.ts +38 -38
  368. package/src/module/workflow/entity/form.entity.ts +25 -25
  369. package/src/module/workflow/entity/stage-action-mapping.entity.ts +17 -17
  370. package/src/module/workflow/entity/stage-group.entity.ts +23 -23
  371. package/src/module/workflow/entity/stage-movement-data.entity.ts +38 -38
  372. package/src/module/workflow/entity/stage.entity.ts +20 -20
  373. package/src/module/workflow/entity/task-data.entity.ts +88 -88
  374. package/src/module/workflow/entity/template-attach-mapper.entity.ts +30 -30
  375. package/src/module/workflow/entity/workflow-data.entity.ts +11 -11
  376. package/src/module/workflow/entity/workflow-level-mapping.entity.ts +18 -18
  377. package/src/module/workflow/entity/workflow.entity.ts +20 -20
  378. package/src/module/workflow/repository/action-category.repository.ts +79 -79
  379. package/src/module/workflow/repository/action-data.repository.ts +354 -354
  380. package/src/module/workflow/repository/action.repository.ts +339 -339
  381. package/src/module/workflow/repository/activity-log.repository.ts +148 -148
  382. package/src/module/workflow/repository/comm-template.repository.ts +157 -157
  383. package/src/module/workflow/repository/form-master.repository.ts +50 -50
  384. package/src/module/workflow/repository/stage-group.repository.ts +186 -186
  385. package/src/module/workflow/repository/stage-movement.repository.ts +217 -217
  386. package/src/module/workflow/repository/stage.repository.ts +160 -160
  387. package/src/module/workflow/repository/task.repository.ts +156 -156
  388. package/src/module/workflow/repository/workflow.repository.ts +42 -42
  389. package/src/module/workflow/service/action-category.service.ts +33 -33
  390. package/src/module/workflow/service/action-data.service.ts +62 -62
  391. package/src/module/workflow/service/action-resources-mapping.service.ts +10 -10
  392. package/src/module/workflow/service/action-template-mapping.service.ts +137 -137
  393. package/src/module/workflow/service/action.service.ts +302 -302
  394. package/src/module/workflow/service/activity-log.service.ts +107 -107
  395. package/src/module/workflow/service/comm-template.service.ts +181 -181
  396. package/src/module/workflow/service/entity-modification.service.ts +61 -61
  397. package/src/module/workflow/service/form-master.service.ts +35 -35
  398. package/src/module/workflow/service/populate-workflow.service.ts +320 -320
  399. package/src/module/workflow/service/stage-action-mapping.service.ts +5 -5
  400. package/src/module/workflow/service/stage-group.service.ts +325 -325
  401. package/src/module/workflow/service/stage.service.ts +197 -197
  402. package/src/module/workflow/service/task.service.ts +551 -551
  403. package/src/module/workflow/service/workflow-list-master.service.ts +68 -68
  404. package/src/module/workflow/service/workflow-meta.service.ts +640 -640
  405. package/src/module/workflow/service/workflow.service.ts +213 -213
  406. package/src/module/workflow/workflow.module.ts +180 -180
  407. package/src/module/workflow-automation/SCHEDULING_GUIDE.md +145 -145
  408. package/src/module/workflow-automation/controller/workflow-automation.controller.ts +43 -43
  409. package/src/module/workflow-automation/entity/workflow-automation-action.entity.ts +26 -26
  410. package/src/module/workflow-automation/entity/workflow-automation.entity.ts +40 -40
  411. package/src/module/workflow-automation/interface/action.decorator.ts +7 -7
  412. package/src/module/workflow-automation/interface/action.interface.ts +5 -5
  413. package/src/module/workflow-automation/service/action-registery.service.ts +35 -35
  414. package/src/module/workflow-automation/service/schedule-handler.service.ts +168 -168
  415. package/src/module/workflow-automation/service/workflow-automation-engine.service.ts +219 -219
  416. package/src/module/workflow-automation/service/workflow-automation.service.ts +474 -476
  417. package/src/module/workflow-automation/workflow-automation.module.ts +54 -54
  418. package/src/module/workflow-schedule/INSTALLATION.md +244 -244
  419. package/src/module/workflow-schedule/MULTI_PROJECT_GUIDE.md +196 -196
  420. package/src/module/workflow-schedule/README.md +422 -422
  421. package/src/module/workflow-schedule/constants/schedule.constants.ts +48 -48
  422. package/src/module/workflow-schedule/controller/workflow-schedule.controller.ts +253 -253
  423. package/src/module/workflow-schedule/docs/CLAUDE_CODE_GUIDE.md +510 -510
  424. package/src/module/workflow-schedule/docs/CLAUDE_CODE_PROMPT.md +362 -362
  425. package/src/module/workflow-schedule/docs/RUN_CLAUDE_CODE.sh +68 -68
  426. package/src/module/workflow-schedule/dto/create-schedule.dto.ts +147 -147
  427. package/src/module/workflow-schedule/dto/get-execution-logs.dto.ts +119 -119
  428. package/src/module/workflow-schedule/dto/update-schedule.dto.ts +96 -96
  429. package/src/module/workflow-schedule/entities/scheduled-workflow.entity.ts +148 -148
  430. package/src/module/workflow-schedule/entities/workflow-execution-log.entity.ts +154 -154
  431. package/src/module/workflow-schedule/interfaces/schedule-job-data.interface.ts +53 -53
  432. package/src/module/workflow-schedule/interfaces/workflow-schedule-options.interface.ts +12 -12
  433. package/src/module/workflow-schedule/processors/schedule.processor.ts +620 -620
  434. package/src/module/workflow-schedule/service/workflow-schedule.service.ts +597 -597
  435. package/src/module/workflow-schedule/workflow-schedule.module.ts +67 -67
  436. package/src/resources/dev.properties.yaml +31 -31
  437. package/src/resources/local.properties.yaml +27 -27
  438. package/src/resources/properties.module.ts +12 -12
  439. package/src/resources/properties.yaml.ts +11 -11
  440. package/src/resources/uat.properties.yaml +31 -31
  441. package/src/table.config.ts +135 -133
  442. package/src/utils/dto/excel-data.dto.ts +14 -14
  443. package/src/utils/dto/excelsheet-data.dto.ts +5 -5
  444. package/src/utils/service/base64util.service.ts +18 -18
  445. package/src/utils/service/clockIDGenUtil.service.ts +21 -21
  446. package/src/utils/service/codeGenerator.service.ts +22 -22
  447. package/src/utils/service/dateUtil.service.ts +17 -17
  448. package/src/utils/service/encryptUtil.service.ts +97 -97
  449. package/src/utils/service/excel-helper.service.ts +72 -72
  450. package/src/utils/service/excelUtil.service.ts +15 -15
  451. package/src/utils/service/file-util.service.ts +11 -11
  452. package/src/utils/service/json-util.service.ts +23 -23
  453. package/src/utils/service/loggingUtil.service.ts +88 -88
  454. package/src/utils/service/reflection-helper.service.ts +62 -62
  455. package/src/utils/service/wbsCodeGen.service.ts +8 -8
  456. package/src/utils/utils.module.ts +27 -27
  457. package/tsconfig.build.json +4 -4
  458. package/tsconfig.json +24 -24
@@ -1,2639 +1,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/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/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
+ }