rez_core 3.1.154 → 3.1.156

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