Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 116.23 KB | None | 0 0
  1. using DMP.DataAccess.SQL.Repositories;
  2. using DMP.Domain.Entities;
  3. using DMP.Domain.Entities.Enums;
  4. using DMP.Domain.Entities.TableEntities;
  5. using DMP.Domain.Exceptions;
  6. using DMP.Domain.ExternalServices;
  7. using DMP.Domain.Repositories;
  8. using DMP.Domain.Utils;
  9. using DMP.ExternalServices.MailChimp;
  10. using DMP.ExternalServices.MailChimp.MailChimpModels;
  11. using DMP.Web.ExternalServices;
  12. using DMP.Web.Models;
  13. using DMP.Web.Models.Audiences;
  14. using DMP.Web.Models.CampaignList;
  15. using DMP.Web.Models.Campaigns;
  16. using DMP.Web.Models.Factories.Interfaces;
  17. using DMP.Web.Models.Jobs;
  18. using DMP.Web.Models.Subscribers;
  19. using DMP.Web.Models.TableModel;
  20. using DMP.Web.Utils;
  21. using Microsoft.AspNetCore.Authorization;
  22. using Microsoft.AspNetCore.Cors;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.Mvc;
  25. using Microsoft.Extensions.Configuration;
  26. using Microsoft.Extensions.Logging;
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Linq;
  31. using System.Reflection;
  32. using System.Threading.Tasks;
  33. using System.Transactions;
  34. using CampaignServices = DMP.Web.ExternalServices.CampaignServices;
  35. using State = DMP.Domain.Entities.State;
  36.  
  37. namespace DMP.Web.Controllers
  38. {
  39. //TODO REVIEW ALL CONTROLLER
  40. public class CampaignsController : BaseController<Campaign>
  41. {
  42. private readonly ISampleCampaignSampleRepository _sampleCampaignSampleRepository;
  43. private readonly ICampaignAudienceSubscribersRepository _campaignAudienceSubscribers;
  44. private readonly IRequestRepository _requestRepository;
  45. private readonly ISampleRepository _sampleRepository;
  46. private readonly ICampaignRepository _campaignRepository;
  47. private readonly IUserRepository _userRepository;
  48. private readonly IProductRepository _productRepository;
  49. private readonly ISurveyRepository _surveyRepository;
  50. private readonly IAccountRepository _accountRepository;
  51. private readonly IBrandRepository _brandRepository;
  52. private readonly IJobRepository _jobRepository;
  53. private readonly IAudienceRepository _audienceRepository;
  54. private readonly ISegmentationServices _mcServices;
  55. private readonly IClientRepository _clientRepository;
  56. private readonly CampaignServices _mcCampaignServices;
  57. private readonly DocumentHandler _documentHandler;
  58. private readonly ISubscriberRepository _subscriberRepository;
  59. private readonly ISubscriberScoresRepository _subscriberScoresRepository;
  60. private readonly ISubscriberAggregateDataRepository _subscriberAggregateDataRepository;
  61. private readonly string surveyShareUrl;
  62. private readonly IPaginatedViewModelFactory<CampaignTable, CampaignsViewModel> campaignPaginatedViewModelFactory;
  63. private readonly IPaginatedViewModelFactory<AudienceSubscriberTable, SubscriberViewModel> subscriberPaginatedViewModelFactory;
  64. private readonly IPaginatedViewModelFactory<AudienceTable, AudiencesViewModel> audiencePaginatedViewModelFactory;
  65.  
  66. private readonly IPaginatedViewModelFactory<CampaignPresentSubscribersTable, SubscriberViewModel> _audiencePresentPaginatedViewModelFactory;
  67.  
  68.  
  69. private readonly IPaginatedViewModelFactory<CampaignAudienceListTable, CampaignListViewModel> _campaignListsPaginatedViewModelFactory;
  70.  
  71. private object _lock;
  72.  
  73. public CampaignsController(ICampaignRepository campaignRepository,
  74. IAudienceRepository audienceRepository,
  75. IUserRepository userRepository,
  76. ISubscriberRepository subscriberRepository,
  77. ISegmentationServices mcServices,
  78. CampaignServices mcCampaignServices,
  79. IProductRepository productRepository,
  80. ISurveyRepository surveyRepository,
  81. IJobRepository jobRepository,
  82. ISubscriberAggregateDataRepository subscriberAggregateDataRepository,
  83. ISubscriberScoresRepository subscriberScoresRepository,
  84. IBrandRepository brandRepository,
  85. IAccountRepository accountRepository,
  86. IHttpContextAccessor httpContextAccessor,
  87. IClientRepository clientRepository,
  88. ISampleRepository sampleRepository,
  89. ISampleCampaignSampleRepository sampleCampaignSampleRepository,
  90. IRequestRepository requestRepository,
  91. ICampaignAudienceSubscribersRepository campaignAudienceSubscribers,
  92. DocumentHandler documentHandler,
  93. IPaginatedViewModelFactory<CampaignTable, CampaignsViewModel> campaignPaginatedViewModelFactory,
  94. IPaginatedViewModelFactory<AudienceSubscriberTable, SubscriberViewModel> subscriberPaginatedViewModelFactory,
  95. IPaginatedViewModelFactory<AudienceTable, AudiencesViewModel> audiencePaginatedViewModelFactory,
  96. IPaginatedViewModelFactory<CampaignAudienceListTable, CampaignListViewModel> campaignListsPaginatedViewModelFactory,
  97. IPaginatedViewModelFactory<CampaignPresentSubscribersTable, SubscriberViewModel> audiencePresentPaginatedViewModelFactory,
  98. ILogger<BaseController<Campaign>> _logger) : base(httpContextAccessor, _logger, (BaseRepository<Campaign>)campaignRepository)
  99. {
  100. _campaignAudienceSubscribers = campaignAudienceSubscribers;
  101. _campaignRepository = campaignRepository;
  102. _userRepository = userRepository;
  103. _productRepository = productRepository;
  104. _surveyRepository = surveyRepository;
  105. _jobRepository = jobRepository;
  106. _audienceRepository = audienceRepository;
  107. _mcServices = mcServices;
  108. _clientRepository = clientRepository;
  109. _mcCampaignServices = mcCampaignServices;
  110. _documentHandler = documentHandler;
  111. _subscriberRepository = subscriberRepository;
  112. _accountRepository = accountRepository;
  113. _brandRepository = brandRepository;
  114. _subscriberAggregateDataRepository = subscriberAggregateDataRepository;
  115. _subscriberScoresRepository = subscriberScoresRepository;
  116. _sampleRepository = sampleRepository;
  117. _requestRepository = requestRepository;
  118. _sampleCampaignSampleRepository = sampleCampaignSampleRepository;
  119. _audiencePresentPaginatedViewModelFactory = audiencePresentPaginatedViewModelFactory;
  120.  
  121. this.campaignPaginatedViewModelFactory = campaignPaginatedViewModelFactory;
  122. this.subscriberPaginatedViewModelFactory = subscriberPaginatedViewModelFactory;
  123. this.audiencePaginatedViewModelFactory = audiencePaginatedViewModelFactory;
  124. _campaignListsPaginatedViewModelFactory = campaignListsPaginatedViewModelFactory;
  125.  
  126. var builder = new ConfigurationBuilder()
  127. .SetBasePath(Directory.GetCurrentDirectory())
  128. .AddJsonFile("appsettings.json");
  129.  
  130. _lock = new object();
  131.  
  132. surveyShareUrl = builder.Build()["AppServer"];
  133. }
  134.  
  135. #region POST
  136. [HttpPost]
  137. [Authorize(Policy = "Update")]
  138. [Authorize(Policy = "Cadet")]
  139. public IActionResult capSettings(int id, int cap, string OrderBy, int ProductId)
  140. {
  141. try
  142. {
  143. AppLog.Info("capSettings started with input information [id= " + id + " cap= " + cap + " OrderBy= " + OrderBy + " ProductId= " + ProductId + "]");
  144.  
  145. int _id = _campaignRepository.SetCap(id, OrderBy, ProductId, cap);
  146. AppLog.Info("capSettings finished");
  147.  
  148. return Ok(_id);
  149. }
  150. catch (DmpException e)
  151. {
  152. AppLog.Error(e.Problem.Description);
  153.  
  154. return BadRequest(e.Problem.Description);
  155. }
  156. catch (Exception e)
  157. {
  158. AppLog.Error(e.ToString());
  159.  
  160. return BadRequest(e.Message);
  161. }
  162. }
  163. [HttpPost]
  164. [Authorize(Policy = "Read")]
  165. [Authorize(Policy = "Cadet")]
  166. public IActionResult ManageRequestedSample(RequestSamplesViewModel model)
  167. {
  168. try
  169. {
  170. using (TransactionScope scope = new TransactionScope())
  171. {
  172. AppLog.Info("Campaigns ManageRequestedSample started");
  173.  
  174. foreach (var id in model.subscribers)
  175. {
  176. _campaignRepository.UpdateSampleRequest(id, model.State, UserId(), model.CampaignId);
  177. }
  178.  
  179. scope.Complete();
  180. AppLog.Info("Campaigns ManageRequestedSample finished");
  181.  
  182. return StatusCode(StatusCodes.Status200OK, new ServiceResponse()
  183. {
  184. MessageTitle = "Update",
  185. Message = "Resquest sample updated.",
  186. InternalStatusCode = 200
  187. });
  188. }
  189. }
  190. catch (DmpException e)
  191. {
  192. AppLog.Error(e.Problem.Description);
  193.  
  194. return BadRequest(e.Problem.Description);
  195. }
  196. catch (Exception e)
  197. {
  198. AppLog.Error(e.ToString());
  199.  
  200. return StatusCode(StatusCodes.Status406NotAcceptable, new ServiceResponse()
  201. {
  202. MessageTitle = "Error",
  203. Message = "Request sample not updated.",
  204. InternalStatusCode = 406
  205. });
  206. }
  207. }
  208. [HttpPost]
  209. [Authorize(Policy = "Add")]
  210. [Authorize(Policy = "Cadet")]
  211. [Route("[action]/{type}")]
  212. public IActionResult CreateCampaign(CreateCampaignViewModel model)
  213. {
  214. try
  215. {
  216. using (var scope = new TransactionScope())
  217. {
  218. AppLog.Info("CreateCampaign started");
  219.  
  220. int typedCampId = -1;
  221.  
  222. var campaign = new Campaign
  223. {
  224. Name = model.Name,
  225. Type = model.Type,
  226. LaunchDate = model.LaunchDate,
  227. ClientId = ClientId
  228. };
  229.  
  230. AuditCreate(campaign, UserId());
  231.  
  232. var campaignId = _campaignRepository.Create(campaign);
  233.  
  234. dynamic _camp;
  235.  
  236. switch (model.Type)
  237. {
  238. case CampaignType.Sample:
  239. if (model.SampleIds == null || model.SampleIds.Count() == 0)
  240. {
  241. return StatusCode(600, "Sample Campaign Without Any Samples Associated");
  242. }
  243.  
  244. //add logic about number of samples stock
  245.  
  246. //var samplesStorageResponse = _sampleRepository.GetListSamplesNumberDictionary(model.ProductId);
  247. //if (!samplesStorageResponse.IsResponseCodeOK())
  248. //{
  249. // return StatusCode(samplesStorageResponse.Code, samplesStorageResponse.Message);
  250. //}
  251. //Dictionary<int, int> samplesStorage = samplesStorageResponse.ObjectNeeded as Dictionary<int, int>;
  252. //if (samplesStorage == null)
  253. //{
  254. // return StatusCode(600, samplesStorageResponse.Message);
  255. //}
  256. //int allStorage = 0;
  257. //foreach (var sample in model.SampleIds)
  258. //{
  259. // if (samplesStorage.ContainsKey(sample))
  260. // {
  261. // allStorage = allStorage + samplesStorage[sample];
  262. // }
  263. //}
  264. //if (allStorage < model.SampleNumber)
  265. //{
  266. // return StatusCode(600, "No Storage Available Max Storage Number is -> " + allStorage);
  267. //}
  268.  
  269.  
  270. _camp = new SampleCampaign
  271. {
  272. CampaignId = campaignId,
  273. SamplesNumber = model.SampleNumber.GetValueOrDefault(),
  274. EndDate = model.EndDate == default(DateTime) ? model.LaunchDate.AddMonths(1) : model.EndDate,
  275. ProductId = model.ProductId
  276.  
  277. };
  278.  
  279. AuditCreate(_camp, UserId());
  280.  
  281. typedCampId = _campaignRepository.CreateSampleCampaign(_camp, model.ProductId);
  282.  
  283. if (model.SampleIds != null && model.SampleIds.Count() > 0)
  284. {
  285. List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
  286. bool createSampleCampaignListResult = CreateSampleCampaignEntries(model.SampleIds, typedCampId, out sampleCampaignSampleList);
  287. if (!createSampleCampaignListResult)
  288. {
  289. return StatusCode(600, "Error Creating Sample Campaign Samples Association");
  290. }
  291.  
  292. var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
  293. if (!createSampleCampaignsResponse.IsResponseCodeOK())
  294. {
  295. return StatusCode(createSampleCampaignsResponse.Code, createSampleCampaignsResponse.Message);
  296. }
  297.  
  298. }
  299.  
  300. var audienceId = _audienceRepository.CreateSamplesAudience(new Audience
  301. {
  302. ClientId = ClientId,
  303. CreatedBy = UserId(),
  304. CreatedOn = DateTime.UtcNow,
  305. Name = $"Audience : {campaign.Name}",
  306. Description = "Audience generated for Sample Campaign"
  307. },
  308. ClientId,
  309. model.ProductId,
  310. model.SampleNumber.Value);
  311.  
  312. _campaignRepository.AssociateAudience(campaignId,
  313. new List<CampaignAudiences>()
  314. {
  315. new CampaignAudiences()
  316. {
  317. CampaignId = campaignId,
  318. AudienceId = audienceId,
  319. CreatedBy = UserId(),
  320. CreatedOn = DateTime.UtcNow
  321. }
  322. });
  323.  
  324. break;
  325.  
  326. case CampaignType.Email:
  327.  
  328. _camp = new EmailCampaign
  329. {
  330. CampaignId = campaignId,
  331. SentDate = model.SentDate
  332. };
  333.  
  334. AuditCreate(_camp, UserId());
  335.  
  336. typedCampId = _campaignRepository.CreateEmailCampaign(_camp);
  337.  
  338. break;
  339.  
  340. case CampaignType.Survey:
  341.  
  342. _camp = new SurveyCampaign
  343. {
  344. CampaignId = campaignId,
  345. SentDate = model.SentDate
  346. };
  347.  
  348. AuditCreate(_camp, UserId());
  349.  
  350. typedCampId = _campaignRepository.CreateSurveyCampaign(_camp, model.SurveyId.GetValueOrDefault());
  351.  
  352. break;
  353.  
  354. default:
  355. throw new Exception($"Invalid Campaign type {model.Type} creation");
  356. }
  357.  
  358. if (typedCampId == -1)
  359. {
  360. throw new Exception($"Failed Campaign type {model.Type} creation");
  361. }
  362.  
  363. scope.Complete();
  364.  
  365. AppLog.Info("CreateCampaign finished");
  366.  
  367. return Ok(new { campaignId = campaignId, TypeCampaignId = typedCampId });
  368. }
  369. }
  370. catch (DmpException e)
  371. {
  372. AppLog.Error(e.Problem.Description);
  373.  
  374. return BadRequest(e.Problem.Description);
  375. }
  376. catch (Exception e)
  377. {
  378. AppLog.Error(e.ToString());
  379. return BadRequest(new { error = e.Message });
  380. }
  381. }
  382.  
  383. [HttpPost]
  384. [Authorize(Policy = "Add")]
  385. [Authorize(Policy = "Cadet")]
  386. [Route("[action]/job/{type}/{jobId}")]
  387. public IActionResult CreateCampaignJob(CreateCampaignViewModel model)
  388. {
  389. try
  390. {
  391. using (var scope = new TransactionScope())
  392. {
  393. AppLog.Info("CreateCampaignJob started");
  394. int typedCampId = -1;
  395. Campaign camp = new Campaign { Name = model.Name, Type = model.Type, LaunchDate = model.LaunchDate, ClientId = ClientId };
  396. AuditCreate(camp, UserId());
  397. var campId = _campaignRepository.Create(camp);
  398. dynamic _camp;
  399.  
  400. switch (model.Type)
  401. {
  402. case CampaignType.Sample:
  403.  
  404. if (model.ProductId == 0)
  405. return BadRequest(new { error = "Invalid Product ID" });
  406.  
  407. _camp = new SampleCampaign
  408. {
  409. CampaignId = campId,
  410. SamplesNumber = model.SampleNumber.GetValueOrDefault(),
  411. EndDate = model.EndDate,
  412. ProductId=model.ProductId
  413. };
  414. AuditCreate(_camp, UserId());
  415. typedCampId = _campaignRepository.CreateSampleCampaign(_camp, model.ProductId);
  416. break;
  417.  
  418. case CampaignType.Email:
  419.  
  420. _camp = new EmailCampaign { CampaignId = campId, SentDate = model.SentDate };
  421. AuditCreate(_camp, UserId());
  422. typedCampId = _campaignRepository.CreateEmailCampaign(_camp);
  423. break;
  424.  
  425. case CampaignType.Survey:
  426.  
  427. _camp = new SurveyCampaign { CampaignId = campId, SentDate = model.SentDate };
  428. AuditCreate(_camp, UserId());
  429. typedCampId = _campaignRepository.CreateSurveyCampaign(_camp, model.SurveyId.GetValueOrDefault());
  430. break;
  431.  
  432. default:
  433. throw new Exception($"Invalid Campaign type {model.Type} creation");
  434. }
  435.  
  436. if (typedCampId == -1)
  437. throw new Exception($"Failed Campaign type {model.Type} creation");
  438. try
  439. {
  440. if (model.jobId != 0)
  441. {
  442. _campaignRepository.AssociateJob(model.jobId, campId);
  443. }
  444. else
  445. {
  446. throw new Exception($"Failed to associate job with campaign");
  447. }
  448. }
  449. catch (Exception ex)
  450. {
  451. if (ex is DmpException)
  452. throw ex;
  453. return BadRequest(new { error = ex.Message });
  454. }
  455. AppLog.Info("CreateCampaignJob finished");
  456.  
  457. scope.Complete();
  458. return Ok(new { campaignId = campId, TypeCampaignId = typedCampId });
  459. }
  460. }
  461. catch (DmpException e)
  462. {
  463. AppLog.Error(e.Problem.Description);
  464.  
  465. return BadRequest(e.Problem.Description);
  466. }
  467. catch (Exception e)
  468. {
  469. AppLog.Error(e.ToString());
  470. return BadRequest(new { error = e.Message });
  471. }
  472. }
  473.  
  474. [HttpPost]
  475. [Authorize(Policy = "Add")]
  476. [Authorize(Policy = "Cadet")]
  477. public IActionResult AddCampaign(CampaignsViewModel model)
  478. {
  479. try
  480. {
  481. AppLog.Info("AddCampaign started");
  482.  
  483. var campaign = new Campaign
  484. {
  485. Name = model.Name,
  486. ClientId = ClientId
  487. };
  488.  
  489. AuditCreate(campaign, UserId());
  490. int x = 0;
  491. CampaignType.TryParse("Survey", out x);
  492.  
  493. AuditCreate(campaign, UserId());
  494. _campaignRepository.Create(campaign);
  495. AppLog.Info("AddCampaign finished");
  496. return StatusCode(StatusCodes.Status200OK);
  497. }
  498. catch (DmpException e)
  499. {
  500. AppLog.Error(e.Problem.Description);
  501.  
  502. return BadRequest(e.Problem.Description);
  503. }
  504. catch (Exception e)
  505. {
  506. AppLog.Error(e.ToString());
  507. return BadRequest(e.Message);
  508. }
  509. }
  510.  
  511. [HttpPost]
  512. [Authorize(Policy = "Update")]
  513. [Authorize(Policy = "Cadet")]
  514. [Route("/campaigns/EditCampaignSamples")]
  515. public IActionResult EditCampaignSamples(List<int> SampleIds, int campaignId)
  516. {
  517. try
  518. {
  519. var typedCampaign = this._campaignRepository.GetCampaign(campaignId, ClientId);
  520. if (!(typedCampaign is SampleCampaign))
  521. {
  522. return StatusCode(600, "Campaign is not a Sample Campaign");
  523. }
  524.  
  525. int sampleCampaignId = typedCampaign.Id;
  526.  
  527. AppLog.Info("EditCampaignSamples started with input information [sampleCampaignId=" + sampleCampaignId + "]");
  528. if (SampleIds == null || SampleIds.Count() == 0)
  529. {
  530. return StatusCode(600, new { Id = sampleCampaignId, Message = "Sample Campaign without Samples." });
  531. }
  532.  
  533. bool updatedSamples = UpdateCampaignSamples(SampleIds, sampleCampaignId);
  534. if (updatedSamples)
  535. {
  536. AppLog.Info("EditCampaignSamples finished successfully");
  537.  
  538. return StatusCode(200, new { Id = sampleCampaignId, Message = "Campaign Samples Sucessfully Updated" });
  539. }
  540. AppLog.Info("EditCampaignSamples finished wrong");
  541. return StatusCode(600, new { Id = sampleCampaignId, Message = "Error Updating Samples" });
  542. }
  543. catch (Exception e)
  544. {
  545. AppLog.Error(e.ToString());
  546. return BadRequest(e.Message);
  547. }
  548. }
  549.  
  550. [HttpPost]
  551. [Authorize(Policy = "Update")]
  552. [Authorize(Policy = "Cadet")]
  553. [Route("/campaigns/EditCampaign")]
  554. public IActionResult EditCampaign(CampaignsViewModel model)
  555. {
  556. try
  557. {
  558. using (var scope = new TransactionScope())
  559. {
  560.  
  561. AppLog.Info("EditCampaign started");
  562.  
  563. var typedCampaign = this._campaignRepository.GetCampaign(model.Id, ClientId);
  564. var currentCampaign = typedCampaign.Campaign;
  565.  
  566. if (currentCampaign.Name != model.Name && model.Name != null)
  567. {
  568. currentCampaign.Name = model.Name;
  569. this.AuditEdit(currentCampaign);
  570. this.AuditEdit(typedCampaign);
  571. }
  572.  
  573. if (model.Job != null && currentCampaign.JobId != model.Job.Id && model.Job.Id != null)
  574. {
  575. currentCampaign.JobId = model.Job.Id;
  576. this.AuditEdit(currentCampaign);
  577. this.AuditEdit(typedCampaign);
  578. }
  579.  
  580. if (currentCampaign.LaunchDate != model.LaunchDate && model.LaunchDate != null)
  581. {
  582. currentCampaign.LaunchDate = model.LaunchDate.Value;
  583. this.AuditEdit(currentCampaign);
  584. this.AuditEdit(typedCampaign);
  585. }
  586. if (typedCampaign is SampleCampaign)
  587. {
  588. typedCampaign.SamplesNumber = model.SuppliedSamples;
  589. this.AuditEdit(typedCampaign);
  590. this._campaignRepository.UpdateSampleCampaign(typedCampaign);
  591.  
  592. }
  593.  
  594.  
  595.  
  596. if (typedCampaign is SampleCampaign && typedCampaign.EndDate != model.EndDate && model.EndDate != null)
  597. {
  598. //add logic about number of samples stock
  599. typedCampaign.EndDate = model.EndDate.Value;
  600. this.AuditEdit(currentCampaign);
  601. this.AuditEdit(typedCampaign);
  602. this._campaignRepository.UpdateSampleCampaign(typedCampaign);
  603.  
  604. }
  605.  
  606. if (!(typedCampaign is SampleCampaign) && typedCampaign.SentDate != model.SentDate && model.SentDate != null)
  607. {
  608.  
  609. typedCampaign.SentDate = model.SentDate.Value;
  610. this.AuditEdit(currentCampaign);
  611. this.AuditEdit(typedCampaign);
  612. if (typedCampaign is EmailCampaign)
  613. this._campaignRepository.UpdateSentDateEmail(typedCampaign);
  614. else
  615. this._campaignRepository.UpdateSentDateSurvey(typedCampaign);
  616. }
  617. this._campaignRepository.Update(currentCampaign);
  618. scope.Complete();
  619. }
  620. var camp = this._campaignRepository.GetCampaign(model.Id, ClientId).Campaign;
  621. AppLog.Info("EditCampaign finished");
  622.  
  623. return this.Ok(new CampaignsViewModel
  624. {
  625. Brand = camp.Job?.Brand?.Name,
  626. Account = camp.Job?.Brand?.Account?.Name,
  627. JobId = camp.JobId
  628. });
  629. }
  630. catch (DmpException e)
  631. {
  632. AppLog.Error(e.Problem.Description);
  633.  
  634. return BadRequest(e.Problem.Description);
  635. }
  636. catch (Exception e)
  637. {
  638. AppLog.Error(e.ToString());
  639. return BadRequest(e.Message);
  640. }
  641. }
  642.  
  643. //TODO NEED REVIEW THE NESTED TRY
  644. [HttpPost]
  645. [Authorize(Policy = "Add")]
  646. [Authorize(Policy = "Cadet")]
  647. [Route("[action]/campaign/{campaignid}/job/{jobid}")]
  648. public IActionResult AssociateJob(int campaignid, int jobid)
  649. {
  650. try
  651. {
  652. try
  653. {
  654. AppLog.Info("Campaigns AssociateJob started with input information [campaignid= " + campaignid + " jobid= " + jobid + "]");
  655.  
  656. _campaignRepository.AssociateJob(jobid, campaignid);
  657.  
  658. var databaseModel = _jobRepository.GetById(jobid, ClientId);
  659.  
  660. if (!databaseModel.IsResponseCodeOK())
  661. {
  662. return StatusCode(databaseModel.Code, databaseModel.Message);
  663. }
  664.  
  665. var job = databaseModel.ObjectNeeded as Job;
  666.  
  667. AppLog.Info("Campaigns AssociateJob finished");
  668.  
  669. return StatusCode(databaseModel.Code, new JobsViewModel()
  670. {
  671. Id = job.Id,
  672. JobNumber = job.JobNumber,
  673. BrandName = job.Brand.Name,
  674. AccountName = job.Brand.Account.Name
  675. });
  676. }
  677. catch (DmpException e)
  678. {
  679. return StatusCode(e.Problem.StatusCode, e.Problem.InvalidParameters.First().Reason);
  680. }
  681. catch (Exception e)
  682. {
  683. return StatusCode(StatusCodes.Status500InternalServerError, $"Failed to AssociateJob with message : {e.Message}");
  684. }
  685. }
  686. catch (DmpException e)
  687. {
  688. AppLog.Error(e.Problem.Description);
  689.  
  690. //put this unique
  691. return BadRequest(e.Problem.Description);
  692. }
  693. catch (Exception e)
  694. {
  695. AppLog.Error(e.ToString());
  696.  
  697. return StatusCode(StatusCodes.Status409Conflict);
  698. }
  699. }
  700.  
  701. //NEEDS REVIEW
  702. [HttpPost]
  703. [Authorize(Policy = "Add")]
  704. [Authorize(Policy = "Cadet")]
  705. [Route("[action]/Campaigns/{campaignId}/Audiences")]
  706. public IActionResult AssociateAudience(int campaignId, [FromBody] int[] audienceIds)
  707. {
  708. var _audience = new List<AudiencesViewModel>();
  709.  
  710. try
  711. {
  712. AppLog.Info($"Campaigns AssociateAudience started with input information [campaignId= {campaignId} audienceId= {string.Join(", ", audienceIds)}]");
  713.  
  714. using (var scope = new TransactionScope())
  715. {
  716. var campaignAudiences = audienceIds.Select(x=> new CampaignAudiences()
  717. {
  718. CampaignId = campaignId,
  719. AudienceId = x,
  720. CreatedBy = UserId(),
  721. CreatedOn = DateTime.UtcNow,
  722. });
  723.  
  724. _campaignRepository.AssociateAudience(campaignId, campaignAudiences);
  725.  
  726. scope.Complete();
  727. }
  728.  
  729. var allCampaignAudiences=_campaignRepository.GetCampaignAudienceLists(campaignId);
  730. if(allCampaignAudiences==null || allCampaignAudiences.Count() == 0)
  731. {
  732. return Ok(_audience);
  733. }
  734. _audience=allCampaignAudiences.Select(x => new AudiencesViewModel
  735. {
  736. Name = x.Name,
  737. Id = x.Id
  738. }).ToList();
  739. AppLog.Info("Campaigns AssociateAudience finished");
  740.  
  741. return Ok(_audience);
  742. }
  743. catch (DmpException e)
  744. {
  745. AppLog.Error(e.Problem.Description);
  746.  
  747. //put this unique
  748. return BadRequest(e.Problem.Description);
  749. }
  750. catch (Exception e)
  751. {
  752. AppLog.Error(e.ToString());
  753.  
  754. return StatusCode(StatusCodes.Status409Conflict);
  755. }
  756. }
  757.  
  758. [HttpPost]
  759. [Authorize(Policy = "Add")]
  760. [Authorize(Policy = "Cadet")]
  761. public IActionResult CreateAudience(string name, AudienceType reviewed, int campaignid)
  762. {
  763. try
  764. {
  765. AppLog.Info($"Campaigns CreateAudience started with input information [name= {name} campaignid= {campaignid}]");
  766.  
  767. var campaign = _campaignRepository.GetCampaign(campaignid, ClientId) as SampleCampaign;
  768.  
  769. if (campaign == null ||
  770. (campaign.Campaign.CampaignAudiences == null || campaign.Campaign.CampaignAudiences.Count() == 0))
  771. {
  772. return BadRequest("No Audience associated or campaign is not a sample campaign");
  773. }
  774.  
  775. if (_audienceRepository.GetByName(ClientId, name).Count() > 0)
  776. {
  777. return BadRequest("Audience name already exist, please try another one.");
  778. }
  779.  
  780. AppLog.Info("Campaigns CreateAudience finished");
  781.  
  782. var campaignAudience = campaign.Campaign.CampaignAudiences
  783. .FirstOrDefault(cmp => cmp.CampaignId == campaignid); // Momentaneamente atribuido o 1o elemento.
  784.  
  785. var newAudienceId = _audienceRepository.GenerateSamplesAudience(campaign.Campaign.ClientId, campaign.ProductId, reviewed, campaignAudience, name);
  786.  
  787. _audienceRepository.UpdateAudienceSubscribersState(newAudienceId);
  788.  
  789. return StatusCode(StatusCodes.Status200OK, newAudienceId);
  790. }
  791. catch (DmpException e)
  792. {
  793. AppLog.Error(e.Problem.Description);
  794.  
  795. return BadRequest(e.Problem.Description);
  796. }
  797. catch (Exception e)
  798. {
  799. AppLog.Error(e.ToString());
  800.  
  801. return StatusCode(StatusCodes.Status409Conflict, e.Message);
  802. }
  803. }
  804.  
  805. [HttpPost]
  806. [Authorize(Policy = "Update")]
  807. [Authorize(Policy = "Cadet")]
  808. public IActionResult Complete(int campaignid)
  809. {
  810. try
  811. {
  812. AppLog.Info("Campaigns Complete started with input information [campaignid= " + campaignid + "]");
  813.  
  814. var campaign = _campaignRepository.GetCampaign(campaignid, ClientId);
  815.  
  816. SampleCampaign sampleCampaign = campaign as SampleCampaign;
  817.  
  818. using (var scope = new TransactionScope())
  819. {
  820. IEnumerable<CampaignAudiences> campaignAudiences = null;
  821.  
  822. if (sampleCampaign != null && sampleCampaign.Campaign != null)
  823. {
  824. if(sampleCampaign.Campaign.CampaignAudiences==null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
  825. {
  826. return StatusCode(600, "Campaign Without Audiences Associated");
  827. }
  828. campaignAudiences = sampleCampaign.Campaign.CampaignAudiences;
  829.  
  830. var audSubApprovedCount = 0;
  831.  
  832. if (campaignAudiences.Count() > 0)
  833. {
  834. var ids = campaignAudiences.Select(cmp => cmp.AudienceId);
  835.  
  836. audSubApprovedCount = (ids.Count() == 0 ? audSubApprovedCount :
  837. _audienceRepository.GetAudienceSubscribersDistinct(ids, State.Approved)
  838. .Select(cmp => cmp.Id)
  839. .Count());
  840. }
  841.  
  842. var prodSampleCount = sampleCampaign.SamplesNumber;
  843.  
  844.  
  845. if (audSubApprovedCount > prodSampleCount)
  846. {
  847. return StatusCode((int)DatabaseReturnCodes.InternalError,
  848. $"Amount of product sample ({prodSampleCount}) is not suficient for amount of campaign audience ({audSubApprovedCount}).");
  849. }
  850.  
  851. var getSampleResponse = _sampleCampaignSampleRepository.WithdrawalSampleNumber(sampleCampaign.Id, audSubApprovedCount);
  852.  
  853. sampleCampaign.SamplesNumber = audSubApprovedCount;
  854.  
  855. _campaignRepository.UpdateSampleCampaign(sampleCampaign);
  856.  
  857. if (!getSampleResponse.IsResponseCodeOK())
  858. {
  859. return StatusCode(getSampleResponse.Code, getSampleResponse.Message);
  860. }
  861. bool createSampleLists = CreateSampleCampaignLists(campaignid);
  862. if(!createSampleLists)
  863. {
  864. return StatusCode(600,"Error Creating Sample Campaign Lists");
  865. }
  866.  
  867.  
  868. }
  869. _campaignRepository.Complete(campaignid, ClientId);
  870.  
  871. IEnumerable<CampaignAudiencesViewModel> campaignAudiencesView = null;
  872. var campaignViewModel = new CampaignsViewModel
  873. {
  874. Id = (sampleCampaign == null) ? campaign.Campaign.Id : sampleCampaign.Campaign.Id,
  875. IsActive = (sampleCampaign == null) ? campaign.Campaign.IsActive : sampleCampaign.Campaign.IsActive,
  876. IsPending = (sampleCampaign == null) ? campaign.Campaign.isPending : sampleCampaign.Campaign.isPending,
  877. CampaignAudiences = campaignAudiencesView
  878. };
  879.  
  880. scope.Complete();
  881.  
  882. AppLog.Info("Campaigns Complete finished");
  883.  
  884. return Ok(campaignViewModel);
  885. }
  886. }
  887. catch (DmpException e)
  888. {
  889. AppLog.Error(e.Problem.Description);
  890.  
  891. return BadRequest(e.Problem.Description);
  892. }
  893. catch (Exception e)
  894. {
  895. AppLog.Error(e.ToString());
  896.  
  897. return StatusCode(StatusCodes.Status409Conflict);
  898. }
  899. }
  900.  
  901. [HttpPost]
  902. [Authorize(Policy = "Update")]
  903. [Authorize(Policy = "Cadet")]
  904. public IActionResult updateSentDate(CampaignsViewModel model)
  905. {
  906. try
  907. {
  908. AppLog.Info("Campaigns updateSentDate started");
  909.  
  910. switch (model.Type)
  911. {
  912. case CampaignType.Email:
  913. var emailObject = _campaignRepository.GetCampaign(model.Id, ClientId);
  914.  
  915. emailObject.SentDate = model.SentDate;
  916. AuditEdit(emailObject);
  917. try
  918. {
  919. _campaignRepository.UpdateSentDateEmail(emailObject);
  920. }
  921. catch (DmpException e)
  922. {
  923. AppLog.Error(e.Problem.Description);
  924.  
  925. //put this unique
  926. return BadRequest(e.Problem.Description);
  927. }
  928. catch (Exception e)
  929. {
  930. AppLog.Error(e.ToString());
  931.  
  932. return StatusCode(StatusCodes.Status409Conflict);
  933. }
  934. break;
  935.  
  936. case CampaignType.Survey:
  937. var surveyObject = _campaignRepository.GetCampaign(model.Id, ClientId);
  938.  
  939. surveyObject.SentDate = model.SentDate;
  940. AuditEdit(surveyObject);
  941. try
  942. {
  943. _campaignRepository.UpdateSentDateSurvey(surveyObject);
  944. }
  945. catch (DmpException e)
  946. {
  947. AppLog.Error(e.Problem.Description);
  948.  
  949. //put this unique
  950. return BadRequest(e.Problem.Description);
  951. }
  952. catch (Exception e)
  953. {
  954. AppLog.Error(e.ToString());
  955.  
  956. return StatusCode(StatusCodes.Status409Conflict);
  957. }
  958. break;
  959. }
  960. AppLog.Info("Campaigns updateSentDate finished");
  961.  
  962. return StatusCode(StatusCodes.Status200OK, new ServiceResponse()
  963. {
  964. MessageTitle = "Updated",
  965. Message = "Sent date updated.",
  966. InternalStatusCode = 200
  967. });
  968. }
  969. catch (DmpException e)
  970. {
  971. AppLog.Error(e.Problem.Description);
  972.  
  973. return BadRequest(e.Problem.Description);
  974. }
  975. catch (Exception e)
  976. {
  977. AppLog.Error(e.ToString());
  978. return BadRequest(e.Message);
  979. }
  980. }
  981. [Authorize(Policy = "Read")]
  982. [Authorize(Policy = "Cadet")]
  983. [Route("refreshSamplesNumber")]
  984. [HttpPost]
  985. public ActionResult RefreshSamplesNumber(List<int> SampleIds, int ProductId)
  986. {
  987. AppLog.Info("RefreshSamplesNumber started");
  988. try
  989. {
  990. int allStorage = 0;
  991. if (SampleIds != null || SampleIds.Count() > 0)
  992. {
  993. var samplesStorageResponse = _sampleRepository.GetListSamplesNumberDictionary(ProductId);
  994. if (!samplesStorageResponse.IsResponseCodeOK())
  995. {
  996. return StatusCode(samplesStorageResponse.Code, samplesStorageResponse.Message);
  997. }
  998. Dictionary<int, int> samplesStorage = samplesStorageResponse.ObjectNeeded as Dictionary<int, int>;
  999. if (samplesStorage == null)
  1000. {
  1001. return StatusCode(600, samplesStorageResponse.Message);
  1002. }
  1003. foreach (var sample in SampleIds)
  1004. {
  1005. if (samplesStorage.ContainsKey(sample))
  1006. {
  1007. allStorage = allStorage + samplesStorage[sample];
  1008. }
  1009. }
  1010. }
  1011. AppLog.Info("RefreshSamplesNumber finished");
  1012. return StatusCode(200, allStorage);
  1013.  
  1014. }
  1015. catch (Exception e)
  1016. {
  1017. AppLog.Error(e.ToString());
  1018. return BadRequest(e.Message);
  1019. }
  1020. }
  1021.  
  1022. #endregion
  1023.  
  1024. #region GET
  1025.  
  1026. [Authorize(Policy = "Read")]
  1027. [Authorize(Policy = "Cadet")]
  1028. public IActionResult Index()
  1029. {
  1030. var campaign = new CampaignsViewModel(Role);
  1031. return View(campaign);
  1032. }
  1033.  
  1034. [HttpGet]
  1035. [Authorize(Policy = "Read")]
  1036. [Authorize(Policy = "Cadet")]
  1037. [Route("[action]/")]
  1038. public ActionResult GetTypes()
  1039. {
  1040. try
  1041. {
  1042. AppLog.Info("GetTypes started");
  1043.  
  1044. Dictionary<string, dynamic> enums = new Dictionary<string, dynamic>();
  1045. var vals = Enum.GetValues(typeof(CampaignType));
  1046. var names = Enum.GetNames(typeof(CampaignType));
  1047.  
  1048. for (int i = 0; i < vals.Length; i++)
  1049. {
  1050. enums.Add(names[i], vals.GetValue(i));
  1051. }
  1052. AppLog.Info("GetTypes finished");
  1053. return Ok(enums);
  1054. }
  1055. catch (DmpException e)
  1056. {
  1057. AppLog.Error(e.Problem.Description);
  1058.  
  1059. return BadRequest(e.Problem.Description);
  1060. }
  1061. catch (Exception e)
  1062. {
  1063. AppLog.Error(e.ToString());
  1064. return BadRequest(e.Message);
  1065. }
  1066. }
  1067.  
  1068. [Authorize(Policy = "Read")]
  1069. [Authorize(Policy = "Cadet")]
  1070. [HttpGet]
  1071. //criar field the pedido de samples numbers
  1072. public IActionResult Details(int id)
  1073. {
  1074. AppLog.Info("Campaigns Details started with input information [id= " + id + "]");
  1075. try
  1076. {
  1077. var _campaign = _campaignRepository.GetCampaign(id, ClientId);
  1078. var getUserResponse = _userRepository.GetById(int.Parse(_campaign.CreatedBy.ToString()));
  1079.  
  1080. if (!getUserResponse.IsResponseCodeOK())
  1081. {
  1082. return StatusCode(getUserResponse.Code, getUserResponse.Message);
  1083. }
  1084.  
  1085. var _user = getUserResponse.ObjectNeeded as User;
  1086.  
  1087. var databaseModel = _campaignAudienceSubscribers.GetCampaignAudienceSubscribersHistory(id);
  1088.  
  1089. if (!databaseModel.IsResponseCodeOK())
  1090. {
  1091. return StatusCode(databaseModel.Code, databaseModel.Message);
  1092. }
  1093.  
  1094. var campaignAudienceSubscribersHistory = (databaseModel.ObjectNeeded as IQueryable<CampaignAudienceSubscribersHistory>)
  1095. .Select(cmp => new CampaignAudienceSubscribersHistoryViewModel()
  1096. {
  1097. Id = cmp.Id,
  1098. CampaignId = cmp.Id,
  1099. CampaignAudienceId = cmp.CampaignAudienceId,
  1100. AudienceId = cmp.AudienceId,
  1101. AudienceDescription = cmp.Audience.Name,
  1102. SubscriberId = cmp.SubscriberId,
  1103. SubscriberName = string.Concat(cmp.Subscriber.FirstName, " ", cmp.Subscriber.LastName),
  1104. CreatedBy = cmp.CreatedBy,
  1105. CreatedOn = cmp.CreatedOn
  1106. });
  1107.  
  1108. var campaigns = new CampaignsViewModel()
  1109. {
  1110. Id = _campaign.Campaign.Id,
  1111. Name = _campaign.Campaign.Name,
  1112. JobNumber = _campaign.Campaign.Job?.JobNumber ?? null,
  1113. JobId = _campaign.Campaign.JobId,
  1114. Brand = _campaign.Campaign.Job?.Brand?.Name ?? null,
  1115. BrandId = _campaign.Campaign.Job?.Brand?.Id ?? null,
  1116. AccountId = _campaign.Campaign.Job?.Brand?.Account?.Id ?? null,
  1117. Account = _campaign.Campaign.Job?.Brand?.Account?.Name ?? null,
  1118. Type = _campaign.Campaign.Type,
  1119. IsActive = _campaign.Campaign.IsActive,
  1120. CreatedBy = _campaign.CreatedBy,
  1121. CreatedByName = _user.Name,
  1122. CreatedOn = _campaign.Campaign.CreatedOn,
  1123. UpdatedOn = _campaign.Campaign.UpdatedOn,
  1124. LaunchDate = _campaign.Campaign.LaunchDate,
  1125. IsPending = _campaign.Campaign.isPending,
  1126. CampaignAudiences = (_campaign.Campaign.CampaignAudiences == null || _campaign.Campaign.CampaignAudiences.Count == 0) ? new List<CampaignAudiencesViewModel>() : new List<CampaignAudiencesViewModel>(),
  1127. CampaignAudienceSubscribersHistory = campaignAudienceSubscribersHistory,
  1128. };
  1129.  
  1130. if (_campaign.GetType() == typeof(EmailCampaign) || _campaign.GetType() == typeof(SurveyCampaign))
  1131. {
  1132. campaigns.SentDate = (_campaign.SentDate == null) ? null : _campaign.SentDate;
  1133.  
  1134. campaigns.IsMailChimpCampaign = (campaignAudienceSubscribersHistory != null && campaignAudienceSubscribersHistory.Count() > 0);
  1135. }
  1136.  
  1137. if (_campaign.GetType() == typeof(SampleCampaign))
  1138. {
  1139. var getProductResponse = _productRepository.GetProduct(_campaign.ProductId);
  1140. if (!getProductResponse.IsResponseCodeOK())
  1141. {
  1142. return StatusCode(getProductResponse.Code, getProductResponse.Message);
  1143. }
  1144. Product _product = getProductResponse.ObjectNeeded as Product;
  1145. if (_product == null)
  1146. {
  1147. return StatusCode(600, "Sample Campaign Not Associated with any Product");
  1148. }
  1149.  
  1150. var getSampleCampaignIdsResponse = _sampleCampaignSampleRepository.GetById(_campaign.Id);
  1151. if (!getSampleCampaignIdsResponse.IsResponseCodeOK())
  1152. {
  1153. return StatusCode(getSampleCampaignIdsResponse.Code, getSampleCampaignIdsResponse.Message);
  1154. }
  1155. IQueryable<SampleCampaignSample> sampleCampaignSamples = getSampleCampaignIdsResponse.ObjectNeeded as IQueryable<SampleCampaignSample>;
  1156. if (sampleCampaignSamples == null || sampleCampaignSamples.Count() == 0)
  1157. {
  1158. campaigns.SampleIds = null;
  1159. }
  1160. campaigns.SampleIds = sampleCampaignSamples.Where(x => x.IsActive).Select(x => x.SampleId).Distinct().ToList();
  1161.  
  1162. var allSamplesListResponse = _sampleRepository.GetListSamplesNumberDictionary(_product.Id);
  1163. if (!allSamplesListResponse.IsResponseCodeOK())
  1164. {
  1165. return StatusCode(allSamplesListResponse.Code, allSamplesListResponse.Message);
  1166. }
  1167. Dictionary<int, int> productSampleStorage = allSamplesListResponse.ObjectNeeded as Dictionary<int, int>;
  1168. int totalStorageAvailable = 0;
  1169. if (productSampleStorage != null && productSampleStorage.Count() > 0)
  1170. {
  1171. foreach (var sample in campaigns.SampleIds)
  1172. {
  1173. if (productSampleStorage.ContainsKey(sample))
  1174. {
  1175. totalStorageAvailable = totalStorageAvailable + productSampleStorage[sample];
  1176. }
  1177. }
  1178. }
  1179.  
  1180. campaigns.SampleDetails = sampleCampaignSamples.Where(x => x.IsActive).ToDictionary(x => x.SampleId, x => x.Sample.Name);
  1181.  
  1182.  
  1183. campaigns.ExtProductId = (_product._ExternalId == null) ? null : _product._ExternalId;
  1184. campaigns.ProductId = _product.Id;
  1185. campaigns.ProductName = _product.Name;
  1186. campaigns.SuppliedSamples = _campaign.SamplesNumber;
  1187. campaigns.EndDate = (_campaign.EndDate == null) ? null : _campaign.EndDate;
  1188. campaigns.ProductUrl = _product.Url;
  1189. campaigns.IsCapped = _campaignRepository.IsCapped(_product.Id);
  1190. campaigns.SampleRequestsCount = _campaignRepository.CountSampleRequests(_product.Id);
  1191. campaigns.AvailableStorage = totalStorageAvailable;
  1192.  
  1193. var stats = _campaignRepository.getStats(id, ClientId);
  1194.  
  1195. campaigns.approvedProfiles = stats[0];
  1196. campaigns.approvedReviews = stats[1];
  1197. campaigns.averageRating = stats[2];
  1198.  
  1199. databaseModel = _audienceRepository.GetAudienceByCampaign(id, ClientId);
  1200.  
  1201. if (!databaseModel.IsResponseCodeOK())
  1202. {
  1203. return StatusCode(databaseModel.Code, databaseModel.Message);
  1204. }
  1205.  
  1206. var campaign = databaseModel.ObjectNeeded as Campaign;
  1207.  
  1208. var campaignAudiences = campaign.CampaignAudiences.FirstOrDefault(cmp=>cmp.Audience.SampleAudience);
  1209. if (campaignAudiences == null)
  1210. {
  1211. return StatusCode(600, "There is no Sample Audience type for Campaign");
  1212. }
  1213.  
  1214. int sampleAudienceId = campaignAudiences.AudienceId;
  1215. var sampleAudienceSubscribers = _audienceRepository.GetAudienceSubscribers(sampleAudienceId);
  1216. campaigns.RequestedApprovedProfiles = sampleAudienceSubscribers.Count();
  1217.  
  1218. }
  1219. AppLog.Info("Campaigns Details finished");
  1220. return View(campaigns);
  1221. }
  1222. catch (DmpException e)
  1223. {
  1224. AppLog.Error(e.Problem.Description);
  1225.  
  1226. //put this unique
  1227. return BadRequest(e.Problem.Description);
  1228. }
  1229. catch (Exception e)
  1230. {
  1231. AppLog.Error(e.ToString());
  1232.  
  1233. return BadRequest(e.Message);
  1234. }
  1235. }
  1236.  
  1237. [Authorize(Policy = "Read")]
  1238. [Authorize(Policy = "Cadet")]
  1239. [HttpGet]
  1240. public IActionResult Requests(int id)
  1241. {
  1242. try
  1243. {
  1244. AppLog.Info("Campaigns Requests started with input information [id= " + id + "]");
  1245.  
  1246. var _campaign = _campaignRepository.GetCampaign(id, ClientId);
  1247. DataBaseFunctionReturnModel getUserResponse = _userRepository.GetById(int.Parse(_campaign.CreatedBy.ToString()));
  1248. if (!getUserResponse.IsResponseCodeOK())
  1249. {
  1250. return StatusCode(getUserResponse.Code, getUserResponse.Message);
  1251. }
  1252.  
  1253. User _user = getUserResponse.ObjectNeeded as User;
  1254. if (_user == null)
  1255. {
  1256. return StatusCode(600, "User Not Found");
  1257. }
  1258.  
  1259. var getTotalProfilesResponse = _campaignAudienceSubscribers.GetAllPresentCampaignAudienceMembers(id);
  1260.  
  1261. if(!getTotalProfilesResponse.IsResponseCodeOK())
  1262. {
  1263. return StatusCode(getTotalProfilesResponse.Code, getTotalProfilesResponse.Message);
  1264. }
  1265.  
  1266. IQueryable<CampaignPresentSubscribersTable> campaignSubscribers = getTotalProfilesResponse.ObjectNeeded as IQueryable<CampaignPresentSubscribersTable>;
  1267.  
  1268. int totalProfiles = campaignSubscribers.Select(x => x.Id).Distinct().Count();
  1269.  
  1270.  
  1271. var campaigns = new CampaignsViewModel(Role)
  1272. {
  1273. Id = _campaign.Campaign.Id,
  1274. Name = _campaign.Campaign.Name,
  1275. Type = _campaign.Campaign.Type,
  1276. IsActive = _campaign.Campaign.IsActive,
  1277. CreatedBy = _campaign.Campaign.CreatedBy,
  1278. CreatedOn = _campaign.Campaign.CreatedOn,
  1279. UpdatedOn = _campaign.Campaign.UpdatedOn,
  1280. LaunchDate = _campaign.Campaign.LaunchDate,
  1281. IsPending = _campaign.Campaign.isPending,
  1282. TotalProfiles = totalProfiles,
  1283. CampaignAudiences = null,
  1284. Job = (_campaign.Campaign.Job == null)
  1285. ? null
  1286. : new JobsViewModel
  1287. {
  1288. Name = _campaign.Campaign.Job.Name,
  1289. JobNumber = _campaign.Campaign.Job.JobNumber,
  1290. BrandName = _campaign.Campaign.Job.Brand.Name,
  1291. AccountName = _campaign.Campaign.Job.Brand.Account.Name,
  1292. ClientId = ClientId
  1293. }
  1294. };
  1295.  
  1296. if (_campaign.GetType() == typeof(EmailCampaign) || _campaign.GetType() == typeof(SurveyCampaign))
  1297. campaigns.SentDate = (_campaign.SentDate == null) ? null : _campaign.SentDate;
  1298.  
  1299. if (_campaign.GetType() == typeof(SampleCampaign))
  1300. {
  1301. var getProductResponse = _productRepository.GetProduct(_campaign.ProductId);
  1302. if (!getProductResponse.IsResponseCodeOK())
  1303. {
  1304. return StatusCode(getProductResponse.Code, getProductResponse.Message);
  1305. }
  1306. Product _product = getProductResponse.ObjectNeeded as Product;
  1307. campaigns.ExtProductId = (_product._ExternalId == null) ? null : _product._ExternalId;
  1308. campaigns.ProductId = _product.Id;
  1309. //which one of the fields should we consider
  1310. campaigns.SuppliedSamples = (_campaign.SamplesNumber ?? 0);
  1311. campaigns.EndDate = (_campaign.EndDate == null) ? null : _campaign.EndDate;
  1312. }
  1313. AppLog.Info("Campaigns Requests finished");
  1314.  
  1315. return View(campaigns);
  1316. }
  1317. catch (DmpException e)
  1318. {
  1319. AppLog.Error(e.Problem.Description);
  1320.  
  1321. //put this unique
  1322. return BadRequest(e.Problem.Description);
  1323. }
  1324. catch (Exception e)
  1325. {
  1326. AppLog.Error(e.ToString());
  1327.  
  1328. return BadRequest(e.Message);
  1329. }
  1330. }
  1331.  
  1332. [Authorize(Policy = "Read")]
  1333. [Authorize(Policy = "Cadet")]
  1334. [HttpGet]
  1335. public IActionResult getProducts(int? campaignTypeId)
  1336. {
  1337. try
  1338. {
  1339. AppLog.Info("Campaigns getProducts started");
  1340.  
  1341. var getAllProductsResponse = _productRepository.GetAllProducts(ClientId);
  1342.  
  1343. if (!getAllProductsResponse.IsResponseCodeOK())
  1344. {
  1345. return StatusCode(getAllProductsResponse.Code, getAllProductsResponse.Message);
  1346. }
  1347.  
  1348. var products = getAllProductsResponse.ObjectNeeded as List<Product>;
  1349.  
  1350. if (campaignTypeId.HasValue)
  1351. {
  1352. switch ((CampaignType)campaignTypeId)
  1353. {
  1354. case CampaignType.Sample:
  1355. var dataBaseReturnModel = _requestRepository.GetRequestProductId();
  1356. var allProductWithSamples = products.Where(x => x.Sample != null && x.Sample.Count() > 0).ToList();
  1357. products = allProductWithSamples;
  1358.  
  1359. break;
  1360.  
  1361. case CampaignType.Survey:
  1362.  
  1363. break;
  1364.  
  1365. case CampaignType.Email:
  1366.  
  1367. break;
  1368.  
  1369. default:
  1370. break;
  1371. }
  1372. }
  1373.  
  1374. AppLog.Info("Campaigns getProducts finished");
  1375.  
  1376. return Ok(products
  1377. .Where(p => p.IsActive)
  1378. .Select(p => new
  1379. {
  1380. id = p.Id,
  1381. name = p.Name,
  1382. externalid = p.ExternalId,
  1383. suppliedSamples = p.Sample.FirstOrDefault(x => x.ProductId == p.Id)?.NumberOfSamples ?? 0
  1384. }));
  1385. }
  1386. catch (DmpException e)
  1387. {
  1388. AppLog.Error(e.Problem.Description);
  1389.  
  1390. //put this unique
  1391. return BadRequest(e.Problem.Description);
  1392. }
  1393. catch (Exception e)
  1394. {
  1395. AppLog.Error(e.ToString());
  1396.  
  1397. //TODO CHECK THIS GARBAGE AND PUT THIS UNIQUE
  1398. return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
  1399. {
  1400. MessageTitle = "No Content",
  1401. Message = "No Products Available.",
  1402. InternalStatusCode = 204
  1403. });
  1404. }
  1405. }
  1406.  
  1407. [Authorize(Policy = "Read")]
  1408. [Authorize(Policy = "Cadet")]
  1409. [HttpGet]
  1410. public IActionResult getSurveys()
  1411. {
  1412. try
  1413. {
  1414. AppLog.Info("Campaigns getSurveys started");
  1415.  
  1416. var allSurveysResponse = _surveyRepository.GetAll();
  1417.  
  1418. if (!allSurveysResponse.IsResponseCodeOK())
  1419. {
  1420. AppLog.Info("Campaigns getSurveys finished");
  1421. return StatusCode(allSurveysResponse.Code, allSurveysResponse.Message);
  1422. }
  1423.  
  1424. var allSurveys = allSurveysResponse.ObjectNeeded as List<Survey>;
  1425.  
  1426. AppLog.Info("Campaigns getSurveys finished");
  1427.  
  1428. return Ok(allSurveys
  1429. .Where(s => s.IsActive
  1430. && s.ClientId == ClientId)
  1431. .Select(s => new
  1432. {
  1433. id = s.Id,
  1434. name = s.Name
  1435. }));
  1436. }
  1437. catch (DmpException e)
  1438. {
  1439. AppLog.Error(e.Problem.Description);
  1440.  
  1441. //put this unique
  1442. return BadRequest(e.Problem.Description);
  1443. }
  1444. catch (Exception e)
  1445. {
  1446. AppLog.Error(e.ToString());
  1447.  
  1448. //TODO CHECK THIS GARBAGE AND PUT THIS UNIQUE
  1449. return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
  1450. {
  1451. MessageTitle = "No Content",
  1452. Message = "No products available.",
  1453. InternalStatusCode = 204
  1454. });
  1455. }
  1456. }
  1457.  
  1458. [HttpGet]
  1459. [Authorize(Policy = "Read")]
  1460. [Authorize(Policy = "Cadet")]
  1461. public IActionResult GetJobs()
  1462. {
  1463. try
  1464. {
  1465. AppLog.Info("Campaigns GetJobs started");
  1466. AppLog.Info("Campaigns GetJobs finished");
  1467.  
  1468. var databaseModel = _jobRepository.GetAll(ClientId);
  1469.  
  1470. if (!databaseModel.IsResponseCodeOK())
  1471. {
  1472. return StatusCode(databaseModel.Code, databaseModel.Message);
  1473. }
  1474.  
  1475. var jobs = databaseModel.ObjectNeeded as IQueryable<JobTable>;
  1476.  
  1477. return StatusCode(databaseModel.Code,
  1478. jobs.Where(c => c.IsActive).Select(j => new
  1479. {
  1480. id = j.Id,
  1481. name = j.JobNumber,
  1482. Brand = new Brand()
  1483. {
  1484. Name = j.Brand,
  1485. ClientId = ClientId
  1486. },
  1487. Account = new Account()
  1488. {
  1489. Name = j.Account
  1490. }
  1491. })
  1492. .ToList());
  1493. }
  1494. catch (DmpException e)
  1495. {
  1496. return StatusCode(e.Problem.StatusCode, e.Problem.InvalidParameters.First().Reason);
  1497. }
  1498. catch (Exception e)
  1499. {
  1500. return StatusCode(StatusCodes.Status500InternalServerError, $"Failed to GetJobs with message : {e.Message}");
  1501. }
  1502. }
  1503.  
  1504. [HttpGet]
  1505. [Authorize(Policy = "Read")]
  1506. [Authorize(Policy = "Cadet")]
  1507. public IActionResult GetAudiences()
  1508. {
  1509. try
  1510. {
  1511. AppLog.Info("Campaigns GetAudiences started");
  1512.  
  1513. AppLog.Info("Campaigns GetAudiences finished");
  1514.  
  1515. return Ok(_audienceRepository.Get(ClientId)
  1516. .Where(a => a.IsActive)
  1517. .Select(j => new
  1518. {
  1519. id = j.Id,
  1520. name = j.Name
  1521. }));
  1522. }
  1523. catch (DmpException e)
  1524. {
  1525. AppLog.Error(e.Problem.Description);
  1526.  
  1527. //put this unique
  1528. return BadRequest(e.Problem.Description);
  1529. }
  1530. catch (Exception e)
  1531. {
  1532. AppLog.Error(e.ToString());
  1533.  
  1534. return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
  1535. {
  1536. MessageTitle = "No Content",
  1537. Message = "Id Audience Invalid.",
  1538. InternalStatusCode = 204
  1539. });
  1540. }
  1541. }
  1542.  
  1543. //need to be revisited
  1544. [HttpGet]
  1545. [Authorize(Policy = "Read")]
  1546. [Authorize(Policy = "Cadet")]
  1547. public IActionResult GetRequestedSamples(State state, int id, TableModelView model)
  1548. {
  1549.  
  1550. try
  1551. {
  1552. AppLog.Info("Campaigns GetRequestedSamples started with input information [id= " + id + "]");
  1553.  
  1554. var campaign = _campaignRepository.GetCampaign(id, ClientId) as SampleCampaign;
  1555.  
  1556. if (campaign == null)
  1557. {
  1558. return StatusCode(StatusCodes.Status404NotFound, new ServiceResponse()
  1559. {
  1560. MessageTitle = "Wrong",
  1561. Message = "Wrong identifier for sample campaign.",
  1562. InternalStatusCode = 404
  1563. });
  1564. }
  1565. var getTotalProfilesResponse = this._campaignAudienceSubscribers.GetAllPresentCampaignAudienceMembers(id);
  1566. if (!getTotalProfilesResponse.IsResponseCodeOK())
  1567. {
  1568. return StatusCode(getTotalProfilesResponse.Code, getTotalProfilesResponse.Message);
  1569. }
  1570. IQueryable<CampaignPresentSubscribersTable> campaignSubscribers = getTotalProfilesResponse.ObjectNeeded as IQueryable<CampaignPresentSubscribersTable>;
  1571.  
  1572.  
  1573.  
  1574.  
  1575. if (campaignSubscribers == null || campaignSubscribers.Count() == 0)
  1576. {
  1577. PageResponse<SubscriberViewModel> emptyResponse = new PageResponse<SubscriberViewModel>();
  1578. emptyResponse.Elems = new List<SubscriberViewModel>();
  1579. emptyResponse.Direction = model.Direction;
  1580. emptyResponse.OrderBy = model.OrderBy;
  1581. emptyResponse.PageSize = model.PageSize;
  1582. emptyResponse.Search = model.Search;
  1583. emptyResponse.Page = model.Page;
  1584. return StatusCode(200, emptyResponse);
  1585. }
  1586. campaignSubscribers = campaignSubscribers.Where(x => x.Status == (int)state);
  1587.  
  1588. if (campaign.Campaign.CampaignAudiences != null)
  1589. {
  1590. //var audienceIds = campaign.Campaign.CampaignAudiences.Select(cmp => cmp.AudienceId);
  1591.  
  1592. AppLog.Info("Campaigns GetRequestedSamples finished");
  1593.  
  1594. return Ok(this._audiencePresentPaginatedViewModelFactory.Create(
  1595. () => campaignSubscribers,
  1596. subscriber => new SubscriberViewModel
  1597. {
  1598. FirstName = subscriber.FirstName,
  1599. LastName = subscriber.LastName,
  1600. City = subscriber.City,
  1601. State = subscriber.State,
  1602. ZipCode = subscriber.ZipCode,
  1603. CreatedOn = subscriber.CreatedOn,
  1604. IsActive = subscriber.IsActive,
  1605. ProfileScore=subscriber.ProfileScore,
  1606. UserScore=subscriber.UserScore,
  1607. ReviewScore=subscriber.ReviewScore,
  1608. Id = subscriber.Id
  1609. },
  1610. model.Page,
  1611. model.PageSize,
  1612. model.Search,
  1613. model.OrderBy,
  1614. model.Direction
  1615. ));
  1616. }
  1617. }
  1618. catch (DmpException e)
  1619. {
  1620. AppLog.Error(e.Problem.Description);
  1621.  
  1622. return BadRequest(e.Problem.Description);
  1623. }
  1624. catch (Exception e)
  1625. {
  1626. AppLog.Error(e.ToString());
  1627. return StatusCode(StatusCodes.Status400BadRequest, new ServiceResponse()
  1628. {
  1629. MessageTitle = "Error",
  1630. Message = "Error on getting samples requests.",
  1631. InternalStatusCode = 400
  1632. });
  1633. }
  1634. return StatusCode(StatusCodes.Status400BadRequest, new ServiceResponse()
  1635. {
  1636. MessageTitle = "Error",
  1637. Message = "Error on getting samples requests.",
  1638. InternalStatusCode = 400
  1639. });
  1640.  
  1641. }
  1642.  
  1643. [HttpGet]
  1644. [EnableCors("CorsPolicy")]
  1645. [Authorize(Policy = "Read")]
  1646. [Authorize(Policy = "Cadet")]
  1647. [Route("campaigns/mailchimpEmailCampaignDetails/{id}")]
  1648. public ActionResult GetMailChimpEmailCampaignDetails(int id)
  1649. {
  1650. try
  1651. {
  1652. AppLog.Info("Campaigns GetMailChimpEmailCampaignDetails started with input information [id= " + id + "]");
  1653.  
  1654. var ExternalClientObject = _clientRepository.GetExternalServices(ClientId).Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim()).FirstOrDefault();
  1655. var client = _clientRepository.GetById(ClientId);
  1656. var emailCampaign = (EmailCampaign)_campaignRepository.GetCampaign(id, ClientId);
  1657. MailChimpKeyStore manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
  1658. string mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
  1659. MailChimpNewService mailchimp = new MailChimpNewService();
  1660. if (emailCampaign.ServiceId == null)
  1661. {
  1662. return BadRequest(new Exception("Campaign does not exist in mailChimp"));
  1663. }
  1664. else
  1665. {
  1666. var mailChimpResponse = mailchimp.GetCampaignInformationById(emailCampaign.ServiceId, mailchimpKey);
  1667. if (mailChimpResponse == null)
  1668. {
  1669. return BadRequest(new Exception("Error Calling MailChimp"));
  1670. }
  1671. AppLog.Info("Campaigns GetMailChimpEmailCampaignDetails finished");
  1672.  
  1673. return Ok(mailChimpResponse.RedirectLink);
  1674. }
  1675. }
  1676. catch (DmpException e)
  1677. {
  1678. AppLog.Error(e.Problem.Description);
  1679.  
  1680. return BadRequest(e.Problem.Description);
  1681. }
  1682. catch (Exception e)
  1683. {
  1684. AppLog.Error(e.ToString());
  1685.  
  1686. return BadRequest(e.Message);
  1687. }
  1688. }
  1689.  
  1690. [HttpGet]
  1691. [EnableCors("CorsPolicy")]
  1692. [Authorize(Policy = "Read")]
  1693. [Authorize(Policy = "Cadet")]
  1694. [Route("campaigns/mailchimpSurveyCampaignDetails/{id}")]
  1695. public ActionResult GetMailChimpSurveyCampaignDetails(int id)
  1696. {
  1697. try
  1698. {
  1699. AppLog.Info("Campaigns GetMailChimpSurveyCampaignDetails started with input information [id= " + id + "]");
  1700.  
  1701. var ExternalClientObject = _clientRepository.GetExternalServices(ClientId).Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim()).FirstOrDefault();
  1702. var client = _clientRepository.GetById(ClientId);
  1703. var emailCampaign = (SurveyCampaign)_campaignRepository.GetCampaign(id, ClientId);
  1704. MailChimpKeyStore manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
  1705. string mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
  1706. MailChimpNewService mailchimp = new MailChimpNewService();
  1707. if (emailCampaign.ServiceId == null)
  1708. {
  1709. return BadRequest(new Exception("Campaign does not exist in mailChimp"));
  1710. }
  1711. else
  1712. {
  1713. var mailChimpResponse = mailchimp.GetCampaignInformationById(emailCampaign.ServiceId, mailchimpKey);
  1714. if (mailChimpResponse == null)
  1715. {
  1716. return BadRequest(new Exception("Error Calling MailChimp"));
  1717. }
  1718. AppLog.Info("Campaigns GetMailChimpSurveyCampaignDetails finished");
  1719.  
  1720. return Ok(mailChimpResponse.RedirectLink);
  1721. }
  1722. }
  1723. catch (DmpException e)
  1724. {
  1725. AppLog.Error(e.Problem.Description);
  1726.  
  1727. return BadRequest(e.Problem.Description);
  1728. }
  1729. catch (Exception e)
  1730. {
  1731. AppLog.Error(e.ToString());
  1732.  
  1733. return BadRequest(e.Message);
  1734. }
  1735. }
  1736.  
  1737. [HttpGet]
  1738. [EnableCors("CorsPolicy")]
  1739. [Authorize(Policy = "Read")]
  1740. [Authorize(Policy = "Cadet")]
  1741. [Route("campaigns/ExportEmailCampaign/{id}")]
  1742. public ActionResult ExportEmailCampaign(int id)
  1743. {
  1744. try
  1745. {
  1746. AppLog.Info("Campaigns ExportEmailCampaign started with input information [id= " + id + "]");
  1747.  
  1748. MailChimpCreateCampaignResponseModel campaignResponse;
  1749.  
  1750. using (var scope = new TransactionScope())
  1751. {
  1752.  
  1753. var emailCampaign = (EmailCampaign)_campaignRepository.GetCampaign(id, ClientId);
  1754.  
  1755. if (emailCampaign.ServiceId != null)
  1756. {
  1757. return BadRequest("Campaign already in MailChimp");
  1758. }
  1759. if(emailCampaign==null || emailCampaign.Campaign.CampaignAudiences==null || emailCampaign.Campaign.CampaignAudiences.Count() == 0)
  1760. {
  1761. return StatusCode(600,"Campaign Without Audiences Associated");
  1762. }
  1763.  
  1764. var ExternalClientObject = _clientRepository.GetExternalServices(ClientId)
  1765. .Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
  1766. .FirstOrDefault();
  1767.  
  1768. var client = _clientRepository.GetById(ClientId);
  1769.  
  1770. var mailchimp = new MailChimpNewService();
  1771. var manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
  1772. var mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
  1773.  
  1774. var mailChimpListModel = ExportAudienceToMailChimp(id).Result;
  1775.  
  1776. if (mailChimpListModel.Errors.Count() > 0)
  1777. {
  1778. mailchimp.DeleteAudience(mailChimpListModel.ListId, mailchimpKey);
  1779.  
  1780. var errors = string.Join(", ", mailChimpListModel.Errors);
  1781.  
  1782. return BadRequest($"Error to export audience to MailChimp: {errors}");
  1783. }
  1784.  
  1785.  
  1786. var segId = mailChimpListModel.ListId;
  1787.  
  1788. if (segId == null)
  1789. {
  1790. throw new Exception("This campaign's audience has not been exported yet");
  1791. }
  1792.  
  1793. campaignResponse = mailchimp.CreateNewMailChimpCampaign(segId, id, null, emailCampaign.Campaign.Name, mailchimpKey);
  1794.  
  1795. if (campaignResponse == null)
  1796. {
  1797. throw new Exception("No API Key associated with this client.");
  1798. }
  1799.  
  1800. bool updateExternalIdResult = _campaignRepository.UpdateEmailCampaignExternalCampaignId(emailCampaign.Id, campaignResponse.Id);
  1801.  
  1802. if (!updateExternalIdResult)
  1803. {
  1804. return BadRequest("Error Setting ExternalId");
  1805. }
  1806. scope.Complete();
  1807. }
  1808.  
  1809. AppLog.Info("Campaigns ExportEmailCampaign finished");
  1810.  
  1811. return Ok(campaignResponse.RedirectLink);
  1812. }
  1813. catch (DmpException e)
  1814. {
  1815. AppLog.Error(e.Problem.Description);
  1816.  
  1817. return BadRequest(e.Problem.Description);
  1818. }
  1819. catch (Exception e)
  1820. {
  1821. AppLog.Error(e.ToString());
  1822.  
  1823. return BadRequest(e.Message);
  1824. }
  1825. }
  1826.  
  1827. [HttpGet]
  1828. [Authorize(Policy = "Read")]
  1829. [Authorize(Policy = "Cadet")]
  1830. [Route("campaigns/audienceLists")]
  1831. public IActionResult GetCampaignLists(TableModelView model)
  1832. {
  1833. try
  1834. {
  1835. AppLog.Info("GetCampaignLists started");
  1836. AppLog.Info("GetCampaignLists finished");
  1837.  
  1838. return Ok(this._campaignListsPaginatedViewModelFactory.Create(
  1839. () => this._campaignRepository.GetCampaignAudienceLists(model.Id),
  1840. list => new CampaignListViewModel
  1841. {
  1842. Id = list.Id,
  1843. Name = list.Name,
  1844. AudienceId = list.AudienceId,
  1845. CampaignId = list.CampaignId,
  1846. CreatedOn = list.CreatedOn,
  1847. ClientId = list.ClientId,
  1848. NumberSubscribers = list.NumberSubscribers
  1849. },
  1850. model.Page,
  1851. model.PageSize,
  1852. model.Search,
  1853. model.OrderBy,
  1854. model.Direction));
  1855. }
  1856. catch (DmpException e)
  1857. {
  1858. AppLog.Error(e.Problem.Description);
  1859.  
  1860. return BadRequest(e.Problem.Description);
  1861. }
  1862. catch (Exception e)
  1863. {
  1864. AppLog.Error(e.ToString());
  1865.  
  1866. return BadRequest(e.Message);
  1867. }
  1868. }
  1869.  
  1870. [HttpGet]
  1871. [EnableCors("CorsPolicy")]
  1872. [Authorize(Policy = "Read")]
  1873. [Authorize(Policy = "Cadet")]
  1874. [Route("campaigns/exportSurvey/{id}")]
  1875. public ActionResult ExportSurveyCampaign(int id, string textToAppend = "")
  1876. {
  1877. try
  1878. {
  1879. AppLog.Info("Campaigns ExportSurveyCampaign started with input information [id= " + id + "]");
  1880.  
  1881. MailChimpCreateCampaignResponseModel campaignResponse;
  1882.  
  1883. using (var scope = new TransactionScope())
  1884. {
  1885.  
  1886. var surveyCampaign = (SurveyCampaign)_campaignRepository.GetCampaign(id, ClientId);
  1887.  
  1888. if (surveyCampaign.ServiceId != null)
  1889. {
  1890. return BadRequest("Campaign already in MailChimp");
  1891. }
  1892. if(surveyCampaign.Campaign.CampaignAudiences==null ||surveyCampaign.Campaign.CampaignAudiences.Count()==0)
  1893. {
  1894. return StatusCode(600,"Campaign Without Audiences Associated");
  1895. }
  1896.  
  1897. var ExternalClientObject = _clientRepository.GetExternalServices(ClientId)
  1898. .Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
  1899. .FirstOrDefault();
  1900.  
  1901. var client = _clientRepository.GetById(ClientId);
  1902.  
  1903. var mailchimp = new MailChimpNewService();
  1904. var manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
  1905. var mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
  1906.  
  1907. var mailChimpListModel = ExportAudienceToMailChimp(id).Result;
  1908.  
  1909. if (mailChimpListModel.Errors.Count() > 0)
  1910. {
  1911. var errors = string.Join(", ", mailChimpListModel.Errors);
  1912.  
  1913. return BadRequest($"Error to export audience to MailChimp: {errors}");
  1914. }
  1915.  
  1916.  
  1917.  
  1918.  
  1919. var databaseModel = _campaignAudienceSubscribers.BuildCampaignSubscribers(mailChimpListModel.CampaignGuid, mailChimpListModel.ListId, UserId()).Result; // Distinc data to send to Mail Chimp
  1920. if (!databaseModel.IsResponseCodeOK())
  1921. {
  1922. return StatusCode(databaseModel.Code, databaseModel.Message);
  1923. }
  1924. var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
  1925.  
  1926. var subscribersEmail = campaignSubscribers
  1927. .Select(cmp => cmp.SubscriberEmail)
  1928. .ToList();
  1929.  
  1930. if (subscribersEmail.Count() == 0)
  1931. {
  1932. return StatusCode(StatusCodes.Status406NotAcceptable, "Audience without subscribers");
  1933. }
  1934.  
  1935. var segId = mailChimpListModel.ListId;
  1936.  
  1937. if (segId == null)
  1938. {
  1939. throw new Exception("This campaign's audience has not been exported yet");
  1940. }
  1941.  
  1942. var uri = HttpContext.Request.Host;
  1943. var url = string.Concat(HttpContext.Request.Scheme, "://", uri);
  1944.  
  1945. AppLog.Info(uri.ToString());
  1946.  
  1947. var getEmailSurveyResponse = _surveyRepository.GetSurveyEmail(surveyCampaign.SurveyId, ClientId, Environment.GetEnvironmentVariable("APPSETTING_CallbackURL") ?? url, new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("DMP.Web.Resources.SurveyEmailTemplate.html")).ReadToEnd(), textToAppend);
  1948.  
  1949. if (!getEmailSurveyResponse.IsResponseCodeOK())
  1950. {
  1951. return StatusCode(getEmailSurveyResponse.Code, getEmailSurveyResponse.Message);
  1952. }
  1953.  
  1954. var survey = getEmailSurveyResponse.ObjectNeeded as string;
  1955. var audienceIds = surveyCampaign.Campaign.CampaignAudiences.Select(cmp => cmp.AudienceId);
  1956. var createRequestsResponse = _surveyRepository.CreateRequests(surveyCampaign.SurveyId, UserId(), audienceIds);
  1957.  
  1958. if (!createRequestsResponse.IsResponseCodeOK())
  1959. {
  1960. return StatusCode(createRequestsResponse.Code, createRequestsResponse.Message);
  1961. }
  1962.  
  1963. campaignResponse = mailchimp.CreateNewMailChimpCampaign(segId, id, survey, surveyCampaign.Campaign.Name, mailchimpKey);
  1964.  
  1965. if (campaignResponse == null)
  1966. {
  1967. throw new Exception("No API Key associated with this client.");
  1968. }
  1969.  
  1970. _campaignRepository.AssociateSegmentId(surveyCampaign.Id, campaignResponse.Id);
  1971.  
  1972. var subscriberIds = _audienceRepository.GetAudienceSubscribersByCampaign(surveyCampaign.Campaign.Id)
  1973. .Select(cmp => cmp.Id);
  1974.  
  1975.  
  1976. foreach (var subscriberId in subscriberIds)
  1977. {
  1978. _subscriberAggregateDataRepository.AddSubscriberSurveyToCount(subscriberId);
  1979. }
  1980. scope.Complete();
  1981. //Task<DataBaseFunctionReturnModel> task = Task<DataBaseFunctionReturnModel>.Factory.StartNew(() =>
  1982. //{
  1983. //DataBaseFunctionReturnModel recomputeAllScoresReponse;
  1984. //recomputeAllScoresReponse = ;
  1985. //if (!recomputeAllScoresReponse.IsResponseCodeOK())
  1986. //{
  1987. // return StatusCode(recomputeAllScoresReponse.Code, recomputeAllScoresReponse.Message);
  1988. //}
  1989. //recomputeAllScoresReponse = _subscriberScoresRepository.RecomputeAllProfileScores();
  1990. //if (!recomputeAllScoresReponse.IsResponseCodeOK())
  1991. //{
  1992. // return StatusCode(recomputeAllScoresReponse.Code, recomputeAllScoresReponse.Message);
  1993. //}
  1994. // return StatusCode(200, "Scores Updated");
  1995. //});
  1996. //if(task.Result.)
  1997. }
  1998. var jobId = Hangfire.BackgroundJob.Enqueue(() => _subscriberScoresRepository.RecomputeAllUserScores(ClientId));
  1999. Hangfire.BackgroundJob.ContinueWith(jobId, () => _subscriberScoresRepository.RecomputeAllProfileScores(ClientId));
  2000. AppLog.Info("Campaigns ExportSurveyCampaign finished");
  2001.  
  2002. return Ok(campaignResponse.RedirectLink);
  2003. }
  2004. catch (DmpException e)
  2005. {
  2006. AppLog.Error(e.Problem.Description);
  2007.  
  2008. return BadRequest(e.Problem.Description);
  2009. }
  2010. catch (Exception e)
  2011. {
  2012. AppLog.Error(e.ToString());
  2013.  
  2014. return BadRequest(e.Message);
  2015. }
  2016. }
  2017.  
  2018. [HttpGet]
  2019. [Authorize(Policy = "Read")]
  2020. [Authorize(Policy = "Cadet")]
  2021. [Route("campaigns/ExportSampleCampaign/{id}")]
  2022. public ActionResult ExportSampleCampaign(int id)
  2023. {
  2024. try
  2025. {
  2026. AppLog.Info($"Campaigns ExportSampleCampaign started with input information [id= {id}]");
  2027.  
  2028. var sampleCampaign = (SampleCampaign)_campaignRepository.GetCampaign(id, ClientId);
  2029.  
  2030. if (sampleCampaign == null || sampleCampaign.Campaign.CampaignAudiences == null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
  2031. {
  2032. return StatusCode(600, "Campaign Without Audiences Associated");
  2033. }
  2034.  
  2035. var getProductResponse = _productRepository.GetProduct(sampleCampaign.ProductId);
  2036.  
  2037. if (!getProductResponse.IsResponseCodeOK())
  2038. {
  2039. return StatusCode(getProductResponse.Code, getProductResponse.Message);
  2040. }
  2041.  
  2042. var prod = getProductResponse.ObjectNeeded as Product;
  2043.  
  2044. var prodInfo = new List<(string, string)>
  2045. {
  2046. ("Product Name:", prod.Name),
  2047. ("Product ID: ", prod.ExternalId.Split('_')[1]),
  2048. ("Sample Campaign Name: ", sampleCampaign.Campaign.Name),
  2049. ("Supplied Samples: ", sampleCampaign.SamplesNumber.ToString())
  2050. };
  2051.  
  2052. if (!sampleCampaign.Campaign.IsActive)
  2053. {
  2054. return StatusCode(StatusCodes.Status406NotAcceptable, new ServiceResponse()
  2055. {
  2056. MessageTitle = "Audience has not been generated",
  2057. Message = "Audience has not been generated",
  2058. InternalStatusCode = 406
  2059. });
  2060. }
  2061.  
  2062. if (sampleCampaign.Campaign.CampaignAudiences != null)
  2063. {
  2064.  
  2065.  
  2066. var subscribers = _audienceRepository.GetAudienceSubscribersByCampaign(sampleCampaign.Campaign.Id)
  2067. .GroupBy(x => x.Id)
  2068. .Select(x => x.First())
  2069. .ToList();
  2070.  
  2071. DataBaseFunctionReturnModel databaseModel;
  2072.  
  2073. databaseModel = _campaignAudienceSubscribers.GetCampaignSubscribers(id);
  2074.  
  2075. if (!databaseModel.IsResponseCodeOK())
  2076. {
  2077. return StatusCode(databaseModel.Code, databaseModel.Message);
  2078. }
  2079.  
  2080. var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
  2081.  
  2082. var items = subscribers
  2083. .Where(cmp => campaignSubscribers.Any(cmp2 => cmp2.SubscriberId == cmp.Id))
  2084. .Select(cmp => new[]
  2085. {
  2086. string.Concat(cmp.FirstName, " ", cmp.LastName),
  2087. cmp.Email,
  2088. $"{cmp.State}, {cmp.City}, {cmp.AddressLineOne}, {cmp.AddressLineTwo}, {cmp.ZipCode} "
  2089. });
  2090.  
  2091. var doc = _documentHandler.initFile()
  2092. .AddInfo(prodInfo, "Product")
  2093. .AddList(items, "Adressee Info", new[] { "Name", "Email", "Address" });
  2094.  
  2095. var httpResponse = Response;
  2096.  
  2097. httpResponse.Clear();
  2098. httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  2099. httpResponse.Headers.Add("content-disposition", "attachment;filename=\"Fullfillment_List.xlsx\"");
  2100.  
  2101. using (var memoryStream = new MemoryStream())
  2102. {
  2103. doc.SaveAs(memoryStream);
  2104. memoryStream.Position = 0;
  2105.  
  2106. var res = memoryStream.ReadFully();
  2107.  
  2108. AppLog.Info("Campaigns ExportSampleCampaign finished");
  2109.  
  2110. return File(res, "application/octet-stream");
  2111. }
  2112. }
  2113.  
  2114. throw new Exception("This campaign does not have any subscribers associated");
  2115. }
  2116. catch (DmpException e)
  2117. {
  2118. AppLog.Error(e.Problem.Description);
  2119.  
  2120. return BadRequest(e.Problem.Description);
  2121. }
  2122. catch (Exception e)
  2123. {
  2124. AppLog.Error(e.ToString());
  2125. return BadRequest(e.Message);
  2126. }
  2127. }
  2128.  
  2129. [HttpGet]
  2130. [Authorize(Policy = "Read")]
  2131. [Authorize(Policy = "Cadet")]
  2132. public IActionResult GetAudienceToData(TableModelView model)
  2133. {
  2134. try
  2135. {
  2136. AppLog.Info("Campaigns GetAudienceToData started");
  2137. AppLog.Info("Campaigns GetAudienceToData finished");
  2138.  
  2139. //MISSING IS PENDING FROM CAMPAIGN AND SYNCED FROM AUDIENCE
  2140. return Ok(this.audiencePaginatedViewModelFactory.Create(
  2141. () => this._campaignRepository.GetCampaignAudiences(model.Id, ClientId),
  2142. audience => new AudiencesViewModel
  2143. {
  2144. Id = audience.Id,
  2145. Name = audience.Name,
  2146. CreatedOn = audience.CreatedOn,
  2147. UpdatedOn = audience.UpdatedOn,
  2148. IsActive = audience.IsActive,
  2149. AudienceMembers = audience.AudienceSubscriberCount
  2150. },
  2151. model.Page,
  2152. model.PageSize,
  2153. model.Search,
  2154. model.OrderBy,
  2155. model.Direction));
  2156. }
  2157. catch (DmpException e)
  2158. {
  2159. AppLog.Error(e.Problem.Description);
  2160.  
  2161. return BadRequest(e.Problem.Description);
  2162. }
  2163. catch (Exception e)
  2164. {
  2165. AppLog.Error(e.ToString());
  2166.  
  2167. return BadRequest(e.Message);
  2168. }
  2169. }
  2170.  
  2171. [HttpGet]
  2172. [Authorize(Policy = "Read")]
  2173. [Authorize(Policy = "Cadet")]
  2174. public IActionResult GetCampaignToData(TableModelView model, CampaignType? type)
  2175. {
  2176. try
  2177. {
  2178. AppLog.Info("Campaigns GetCampaignToData Paging started");
  2179.  
  2180. AppLog.Info("Campaigns GetCampaignToData Paging finished");
  2181.  
  2182. //MISSING IS PENDING FROM CAMPAIGN AND SYNCED FROM AUDIENCE
  2183. return Ok(this.campaignPaginatedViewModelFactory.Create(
  2184. () => this._campaignRepository.GetAll(ClientId, type),
  2185. campaign => new CampaignsViewModel
  2186. {
  2187. Id = campaign.Id,
  2188. Name = campaign.Name,
  2189. JobNumber = campaign.JobNumber,
  2190. Account = campaign.Account,
  2191. Brand = campaign.Brand,
  2192. CreatedOn = campaign.CreatedOn,
  2193. Type = campaign.Type,
  2194. IsActive = campaign.IsActive,
  2195. IsPending = campaign.IsPending
  2196. },
  2197. model.Page,
  2198. model.PageSize,
  2199. model.Search,
  2200. model.OrderBy,
  2201. model.Direction));
  2202. }
  2203. catch (DmpException e)
  2204. {
  2205. AppLog.Error(e.Problem.Description);
  2206.  
  2207. return BadRequest(e.Problem.Description);
  2208. }
  2209. catch (Exception e)
  2210. {
  2211. AppLog.Error(e.ToString());
  2212.  
  2213. return BadRequest(e.Message);
  2214. }
  2215. }
  2216.  
  2217. [HttpGet]
  2218. [Authorize(Policy = "Read")]
  2219. [Authorize(Policy = "Cadet")]
  2220. [Route("campaigns/ExportToExcel")]
  2221. public ActionResult ExportToExcel()
  2222. {
  2223. try
  2224. {
  2225. AppLog.Info("ExportToExcel started");
  2226.  
  2227. var clientName = _clientRepository.GetById(ClientId).Name;
  2228. var campaigns = _campaignRepository.GetAll(ClientId);
  2229. var sampleCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Sample);
  2230. var emailCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Email);
  2231. var surveyCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Survey);
  2232.  
  2233. if (campaigns.Count() == 0)
  2234. {
  2235. return StatusCode(600, "This Client does not have any Campaigns associated");
  2236. }
  2237.  
  2238. var itemsCampaigns = campaigns.Select(campaign => new[]
  2239. {
  2240. campaign.Name ?? "--",
  2241. campaign.JobNumber ?? "--",
  2242. campaign.Account ?? "--",
  2243. campaign.Brand ?? "--",
  2244. campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
  2245. campaign.Type.ToString() ?? "--",
  2246. campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
  2247. }).ToList();
  2248.  
  2249. List<string[]> itemsSampleCampaigns = new List<string[]>();
  2250. List<string[]> itemsEmailCampaigns = new List<string[]>();
  2251. List<string[]> itemsSurveyCampaigns = new List<string[]>();
  2252.  
  2253. if (sampleCampaigns.Count() != 0)
  2254. {
  2255. itemsSampleCampaigns = sampleCampaigns.Select(campaign => new[]
  2256. {
  2257. campaign.Name ?? "--",
  2258. campaign.JobNumber ?? "--",
  2259. campaign.Account ?? "--",
  2260. campaign.Brand ?? "--",
  2261. campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
  2262. campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
  2263. }).ToList();
  2264. }
  2265.  
  2266. if (emailCampaigns.Count() != 0)
  2267. {
  2268. itemsEmailCampaigns = emailCampaigns.Select(campaign => new[]
  2269. {
  2270. campaign.Name ?? "--",
  2271. campaign.JobNumber ?? "--",
  2272. campaign.Account ?? "--",
  2273. campaign.Brand ?? "--",
  2274. campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
  2275. campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") :"Inactive"
  2276. }).ToList();
  2277. }
  2278.  
  2279. if (emailCampaigns.Count() != 0)
  2280. {
  2281. itemsSurveyCampaigns = surveyCampaigns.Select(campaign => new[]
  2282. {
  2283. campaign.Name ?? "--",
  2284. campaign.JobNumber ?? "--",
  2285. campaign.Account ?? "--",
  2286. campaign.Brand ?? "--",
  2287. campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
  2288. campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
  2289. }).ToList();
  2290. }
  2291.  
  2292. var doc = _documentHandler.initFile().AddList(itemsCampaigns, $"Campaigns",
  2293. new[]
  2294. {
  2295. "Name:",
  2296. "Job Number:",
  2297. "Account:",
  2298. "Brand:",
  2299. "Created On:",
  2300. "Type:",
  2301. "Status:"
  2302. }
  2303. ).AddList(itemsSampleCampaigns, $"Sample Campaigns",
  2304. new[]
  2305. {
  2306. "Name:",
  2307. "Job Number:",
  2308. "Account:",
  2309. "Brand:",
  2310. "Created On:",
  2311. "Status:"
  2312. }
  2313. ).AddList(itemsEmailCampaigns, $"Email Campaigns",
  2314. new[]
  2315. {
  2316. "Name:",
  2317. "Job Number:",
  2318. "Account:",
  2319. "Brand:",
  2320. "Created On:",
  2321. "Status:"
  2322. }
  2323. ).AddList(itemsSurveyCampaigns, $"Survey Campaigns",
  2324. new[]
  2325. {
  2326. "Name:",
  2327. "Job Number:",
  2328. "Account:",
  2329. "Brand:",
  2330. "Created On:",
  2331. "Status:"
  2332. }
  2333. );
  2334.  
  2335. HttpResponse httpResponse = Response;
  2336. httpResponse.Clear();
  2337. httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  2338. httpResponse.Headers.Add("content-disposition", $"attachment;filename=\"{clientName}'s Campaigns.xlsx\"");
  2339. using (MemoryStream memoryStream = new MemoryStream())
  2340. {
  2341. doc.SaveAs(memoryStream);
  2342. memoryStream.Position = 0;
  2343. var res = memoryStream.ReadFully();
  2344. AppLog.Info("ExportToExcel finished");
  2345.  
  2346. return File(res, "application/octet-stream");
  2347. }
  2348. }
  2349. catch (DmpException e)
  2350. {
  2351. AppLog.Error(e.Problem.Description);
  2352.  
  2353. return BadRequest(e.Problem.Description);
  2354. }
  2355. catch (Exception e)
  2356. {
  2357. AppLog.Error(e.ToString());
  2358.  
  2359. return BadRequest(e.Message);
  2360. }
  2361. }
  2362.  
  2363. [HttpGet]
  2364. [Authorize(Policy = "Read")]
  2365. [Authorize(Policy = "Cadet")]
  2366. [Route("campaigns/RedirectSampleAudience/Campaigns/{campaignId}")]
  2367. public IActionResult RedirectCampaignSampleAudience(int campaignId)
  2368. {
  2369. AppLog.Info($"RedirectCampaignSampleAudience started with input information [campaignId= {campaignId}]");
  2370. try
  2371. {
  2372. var databaseModel = _audienceRepository.GetAudienceByCampaign(campaignId, ClientId);
  2373.  
  2374. if (!databaseModel.IsResponseCodeOK())
  2375. {
  2376. return StatusCode(databaseModel.Code, databaseModel.Message);
  2377. }
  2378.  
  2379. var campaign = databaseModel.ObjectNeeded as Campaign;
  2380.  
  2381. var campaignAudiences = campaign.CampaignAudiences
  2382. .Where(cmp => cmp.Audience.SampleAudience);
  2383.  
  2384. if (campaignAudiences==null ||campaignAudiences.Count() == 0)
  2385. {
  2386. return StatusCode(600, "There is no Sample Audience type for Campaign");
  2387. }
  2388.  
  2389. var audienceId = campaignAudiences
  2390. .FirstOrDefault().AudienceId;
  2391.  
  2392. AppLog.Info("RedirectCampaignSampleAudience finished");
  2393.  
  2394. return RedirectToAction("Details", "Audiences", new { Id = audienceId });
  2395. }
  2396. catch (DmpException e)
  2397. {
  2398. AppLog.Error(e.Problem.Description);
  2399.  
  2400. return BadRequest(e.Problem.Description);
  2401. }
  2402. catch (Exception e)
  2403. {
  2404. AppLog.Error(e.ToString());
  2405.  
  2406. return BadRequest(e.Message);
  2407. }
  2408. }
  2409.  
  2410. #endregion
  2411.  
  2412. #region PRIVATE
  2413.  
  2414.  
  2415. private bool CreateSampleCampaignLists(int id)
  2416. {
  2417. try
  2418. {
  2419. var sampleCampaign = (SampleCampaign)_campaignRepository.GetCampaign(id, ClientId);
  2420.  
  2421. if (sampleCampaign == null || sampleCampaign.Campaign.CampaignAudiences == null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
  2422. {
  2423. return false;
  2424. }
  2425.  
  2426. if (sampleCampaign.Campaign.CampaignAudiences != null)
  2427. {
  2428. DataBaseFunctionReturnModel databaseModel;
  2429.  
  2430. using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
  2431. {
  2432. databaseModel = _campaignAudienceSubscribers.CreateCampaignAudienceSubscribers(id, UserId()).Result; // Create core data to send to Mail Chimp
  2433.  
  2434. if (!databaseModel.IsResponseCodeOK() && databaseModel.Code != DatabaseCodes.AlreadyExists)
  2435. {
  2436. return false ;
  2437.  
  2438. }
  2439.  
  2440. if (databaseModel.IsResponseCodeOK())
  2441. {
  2442. var guid = (Guid)databaseModel.ObjectNeeded;
  2443.  
  2444. databaseModel = _campaignAudienceSubscribers.CreateCampaignSubscribers(guid, string.Empty, UserId()).Result; // Create distinct data by subscriber
  2445. }
  2446. scope.Complete();
  2447. return true;
  2448. }
  2449. }
  2450. return false;
  2451.  
  2452. }catch(Exception e)
  2453. {
  2454. return false;
  2455. }
  2456. }
  2457. private async Task<MailChimpListModel> ExportAudienceToMailChimp(int campaignId)
  2458. {
  2459. var mailChimpListModel = new MailChimpListModel()
  2460. {
  2461. Errors = new List<MailChimpErrorModel>()
  2462. };
  2463.  
  2464. try
  2465. {
  2466. AppLog.Info($"ExportAudienceToMailChimp with input information [campaignId= {campaignId}]");
  2467.  
  2468. using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
  2469. {
  2470. var campaign = _campaignRepository.GetById(campaignId, ClientId);
  2471.  
  2472. if (campaign == null)
  2473. {
  2474. mailChimpListModel.Errors.Add(AddMailChimpError("Campaign do not exists"));
  2475.  
  2476. return mailChimpListModel;
  2477. }
  2478.  
  2479. var databaseModel = await _campaignAudienceSubscribers.CreateCampaignAudienceSubscribers(campaignId, UserId()); // Create core data to send to Mail Chimp
  2480.  
  2481. if (!databaseModel.IsResponseCodeOK())
  2482. {
  2483. mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
  2484.  
  2485. return mailChimpListModel;
  2486. }
  2487.  
  2488. var guid = (Guid)databaseModel.ObjectNeeded;
  2489.  
  2490. var client = _clientRepository.GetById(ClientId);
  2491. var mailChimpUtil = new MailChimpUtil();
  2492. var manageKeyStore = mailChimpUtil.CreateMailChimpKeyStore(client.Email, client.Salt);
  2493.  
  2494. if (manageKeyStore == null)
  2495. {
  2496. mailChimpListModel.Errors.Add(AddMailChimpError("Error Creating MailChimp Key Store"));
  2497.  
  2498. return mailChimpListModel;
  2499. }
  2500.  
  2501. var externalService = _clientRepository.GetExternalServices(ClientId)
  2502. .Where(cmp => cmp.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
  2503. .FirstOrDefault();
  2504.  
  2505. var mailchimpKey = manageKeyStore.Decrypt(externalService.encKey);
  2506.  
  2507. if (!mailChimpUtil.MailChimpKeyIsNull(mailchimpKey))
  2508. {
  2509. mailChimpListModel.Errors.Add(AddMailChimpError("Invalid MailChimp key"));
  2510.  
  2511. return mailChimpListModel;
  2512. }
  2513.  
  2514. var audienceInfo = new AudienceInfo
  2515. {
  2516. Contact = new Contact(client.Name, client.AddressLineOne ?? string.Empty, client.AddressLineTwo ?? string.Empty,
  2517. client.City, client.State, client.ZipCode, client.Country, client.Phone),
  2518.  
  2519. ListName = campaign.Name,
  2520. FromName = client.Name,
  2521. FromEmail = client.Email,
  2522. Reminder = "_",
  2523. Language = "EN",
  2524. Subject = string.Concat(campaign.Name, " - ", campaign.Type.ToString())
  2525. };
  2526.  
  2527. var mailchimpService = new MailChimpNewService();
  2528.  
  2529. mailchimpService.mailChimpHttpClient = mailChimpUtil.CreateNewHttpClient();
  2530.  
  2531. var mailChimpAudience = mailchimpService.CreateNewAudience(audienceInfo, mailchimpKey);
  2532.  
  2533. string serviceId = mailChimpAudience.ListId;
  2534.  
  2535. if (mailChimpAudience == null || mailChimpAudience.MailChimpOperationError != null || mailChimpAudience.ListId == null)
  2536. {
  2537. if (mailChimpAudience.MailChimpOperationError != null)
  2538. {
  2539. AppLog.Error($"MailChimp Error StatusCode: {mailChimpAudience.MailChimpOperationError.StatusCode} Message: {mailChimpAudience.MailChimpOperationError.ErrorMessage}");
  2540. }
  2541.  
  2542. mailChimpListModel.Errors.Add(AddMailChimpError("Error creating mailchimp audience"));
  2543.  
  2544. return mailChimpListModel;
  2545. }
  2546.  
  2547. mailchimpService.mailChimpHttpClient = mailChimpUtil.CreateNewHttpClient();
  2548.  
  2549. databaseModel = await _campaignAudienceSubscribers.BuildCampaignSubscribers(guid, mailChimpAudience.ListId, UserId()); // Distinc data to send to Mail Chimp
  2550.  
  2551. if (!databaseModel.IsResponseCodeOK())
  2552. {
  2553. mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
  2554.  
  2555. return mailChimpListModel;
  2556. }
  2557.  
  2558. var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
  2559.  
  2560. var subscribersEmail = campaignSubscribers
  2561. .Select(cmp => cmp.SubscriberEmail)
  2562. .ToList();
  2563.  
  2564. mailChimpListModel = mailchimpService.UpdateMailChimpAudience(mailChimpAudience.ListId, subscribersEmail, client.Salt, "subscribed", mailchimpKey);
  2565.  
  2566. if (mailChimpListModel == null || mailChimpListModel.Errors.Count() != 0)
  2567. {
  2568. if (mailChimpListModel.MailChimpOperationError != null)
  2569. {
  2570. AppLog.Error($"MailChimp Error StatusCode: {mailChimpListModel.MailChimpOperationError.StatusCode} Message: {mailChimpListModel.MailChimpOperationError.ErrorMessage}");
  2571. }
  2572.  
  2573. foreach (var error in mailChimpListModel.Errors)
  2574. {
  2575. AppLog.Error($"MailChimp Error: {(error.Email ?? "null")} Error: {(error.Error ?? "null")}");
  2576. }
  2577.  
  2578. mailChimpListModel.Errors.Add(AddMailChimpError("Error Updating Subscriber Audience"));
  2579. mailChimpListModel.ListId = serviceId;
  2580.  
  2581. return mailChimpListModel;
  2582. }
  2583.  
  2584. databaseModel = await _campaignAudienceSubscribers.CreateCampaignSubscribers(campaignSubscribers, mailChimpAudience.ListId); // Create distinct data to send to Mail Chimp
  2585.  
  2586. if (!databaseModel.IsResponseCodeOK())
  2587. {
  2588. mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
  2589.  
  2590. return mailChimpListModel;
  2591. }
  2592. mailChimpListModel.CampaignGuid = guid;
  2593. mailChimpListModel.ListId = serviceId;
  2594.  
  2595. scope.Complete();
  2596. }
  2597.  
  2598. AppLog.Info($"ExportAudienceToMailChimp finished");
  2599. }
  2600. catch (DmpException e)
  2601. {
  2602. AppLog.Error(e.Problem.Description);
  2603.  
  2604. mailChimpListModel.Errors.Add(AddMailChimpError(e.Problem.Description));
  2605. }
  2606. catch (Exception e)
  2607. {
  2608. AppLog.Error(e.ToString());
  2609.  
  2610. mailChimpListModel.Errors.Add(AddMailChimpError(e.ToString()));
  2611. }
  2612. return mailChimpListModel;
  2613. }
  2614.  
  2615. private bool CreateSampleCampaignEntries(List<int> SampleIds, int sampleCampaignId, out List<SampleCampaignSample> addSampleCampaignSamples)
  2616. {
  2617. try
  2618. {
  2619. AppLog.Info("CreateSampleCampaignEntries started with input information [sampleCampaignId=" + sampleCampaignId + "]");
  2620.  
  2621. List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
  2622. foreach (int sampleId in SampleIds)
  2623. {
  2624. SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
  2625. sampleCampaignSample.SampleCampaignId = sampleCampaignId;
  2626. sampleCampaignSample.SampleId = sampleId;
  2627. AuditCreate(sampleCampaignSample, UserId());
  2628. sampleCampaignSampleList.Add(sampleCampaignSample);
  2629. }
  2630. AppLog.Info("CreateSampleCampaignEntries finished");
  2631.  
  2632. addSampleCampaignSamples = sampleCampaignSampleList;
  2633. return true;
  2634. }
  2635. catch (Exception e)
  2636. {
  2637. addSampleCampaignSamples = null;
  2638. return false;
  2639. }
  2640. }
  2641.  
  2642. private bool UpdateCampaignSamples(List<int> SampleIds, int sampleCampaignId)
  2643. {
  2644. try
  2645. {
  2646. using (var scope = new TransactionScope())
  2647. {
  2648. AppLog.Info("UpdateCampaignSamples started");
  2649. var getAllSampleCampaignSampleResponse = _sampleCampaignSampleRepository.GetById(sampleCampaignId);
  2650. if (!getAllSampleCampaignSampleResponse.IsResponseCodeOK())
  2651. {
  2652. return false;
  2653. }
  2654. IQueryable<SampleCampaignSample> sampleCampaignSamples = getAllSampleCampaignSampleResponse.ObjectNeeded as IQueryable<SampleCampaignSample>;
  2655. List<SampleCampaignSample> sampleCampaignSamplesList = sampleCampaignSamples.ToList();
  2656. if (sampleCampaignSamplesList == null || sampleCampaignSamplesList.Count() == 0)
  2657. {
  2658. List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
  2659. foreach (int sampleId in SampleIds)
  2660. {
  2661. SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
  2662. sampleCampaignSample.SampleCampaignId = sampleCampaignId;
  2663. sampleCampaignSample.SampleId = sampleId;
  2664. AuditCreate(sampleCampaignSample, UserId());
  2665. sampleCampaignSampleList.Add(sampleCampaignSample);
  2666. }
  2667. var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
  2668. if (!createSampleCampaignsResponse.IsResponseCodeOK())
  2669. {
  2670. return false;
  2671. }
  2672. }
  2673. List<SampleCampaignSample> InactiveSampleCampaigns = sampleCampaignSamplesList.Where(x => !SampleIds.Contains(x.SampleId)).ToList();
  2674. if (InactiveSampleCampaigns != null && InactiveSampleCampaigns.Count() > 0)
  2675. {
  2676. foreach (var inactivate in InactiveSampleCampaigns)
  2677. {
  2678. inactivate.IsActive = false;
  2679. inactivate.IsDeleted = false;
  2680. AuditEdit(inactivate);
  2681. }
  2682. var updateInactiveSampleCampaignSamples = _sampleCampaignSampleRepository.Update(InactiveSampleCampaigns);
  2683. if (!updateInactiveSampleCampaignSamples.IsResponseCodeOK())
  2684. {
  2685. return false;
  2686. }
  2687. }
  2688. List<SampleCampaignSample> ActivateSampleCampaigns = sampleCampaignSamplesList.Where(x => !x.IsActive && SampleIds.Contains(x.SampleId)).ToList();
  2689. if (ActivateSampleCampaigns != null && ActivateSampleCampaigns.Count() > 0)
  2690. {
  2691. foreach (var activate in ActivateSampleCampaigns)
  2692. {
  2693. activate.IsActive = true;
  2694. activate.IsDeleted = false;
  2695. AuditEdit(activate);
  2696. }
  2697. var updateActiveSampleCampaignSamples = _sampleCampaignSampleRepository.Update(ActivateSampleCampaigns);
  2698. if (!updateActiveSampleCampaignSamples.IsResponseCodeOK())
  2699. {
  2700. return false;
  2701. }
  2702. }
  2703. List<int> presentSampleCampaignIds = sampleCampaignSamplesList.Select(x => x.SampleId).ToList();
  2704.  
  2705. List<int> createSampleCampaignIds = SampleIds.Except(presentSampleCampaignIds).ToList();
  2706. if (createSampleCampaignIds != null && createSampleCampaignIds.Count() > 0)
  2707. {
  2708. List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
  2709. foreach (int sampleId in createSampleCampaignIds)
  2710. {
  2711. SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
  2712. sampleCampaignSample.SampleCampaignId = sampleCampaignId;
  2713. sampleCampaignSample.SampleId = sampleId;
  2714. AuditCreate(sampleCampaignSample, UserId());
  2715. sampleCampaignSampleList.Add(sampleCampaignSample);
  2716. }
  2717. var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
  2718. if (!createSampleCampaignsResponse.IsResponseCodeOK())
  2719. {
  2720. return false;
  2721. }
  2722. }
  2723. scope.Complete();
  2724. }
  2725. AppLog.Info("UpdateCampaignSamples finished");
  2726.  
  2727. return true;
  2728. }
  2729. catch (Exception e)
  2730. {
  2731. AppLog.Error(e.ToString());
  2732. return false;
  2733. }
  2734. }
  2735.  
  2736. private MailChimpErrorModel AddMailChimpError(string errorMessage)
  2737. {
  2738. try
  2739. {
  2740. return new MailChimpErrorModel()
  2741. {
  2742. Error = errorMessage
  2743. };
  2744. }
  2745. catch (Exception)
  2746. {
  2747. throw;
  2748. }
  2749. }
  2750.  
  2751. #endregion
  2752. }
  2753. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement