Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using DMP.DataAccess.SQL.Repositories;
- using DMP.Domain.Entities;
- using DMP.Domain.Entities.Enums;
- using DMP.Domain.Entities.TableEntities;
- using DMP.Domain.Exceptions;
- using DMP.Domain.ExternalServices;
- using DMP.Domain.Repositories;
- using DMP.Domain.Utils;
- using DMP.ExternalServices.MailChimp;
- using DMP.ExternalServices.MailChimp.MailChimpModels;
- using DMP.Web.ExternalServices;
- using DMP.Web.Models;
- using DMP.Web.Models.Audiences;
- using DMP.Web.Models.CampaignList;
- using DMP.Web.Models.Campaigns;
- using DMP.Web.Models.Factories.Interfaces;
- using DMP.Web.Models.Jobs;
- using DMP.Web.Models.Subscribers;
- using DMP.Web.Models.TableModel;
- using DMP.Web.Utils;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Cors;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Threading.Tasks;
- using System.Transactions;
- using CampaignServices = DMP.Web.ExternalServices.CampaignServices;
- using State = DMP.Domain.Entities.State;
- namespace DMP.Web.Controllers
- {
- //TODO REVIEW ALL CONTROLLER
- public class CampaignsController : BaseController<Campaign>
- {
- private readonly ISampleCampaignSampleRepository _sampleCampaignSampleRepository;
- private readonly ICampaignAudienceSubscribersRepository _campaignAudienceSubscribers;
- private readonly IRequestRepository _requestRepository;
- private readonly ISampleRepository _sampleRepository;
- private readonly ICampaignRepository _campaignRepository;
- private readonly IUserRepository _userRepository;
- private readonly IProductRepository _productRepository;
- private readonly ISurveyRepository _surveyRepository;
- private readonly IAccountRepository _accountRepository;
- private readonly IBrandRepository _brandRepository;
- private readonly IJobRepository _jobRepository;
- private readonly IAudienceRepository _audienceRepository;
- private readonly ISegmentationServices _mcServices;
- private readonly IClientRepository _clientRepository;
- private readonly CampaignServices _mcCampaignServices;
- private readonly DocumentHandler _documentHandler;
- private readonly ISubscriberRepository _subscriberRepository;
- private readonly ISubscriberScoresRepository _subscriberScoresRepository;
- private readonly ISubscriberAggregateDataRepository _subscriberAggregateDataRepository;
- private readonly string surveyShareUrl;
- private readonly IPaginatedViewModelFactory<CampaignTable, CampaignsViewModel> campaignPaginatedViewModelFactory;
- private readonly IPaginatedViewModelFactory<AudienceSubscriberTable, SubscriberViewModel> subscriberPaginatedViewModelFactory;
- private readonly IPaginatedViewModelFactory<AudienceTable, AudiencesViewModel> audiencePaginatedViewModelFactory;
- private readonly IPaginatedViewModelFactory<CampaignPresentSubscribersTable, SubscriberViewModel> _audiencePresentPaginatedViewModelFactory;
- private readonly IPaginatedViewModelFactory<CampaignAudienceListTable, CampaignListViewModel> _campaignListsPaginatedViewModelFactory;
- private object _lock;
- public CampaignsController(ICampaignRepository campaignRepository,
- IAudienceRepository audienceRepository,
- IUserRepository userRepository,
- ISubscriberRepository subscriberRepository,
- ISegmentationServices mcServices,
- CampaignServices mcCampaignServices,
- IProductRepository productRepository,
- ISurveyRepository surveyRepository,
- IJobRepository jobRepository,
- ISubscriberAggregateDataRepository subscriberAggregateDataRepository,
- ISubscriberScoresRepository subscriberScoresRepository,
- IBrandRepository brandRepository,
- IAccountRepository accountRepository,
- IHttpContextAccessor httpContextAccessor,
- IClientRepository clientRepository,
- ISampleRepository sampleRepository,
- ISampleCampaignSampleRepository sampleCampaignSampleRepository,
- IRequestRepository requestRepository,
- ICampaignAudienceSubscribersRepository campaignAudienceSubscribers,
- DocumentHandler documentHandler,
- IPaginatedViewModelFactory<CampaignTable, CampaignsViewModel> campaignPaginatedViewModelFactory,
- IPaginatedViewModelFactory<AudienceSubscriberTable, SubscriberViewModel> subscriberPaginatedViewModelFactory,
- IPaginatedViewModelFactory<AudienceTable, AudiencesViewModel> audiencePaginatedViewModelFactory,
- IPaginatedViewModelFactory<CampaignAudienceListTable, CampaignListViewModel> campaignListsPaginatedViewModelFactory,
- IPaginatedViewModelFactory<CampaignPresentSubscribersTable, SubscriberViewModel> audiencePresentPaginatedViewModelFactory,
- ILogger<BaseController<Campaign>> _logger) : base(httpContextAccessor, _logger, (BaseRepository<Campaign>)campaignRepository)
- {
- _campaignAudienceSubscribers = campaignAudienceSubscribers;
- _campaignRepository = campaignRepository;
- _userRepository = userRepository;
- _productRepository = productRepository;
- _surveyRepository = surveyRepository;
- _jobRepository = jobRepository;
- _audienceRepository = audienceRepository;
- _mcServices = mcServices;
- _clientRepository = clientRepository;
- _mcCampaignServices = mcCampaignServices;
- _documentHandler = documentHandler;
- _subscriberRepository = subscriberRepository;
- _accountRepository = accountRepository;
- _brandRepository = brandRepository;
- _subscriberAggregateDataRepository = subscriberAggregateDataRepository;
- _subscriberScoresRepository = subscriberScoresRepository;
- _sampleRepository = sampleRepository;
- _requestRepository = requestRepository;
- _sampleCampaignSampleRepository = sampleCampaignSampleRepository;
- _audiencePresentPaginatedViewModelFactory = audiencePresentPaginatedViewModelFactory;
- this.campaignPaginatedViewModelFactory = campaignPaginatedViewModelFactory;
- this.subscriberPaginatedViewModelFactory = subscriberPaginatedViewModelFactory;
- this.audiencePaginatedViewModelFactory = audiencePaginatedViewModelFactory;
- _campaignListsPaginatedViewModelFactory = campaignListsPaginatedViewModelFactory;
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json");
- _lock = new object();
- surveyShareUrl = builder.Build()["AppServer"];
- }
- #region POST
- [HttpPost]
- [Authorize(Policy = "Update")]
- [Authorize(Policy = "Cadet")]
- public IActionResult capSettings(int id, int cap, string OrderBy, int ProductId)
- {
- try
- {
- AppLog.Info("capSettings started with input information [id= " + id + " cap= " + cap + " OrderBy= " + OrderBy + " ProductId= " + ProductId + "]");
- int _id = _campaignRepository.SetCap(id, OrderBy, ProductId, cap);
- AppLog.Info("capSettings finished");
- return Ok(_id);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult ManageRequestedSample(RequestSamplesViewModel model)
- {
- try
- {
- using (TransactionScope scope = new TransactionScope())
- {
- AppLog.Info("Campaigns ManageRequestedSample started");
- foreach (var id in model.subscribers)
- {
- _campaignRepository.UpdateSampleRequest(id, model.State, UserId(), model.CampaignId);
- }
- scope.Complete();
- AppLog.Info("Campaigns ManageRequestedSample finished");
- return StatusCode(StatusCodes.Status200OK, new ServiceResponse()
- {
- MessageTitle = "Update",
- Message = "Resquest sample updated.",
- InternalStatusCode = 200
- });
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status406NotAcceptable, new ServiceResponse()
- {
- MessageTitle = "Error",
- Message = "Request sample not updated.",
- InternalStatusCode = 406
- });
- }
- }
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- [Route("[action]/{type}")]
- public IActionResult CreateCampaign(CreateCampaignViewModel model)
- {
- try
- {
- using (var scope = new TransactionScope())
- {
- AppLog.Info("CreateCampaign started");
- int typedCampId = -1;
- var campaign = new Campaign
- {
- Name = model.Name,
- Type = model.Type,
- LaunchDate = model.LaunchDate,
- ClientId = ClientId
- };
- AuditCreate(campaign, UserId());
- var campaignId = _campaignRepository.Create(campaign);
- dynamic _camp;
- switch (model.Type)
- {
- case CampaignType.Sample:
- if (model.SampleIds == null || model.SampleIds.Count() == 0)
- {
- return StatusCode(600, "Sample Campaign Without Any Samples Associated");
- }
- //add logic about number of samples stock
- //var samplesStorageResponse = _sampleRepository.GetListSamplesNumberDictionary(model.ProductId);
- //if (!samplesStorageResponse.IsResponseCodeOK())
- //{
- // return StatusCode(samplesStorageResponse.Code, samplesStorageResponse.Message);
- //}
- //Dictionary<int, int> samplesStorage = samplesStorageResponse.ObjectNeeded as Dictionary<int, int>;
- //if (samplesStorage == null)
- //{
- // return StatusCode(600, samplesStorageResponse.Message);
- //}
- //int allStorage = 0;
- //foreach (var sample in model.SampleIds)
- //{
- // if (samplesStorage.ContainsKey(sample))
- // {
- // allStorage = allStorage + samplesStorage[sample];
- // }
- //}
- //if (allStorage < model.SampleNumber)
- //{
- // return StatusCode(600, "No Storage Available Max Storage Number is -> " + allStorage);
- //}
- _camp = new SampleCampaign
- {
- CampaignId = campaignId,
- SamplesNumber = model.SampleNumber.GetValueOrDefault(),
- EndDate = model.EndDate == default(DateTime) ? model.LaunchDate.AddMonths(1) : model.EndDate,
- ProductId = model.ProductId
- };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateSampleCampaign(_camp, model.ProductId);
- if (model.SampleIds != null && model.SampleIds.Count() > 0)
- {
- List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
- bool createSampleCampaignListResult = CreateSampleCampaignEntries(model.SampleIds, typedCampId, out sampleCampaignSampleList);
- if (!createSampleCampaignListResult)
- {
- return StatusCode(600, "Error Creating Sample Campaign Samples Association");
- }
- var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
- if (!createSampleCampaignsResponse.IsResponseCodeOK())
- {
- return StatusCode(createSampleCampaignsResponse.Code, createSampleCampaignsResponse.Message);
- }
- }
- var audienceId = _audienceRepository.CreateSamplesAudience(new Audience
- {
- ClientId = ClientId,
- CreatedBy = UserId(),
- CreatedOn = DateTime.UtcNow,
- Name = $"Audience : {campaign.Name}",
- Description = "Audience generated for Sample Campaign"
- },
- ClientId,
- model.ProductId,
- model.SampleNumber.Value);
- _campaignRepository.AssociateAudience(campaignId,
- new List<CampaignAudiences>()
- {
- new CampaignAudiences()
- {
- CampaignId = campaignId,
- AudienceId = audienceId,
- CreatedBy = UserId(),
- CreatedOn = DateTime.UtcNow
- }
- });
- break;
- case CampaignType.Email:
- _camp = new EmailCampaign
- {
- CampaignId = campaignId,
- SentDate = model.SentDate
- };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateEmailCampaign(_camp);
- break;
- case CampaignType.Survey:
- _camp = new SurveyCampaign
- {
- CampaignId = campaignId,
- SentDate = model.SentDate
- };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateSurveyCampaign(_camp, model.SurveyId.GetValueOrDefault());
- break;
- default:
- throw new Exception($"Invalid Campaign type {model.Type} creation");
- }
- if (typedCampId == -1)
- {
- throw new Exception($"Failed Campaign type {model.Type} creation");
- }
- scope.Complete();
- AppLog.Info("CreateCampaign finished");
- return Ok(new { campaignId = campaignId, TypeCampaignId = typedCampId });
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(new { error = e.Message });
- }
- }
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- [Route("[action]/job/{type}/{jobId}")]
- public IActionResult CreateCampaignJob(CreateCampaignViewModel model)
- {
- try
- {
- using (var scope = new TransactionScope())
- {
- AppLog.Info("CreateCampaignJob started");
- int typedCampId = -1;
- Campaign camp = new Campaign { Name = model.Name, Type = model.Type, LaunchDate = model.LaunchDate, ClientId = ClientId };
- AuditCreate(camp, UserId());
- var campId = _campaignRepository.Create(camp);
- dynamic _camp;
- switch (model.Type)
- {
- case CampaignType.Sample:
- if (model.ProductId == 0)
- return BadRequest(new { error = "Invalid Product ID" });
- _camp = new SampleCampaign
- {
- CampaignId = campId,
- SamplesNumber = model.SampleNumber.GetValueOrDefault(),
- EndDate = model.EndDate,
- ProductId=model.ProductId
- };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateSampleCampaign(_camp, model.ProductId);
- break;
- case CampaignType.Email:
- _camp = new EmailCampaign { CampaignId = campId, SentDate = model.SentDate };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateEmailCampaign(_camp);
- break;
- case CampaignType.Survey:
- _camp = new SurveyCampaign { CampaignId = campId, SentDate = model.SentDate };
- AuditCreate(_camp, UserId());
- typedCampId = _campaignRepository.CreateSurveyCampaign(_camp, model.SurveyId.GetValueOrDefault());
- break;
- default:
- throw new Exception($"Invalid Campaign type {model.Type} creation");
- }
- if (typedCampId == -1)
- throw new Exception($"Failed Campaign type {model.Type} creation");
- try
- {
- if (model.jobId != 0)
- {
- _campaignRepository.AssociateJob(model.jobId, campId);
- }
- else
- {
- throw new Exception($"Failed to associate job with campaign");
- }
- }
- catch (Exception ex)
- {
- if (ex is DmpException)
- throw ex;
- return BadRequest(new { error = ex.Message });
- }
- AppLog.Info("CreateCampaignJob finished");
- scope.Complete();
- return Ok(new { campaignId = campId, TypeCampaignId = typedCampId });
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(new { error = e.Message });
- }
- }
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- public IActionResult AddCampaign(CampaignsViewModel model)
- {
- try
- {
- AppLog.Info("AddCampaign started");
- var campaign = new Campaign
- {
- Name = model.Name,
- ClientId = ClientId
- };
- AuditCreate(campaign, UserId());
- int x = 0;
- CampaignType.TryParse("Survey", out x);
- AuditCreate(campaign, UserId());
- _campaignRepository.Create(campaign);
- AppLog.Info("AddCampaign finished");
- return StatusCode(StatusCodes.Status200OK);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Update")]
- [Authorize(Policy = "Cadet")]
- [Route("/campaigns/EditCampaignSamples")]
- public IActionResult EditCampaignSamples(List<int> SampleIds, int campaignId)
- {
- try
- {
- var typedCampaign = this._campaignRepository.GetCampaign(campaignId, ClientId);
- if (!(typedCampaign is SampleCampaign))
- {
- return StatusCode(600, "Campaign is not a Sample Campaign");
- }
- int sampleCampaignId = typedCampaign.Id;
- AppLog.Info("EditCampaignSamples started with input information [sampleCampaignId=" + sampleCampaignId + "]");
- if (SampleIds == null || SampleIds.Count() == 0)
- {
- return StatusCode(600, new { Id = sampleCampaignId, Message = "Sample Campaign without Samples." });
- }
- bool updatedSamples = UpdateCampaignSamples(SampleIds, sampleCampaignId);
- if (updatedSamples)
- {
- AppLog.Info("EditCampaignSamples finished successfully");
- return StatusCode(200, new { Id = sampleCampaignId, Message = "Campaign Samples Sucessfully Updated" });
- }
- AppLog.Info("EditCampaignSamples finished wrong");
- return StatusCode(600, new { Id = sampleCampaignId, Message = "Error Updating Samples" });
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Update")]
- [Authorize(Policy = "Cadet")]
- [Route("/campaigns/EditCampaign")]
- public IActionResult EditCampaign(CampaignsViewModel model)
- {
- try
- {
- using (var scope = new TransactionScope())
- {
- AppLog.Info("EditCampaign started");
- var typedCampaign = this._campaignRepository.GetCampaign(model.Id, ClientId);
- var currentCampaign = typedCampaign.Campaign;
- if (currentCampaign.Name != model.Name && model.Name != null)
- {
- currentCampaign.Name = model.Name;
- this.AuditEdit(currentCampaign);
- this.AuditEdit(typedCampaign);
- }
- if (model.Job != null && currentCampaign.JobId != model.Job.Id && model.Job.Id != null)
- {
- currentCampaign.JobId = model.Job.Id;
- this.AuditEdit(currentCampaign);
- this.AuditEdit(typedCampaign);
- }
- if (currentCampaign.LaunchDate != model.LaunchDate && model.LaunchDate != null)
- {
- currentCampaign.LaunchDate = model.LaunchDate.Value;
- this.AuditEdit(currentCampaign);
- this.AuditEdit(typedCampaign);
- }
- if (typedCampaign is SampleCampaign)
- {
- typedCampaign.SamplesNumber = model.SuppliedSamples;
- this.AuditEdit(typedCampaign);
- this._campaignRepository.UpdateSampleCampaign(typedCampaign);
- }
- if (typedCampaign is SampleCampaign && typedCampaign.EndDate != model.EndDate && model.EndDate != null)
- {
- //add logic about number of samples stock
- typedCampaign.EndDate = model.EndDate.Value;
- this.AuditEdit(currentCampaign);
- this.AuditEdit(typedCampaign);
- this._campaignRepository.UpdateSampleCampaign(typedCampaign);
- }
- if (!(typedCampaign is SampleCampaign) && typedCampaign.SentDate != model.SentDate && model.SentDate != null)
- {
- typedCampaign.SentDate = model.SentDate.Value;
- this.AuditEdit(currentCampaign);
- this.AuditEdit(typedCampaign);
- if (typedCampaign is EmailCampaign)
- this._campaignRepository.UpdateSentDateEmail(typedCampaign);
- else
- this._campaignRepository.UpdateSentDateSurvey(typedCampaign);
- }
- this._campaignRepository.Update(currentCampaign);
- scope.Complete();
- }
- var camp = this._campaignRepository.GetCampaign(model.Id, ClientId).Campaign;
- AppLog.Info("EditCampaign finished");
- return this.Ok(new CampaignsViewModel
- {
- Brand = camp.Job?.Brand?.Name,
- Account = camp.Job?.Brand?.Account?.Name,
- JobId = camp.JobId
- });
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- //TODO NEED REVIEW THE NESTED TRY
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- [Route("[action]/campaign/{campaignid}/job/{jobid}")]
- public IActionResult AssociateJob(int campaignid, int jobid)
- {
- try
- {
- try
- {
- AppLog.Info("Campaigns AssociateJob started with input information [campaignid= " + campaignid + " jobid= " + jobid + "]");
- _campaignRepository.AssociateJob(jobid, campaignid);
- var databaseModel = _jobRepository.GetById(jobid, ClientId);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var job = databaseModel.ObjectNeeded as Job;
- AppLog.Info("Campaigns AssociateJob finished");
- return StatusCode(databaseModel.Code, new JobsViewModel()
- {
- Id = job.Id,
- JobNumber = job.JobNumber,
- BrandName = job.Brand.Name,
- AccountName = job.Brand.Account.Name
- });
- }
- catch (DmpException e)
- {
- return StatusCode(e.Problem.StatusCode, e.Problem.InvalidParameters.First().Reason);
- }
- catch (Exception e)
- {
- return StatusCode(StatusCodes.Status500InternalServerError, $"Failed to AssociateJob with message : {e.Message}");
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict);
- }
- }
- //NEEDS REVIEW
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- [Route("[action]/Campaigns/{campaignId}/Audiences")]
- public IActionResult AssociateAudience(int campaignId, [FromBody] int[] audienceIds)
- {
- var _audience = new List<AudiencesViewModel>();
- try
- {
- AppLog.Info($"Campaigns AssociateAudience started with input information [campaignId= {campaignId} audienceId= {string.Join(", ", audienceIds)}]");
- using (var scope = new TransactionScope())
- {
- var campaignAudiences = audienceIds.Select(x=> new CampaignAudiences()
- {
- CampaignId = campaignId,
- AudienceId = x,
- CreatedBy = UserId(),
- CreatedOn = DateTime.UtcNow,
- });
- _campaignRepository.AssociateAudience(campaignId, campaignAudiences);
- scope.Complete();
- }
- var allCampaignAudiences=_campaignRepository.GetCampaignAudienceLists(campaignId);
- if(allCampaignAudiences==null || allCampaignAudiences.Count() == 0)
- {
- return Ok(_audience);
- }
- _audience=allCampaignAudiences.Select(x => new AudiencesViewModel
- {
- Name = x.Name,
- Id = x.Id
- }).ToList();
- AppLog.Info("Campaigns AssociateAudience finished");
- return Ok(_audience);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Add")]
- [Authorize(Policy = "Cadet")]
- public IActionResult CreateAudience(string name, AudienceType reviewed, int campaignid)
- {
- try
- {
- AppLog.Info($"Campaigns CreateAudience started with input information [name= {name} campaignid= {campaignid}]");
- var campaign = _campaignRepository.GetCampaign(campaignid, ClientId) as SampleCampaign;
- if (campaign == null ||
- (campaign.Campaign.CampaignAudiences == null || campaign.Campaign.CampaignAudiences.Count() == 0))
- {
- return BadRequest("No Audience associated or campaign is not a sample campaign");
- }
- if (_audienceRepository.GetByName(ClientId, name).Count() > 0)
- {
- return BadRequest("Audience name already exist, please try another one.");
- }
- AppLog.Info("Campaigns CreateAudience finished");
- var campaignAudience = campaign.Campaign.CampaignAudiences
- .FirstOrDefault(cmp => cmp.CampaignId == campaignid); // Momentaneamente atribuido o 1o elemento.
- var newAudienceId = _audienceRepository.GenerateSamplesAudience(campaign.Campaign.ClientId, campaign.ProductId, reviewed, campaignAudience, name);
- _audienceRepository.UpdateAudienceSubscribersState(newAudienceId);
- return StatusCode(StatusCodes.Status200OK, newAudienceId);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict, e.Message);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Update")]
- [Authorize(Policy = "Cadet")]
- public IActionResult Complete(int campaignid)
- {
- try
- {
- AppLog.Info("Campaigns Complete started with input information [campaignid= " + campaignid + "]");
- var campaign = _campaignRepository.GetCampaign(campaignid, ClientId);
- SampleCampaign sampleCampaign = campaign as SampleCampaign;
- using (var scope = new TransactionScope())
- {
- IEnumerable<CampaignAudiences> campaignAudiences = null;
- if (sampleCampaign != null && sampleCampaign.Campaign != null)
- {
- if(sampleCampaign.Campaign.CampaignAudiences==null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
- {
- return StatusCode(600, "Campaign Without Audiences Associated");
- }
- campaignAudiences = sampleCampaign.Campaign.CampaignAudiences;
- var audSubApprovedCount = 0;
- if (campaignAudiences.Count() > 0)
- {
- var ids = campaignAudiences.Select(cmp => cmp.AudienceId);
- audSubApprovedCount = (ids.Count() == 0 ? audSubApprovedCount :
- _audienceRepository.GetAudienceSubscribersDistinct(ids, State.Approved)
- .Select(cmp => cmp.Id)
- .Count());
- }
- var prodSampleCount = sampleCampaign.SamplesNumber;
- if (audSubApprovedCount > prodSampleCount)
- {
- return StatusCode((int)DatabaseReturnCodes.InternalError,
- $"Amount of product sample ({prodSampleCount}) is not suficient for amount of campaign audience ({audSubApprovedCount}).");
- }
- var getSampleResponse = _sampleCampaignSampleRepository.WithdrawalSampleNumber(sampleCampaign.Id, audSubApprovedCount);
- sampleCampaign.SamplesNumber = audSubApprovedCount;
- _campaignRepository.UpdateSampleCampaign(sampleCampaign);
- if (!getSampleResponse.IsResponseCodeOK())
- {
- return StatusCode(getSampleResponse.Code, getSampleResponse.Message);
- }
- bool createSampleLists = CreateSampleCampaignLists(campaignid);
- if(!createSampleLists)
- {
- return StatusCode(600,"Error Creating Sample Campaign Lists");
- }
- }
- _campaignRepository.Complete(campaignid, ClientId);
- IEnumerable<CampaignAudiencesViewModel> campaignAudiencesView = null;
- var campaignViewModel = new CampaignsViewModel
- {
- Id = (sampleCampaign == null) ? campaign.Campaign.Id : sampleCampaign.Campaign.Id,
- IsActive = (sampleCampaign == null) ? campaign.Campaign.IsActive : sampleCampaign.Campaign.IsActive,
- IsPending = (sampleCampaign == null) ? campaign.Campaign.isPending : sampleCampaign.Campaign.isPending,
- CampaignAudiences = campaignAudiencesView
- };
- scope.Complete();
- AppLog.Info("Campaigns Complete finished");
- return Ok(campaignViewModel);
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict);
- }
- }
- [HttpPost]
- [Authorize(Policy = "Update")]
- [Authorize(Policy = "Cadet")]
- public IActionResult updateSentDate(CampaignsViewModel model)
- {
- try
- {
- AppLog.Info("Campaigns updateSentDate started");
- switch (model.Type)
- {
- case CampaignType.Email:
- var emailObject = _campaignRepository.GetCampaign(model.Id, ClientId);
- emailObject.SentDate = model.SentDate;
- AuditEdit(emailObject);
- try
- {
- _campaignRepository.UpdateSentDateEmail(emailObject);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict);
- }
- break;
- case CampaignType.Survey:
- var surveyObject = _campaignRepository.GetCampaign(model.Id, ClientId);
- surveyObject.SentDate = model.SentDate;
- AuditEdit(surveyObject);
- try
- {
- _campaignRepository.UpdateSentDateSurvey(surveyObject);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status409Conflict);
- }
- break;
- }
- AppLog.Info("Campaigns updateSentDate finished");
- return StatusCode(StatusCodes.Status200OK, new ServiceResponse()
- {
- MessageTitle = "Updated",
- Message = "Sent date updated.",
- InternalStatusCode = 200
- });
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("refreshSamplesNumber")]
- [HttpPost]
- public ActionResult RefreshSamplesNumber(List<int> SampleIds, int ProductId)
- {
- AppLog.Info("RefreshSamplesNumber started");
- try
- {
- int allStorage = 0;
- if (SampleIds != null || SampleIds.Count() > 0)
- {
- var samplesStorageResponse = _sampleRepository.GetListSamplesNumberDictionary(ProductId);
- if (!samplesStorageResponse.IsResponseCodeOK())
- {
- return StatusCode(samplesStorageResponse.Code, samplesStorageResponse.Message);
- }
- Dictionary<int, int> samplesStorage = samplesStorageResponse.ObjectNeeded as Dictionary<int, int>;
- if (samplesStorage == null)
- {
- return StatusCode(600, samplesStorageResponse.Message);
- }
- foreach (var sample in SampleIds)
- {
- if (samplesStorage.ContainsKey(sample))
- {
- allStorage = allStorage + samplesStorage[sample];
- }
- }
- }
- AppLog.Info("RefreshSamplesNumber finished");
- return StatusCode(200, allStorage);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- #endregion
- #region GET
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult Index()
- {
- var campaign = new CampaignsViewModel(Role);
- return View(campaign);
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("[action]/")]
- public ActionResult GetTypes()
- {
- try
- {
- AppLog.Info("GetTypes started");
- Dictionary<string, dynamic> enums = new Dictionary<string, dynamic>();
- var vals = Enum.GetValues(typeof(CampaignType));
- var names = Enum.GetNames(typeof(CampaignType));
- for (int i = 0; i < vals.Length; i++)
- {
- enums.Add(names[i], vals.GetValue(i));
- }
- AppLog.Info("GetTypes finished");
- return Ok(enums);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [HttpGet]
- //criar field the pedido de samples numbers
- public IActionResult Details(int id)
- {
- AppLog.Info("Campaigns Details started with input information [id= " + id + "]");
- try
- {
- var _campaign = _campaignRepository.GetCampaign(id, ClientId);
- var getUserResponse = _userRepository.GetById(int.Parse(_campaign.CreatedBy.ToString()));
- if (!getUserResponse.IsResponseCodeOK())
- {
- return StatusCode(getUserResponse.Code, getUserResponse.Message);
- }
- var _user = getUserResponse.ObjectNeeded as User;
- var databaseModel = _campaignAudienceSubscribers.GetCampaignAudienceSubscribersHistory(id);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var campaignAudienceSubscribersHistory = (databaseModel.ObjectNeeded as IQueryable<CampaignAudienceSubscribersHistory>)
- .Select(cmp => new CampaignAudienceSubscribersHistoryViewModel()
- {
- Id = cmp.Id,
- CampaignId = cmp.Id,
- CampaignAudienceId = cmp.CampaignAudienceId,
- AudienceId = cmp.AudienceId,
- AudienceDescription = cmp.Audience.Name,
- SubscriberId = cmp.SubscriberId,
- SubscriberName = string.Concat(cmp.Subscriber.FirstName, " ", cmp.Subscriber.LastName),
- CreatedBy = cmp.CreatedBy,
- CreatedOn = cmp.CreatedOn
- });
- var campaigns = new CampaignsViewModel()
- {
- Id = _campaign.Campaign.Id,
- Name = _campaign.Campaign.Name,
- JobNumber = _campaign.Campaign.Job?.JobNumber ?? null,
- JobId = _campaign.Campaign.JobId,
- Brand = _campaign.Campaign.Job?.Brand?.Name ?? null,
- BrandId = _campaign.Campaign.Job?.Brand?.Id ?? null,
- AccountId = _campaign.Campaign.Job?.Brand?.Account?.Id ?? null,
- Account = _campaign.Campaign.Job?.Brand?.Account?.Name ?? null,
- Type = _campaign.Campaign.Type,
- IsActive = _campaign.Campaign.IsActive,
- CreatedBy = _campaign.CreatedBy,
- CreatedByName = _user.Name,
- CreatedOn = _campaign.Campaign.CreatedOn,
- UpdatedOn = _campaign.Campaign.UpdatedOn,
- LaunchDate = _campaign.Campaign.LaunchDate,
- IsPending = _campaign.Campaign.isPending,
- CampaignAudiences = (_campaign.Campaign.CampaignAudiences == null || _campaign.Campaign.CampaignAudiences.Count == 0) ? new List<CampaignAudiencesViewModel>() : new List<CampaignAudiencesViewModel>(),
- CampaignAudienceSubscribersHistory = campaignAudienceSubscribersHistory,
- };
- if (_campaign.GetType() == typeof(EmailCampaign) || _campaign.GetType() == typeof(SurveyCampaign))
- {
- campaigns.SentDate = (_campaign.SentDate == null) ? null : _campaign.SentDate;
- campaigns.IsMailChimpCampaign = (campaignAudienceSubscribersHistory != null && campaignAudienceSubscribersHistory.Count() > 0);
- }
- if (_campaign.GetType() == typeof(SampleCampaign))
- {
- var getProductResponse = _productRepository.GetProduct(_campaign.ProductId);
- if (!getProductResponse.IsResponseCodeOK())
- {
- return StatusCode(getProductResponse.Code, getProductResponse.Message);
- }
- Product _product = getProductResponse.ObjectNeeded as Product;
- if (_product == null)
- {
- return StatusCode(600, "Sample Campaign Not Associated with any Product");
- }
- var getSampleCampaignIdsResponse = _sampleCampaignSampleRepository.GetById(_campaign.Id);
- if (!getSampleCampaignIdsResponse.IsResponseCodeOK())
- {
- return StatusCode(getSampleCampaignIdsResponse.Code, getSampleCampaignIdsResponse.Message);
- }
- IQueryable<SampleCampaignSample> sampleCampaignSamples = getSampleCampaignIdsResponse.ObjectNeeded as IQueryable<SampleCampaignSample>;
- if (sampleCampaignSamples == null || sampleCampaignSamples.Count() == 0)
- {
- campaigns.SampleIds = null;
- }
- campaigns.SampleIds = sampleCampaignSamples.Where(x => x.IsActive).Select(x => x.SampleId).Distinct().ToList();
- var allSamplesListResponse = _sampleRepository.GetListSamplesNumberDictionary(_product.Id);
- if (!allSamplesListResponse.IsResponseCodeOK())
- {
- return StatusCode(allSamplesListResponse.Code, allSamplesListResponse.Message);
- }
- Dictionary<int, int> productSampleStorage = allSamplesListResponse.ObjectNeeded as Dictionary<int, int>;
- int totalStorageAvailable = 0;
- if (productSampleStorage != null && productSampleStorage.Count() > 0)
- {
- foreach (var sample in campaigns.SampleIds)
- {
- if (productSampleStorage.ContainsKey(sample))
- {
- totalStorageAvailable = totalStorageAvailable + productSampleStorage[sample];
- }
- }
- }
- campaigns.SampleDetails = sampleCampaignSamples.Where(x => x.IsActive).ToDictionary(x => x.SampleId, x => x.Sample.Name);
- campaigns.ExtProductId = (_product._ExternalId == null) ? null : _product._ExternalId;
- campaigns.ProductId = _product.Id;
- campaigns.ProductName = _product.Name;
- campaigns.SuppliedSamples = _campaign.SamplesNumber;
- campaigns.EndDate = (_campaign.EndDate == null) ? null : _campaign.EndDate;
- campaigns.ProductUrl = _product.Url;
- campaigns.IsCapped = _campaignRepository.IsCapped(_product.Id);
- campaigns.SampleRequestsCount = _campaignRepository.CountSampleRequests(_product.Id);
- campaigns.AvailableStorage = totalStorageAvailable;
- var stats = _campaignRepository.getStats(id, ClientId);
- campaigns.approvedProfiles = stats[0];
- campaigns.approvedReviews = stats[1];
- campaigns.averageRating = stats[2];
- databaseModel = _audienceRepository.GetAudienceByCampaign(id, ClientId);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var campaign = databaseModel.ObjectNeeded as Campaign;
- var campaignAudiences = campaign.CampaignAudiences.FirstOrDefault(cmp=>cmp.Audience.SampleAudience);
- if (campaignAudiences == null)
- {
- return StatusCode(600, "There is no Sample Audience type for Campaign");
- }
- int sampleAudienceId = campaignAudiences.AudienceId;
- var sampleAudienceSubscribers = _audienceRepository.GetAudienceSubscribers(sampleAudienceId);
- campaigns.RequestedApprovedProfiles = sampleAudienceSubscribers.Count();
- }
- AppLog.Info("Campaigns Details finished");
- return View(campaigns);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [HttpGet]
- public IActionResult Requests(int id)
- {
- try
- {
- AppLog.Info("Campaigns Requests started with input information [id= " + id + "]");
- var _campaign = _campaignRepository.GetCampaign(id, ClientId);
- DataBaseFunctionReturnModel getUserResponse = _userRepository.GetById(int.Parse(_campaign.CreatedBy.ToString()));
- if (!getUserResponse.IsResponseCodeOK())
- {
- return StatusCode(getUserResponse.Code, getUserResponse.Message);
- }
- User _user = getUserResponse.ObjectNeeded as User;
- if (_user == null)
- {
- return StatusCode(600, "User Not Found");
- }
- var getTotalProfilesResponse = _campaignAudienceSubscribers.GetAllPresentCampaignAudienceMembers(id);
- if(!getTotalProfilesResponse.IsResponseCodeOK())
- {
- return StatusCode(getTotalProfilesResponse.Code, getTotalProfilesResponse.Message);
- }
- IQueryable<CampaignPresentSubscribersTable> campaignSubscribers = getTotalProfilesResponse.ObjectNeeded as IQueryable<CampaignPresentSubscribersTable>;
- int totalProfiles = campaignSubscribers.Select(x => x.Id).Distinct().Count();
- var campaigns = new CampaignsViewModel(Role)
- {
- Id = _campaign.Campaign.Id,
- Name = _campaign.Campaign.Name,
- Type = _campaign.Campaign.Type,
- IsActive = _campaign.Campaign.IsActive,
- CreatedBy = _campaign.Campaign.CreatedBy,
- CreatedOn = _campaign.Campaign.CreatedOn,
- UpdatedOn = _campaign.Campaign.UpdatedOn,
- LaunchDate = _campaign.Campaign.LaunchDate,
- IsPending = _campaign.Campaign.isPending,
- TotalProfiles = totalProfiles,
- CampaignAudiences = null,
- Job = (_campaign.Campaign.Job == null)
- ? null
- : new JobsViewModel
- {
- Name = _campaign.Campaign.Job.Name,
- JobNumber = _campaign.Campaign.Job.JobNumber,
- BrandName = _campaign.Campaign.Job.Brand.Name,
- AccountName = _campaign.Campaign.Job.Brand.Account.Name,
- ClientId = ClientId
- }
- };
- if (_campaign.GetType() == typeof(EmailCampaign) || _campaign.GetType() == typeof(SurveyCampaign))
- campaigns.SentDate = (_campaign.SentDate == null) ? null : _campaign.SentDate;
- if (_campaign.GetType() == typeof(SampleCampaign))
- {
- var getProductResponse = _productRepository.GetProduct(_campaign.ProductId);
- if (!getProductResponse.IsResponseCodeOK())
- {
- return StatusCode(getProductResponse.Code, getProductResponse.Message);
- }
- Product _product = getProductResponse.ObjectNeeded as Product;
- campaigns.ExtProductId = (_product._ExternalId == null) ? null : _product._ExternalId;
- campaigns.ProductId = _product.Id;
- //which one of the fields should we consider
- campaigns.SuppliedSamples = (_campaign.SamplesNumber ?? 0);
- campaigns.EndDate = (_campaign.EndDate == null) ? null : _campaign.EndDate;
- }
- AppLog.Info("Campaigns Requests finished");
- return View(campaigns);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [HttpGet]
- public IActionResult getProducts(int? campaignTypeId)
- {
- try
- {
- AppLog.Info("Campaigns getProducts started");
- var getAllProductsResponse = _productRepository.GetAllProducts(ClientId);
- if (!getAllProductsResponse.IsResponseCodeOK())
- {
- return StatusCode(getAllProductsResponse.Code, getAllProductsResponse.Message);
- }
- var products = getAllProductsResponse.ObjectNeeded as List<Product>;
- if (campaignTypeId.HasValue)
- {
- switch ((CampaignType)campaignTypeId)
- {
- case CampaignType.Sample:
- var dataBaseReturnModel = _requestRepository.GetRequestProductId();
- var allProductWithSamples = products.Where(x => x.Sample != null && x.Sample.Count() > 0).ToList();
- products = allProductWithSamples;
- break;
- case CampaignType.Survey:
- break;
- case CampaignType.Email:
- break;
- default:
- break;
- }
- }
- AppLog.Info("Campaigns getProducts finished");
- return Ok(products
- .Where(p => p.IsActive)
- .Select(p => new
- {
- id = p.Id,
- name = p.Name,
- externalid = p.ExternalId,
- suppliedSamples = p.Sample.FirstOrDefault(x => x.ProductId == p.Id)?.NumberOfSamples ?? 0
- }));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- //TODO CHECK THIS GARBAGE AND PUT THIS UNIQUE
- return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
- {
- MessageTitle = "No Content",
- Message = "No Products Available.",
- InternalStatusCode = 204
- });
- }
- }
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [HttpGet]
- public IActionResult getSurveys()
- {
- try
- {
- AppLog.Info("Campaigns getSurveys started");
- var allSurveysResponse = _surveyRepository.GetAll();
- if (!allSurveysResponse.IsResponseCodeOK())
- {
- AppLog.Info("Campaigns getSurveys finished");
- return StatusCode(allSurveysResponse.Code, allSurveysResponse.Message);
- }
- var allSurveys = allSurveysResponse.ObjectNeeded as List<Survey>;
- AppLog.Info("Campaigns getSurveys finished");
- return Ok(allSurveys
- .Where(s => s.IsActive
- && s.ClientId == ClientId)
- .Select(s => new
- {
- id = s.Id,
- name = s.Name
- }));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- //TODO CHECK THIS GARBAGE AND PUT THIS UNIQUE
- return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
- {
- MessageTitle = "No Content",
- Message = "No products available.",
- InternalStatusCode = 204
- });
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult GetJobs()
- {
- try
- {
- AppLog.Info("Campaigns GetJobs started");
- AppLog.Info("Campaigns GetJobs finished");
- var databaseModel = _jobRepository.GetAll(ClientId);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var jobs = databaseModel.ObjectNeeded as IQueryable<JobTable>;
- return StatusCode(databaseModel.Code,
- jobs.Where(c => c.IsActive).Select(j => new
- {
- id = j.Id,
- name = j.JobNumber,
- Brand = new Brand()
- {
- Name = j.Brand,
- ClientId = ClientId
- },
- Account = new Account()
- {
- Name = j.Account
- }
- })
- .ToList());
- }
- catch (DmpException e)
- {
- return StatusCode(e.Problem.StatusCode, e.Problem.InvalidParameters.First().Reason);
- }
- catch (Exception e)
- {
- return StatusCode(StatusCodes.Status500InternalServerError, $"Failed to GetJobs with message : {e.Message}");
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult GetAudiences()
- {
- try
- {
- AppLog.Info("Campaigns GetAudiences started");
- AppLog.Info("Campaigns GetAudiences finished");
- return Ok(_audienceRepository.Get(ClientId)
- .Where(a => a.IsActive)
- .Select(j => new
- {
- id = j.Id,
- name = j.Name
- }));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- //put this unique
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status204NoContent, new ServiceResponse()
- {
- MessageTitle = "No Content",
- Message = "Id Audience Invalid.",
- InternalStatusCode = 204
- });
- }
- }
- //need to be revisited
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult GetRequestedSamples(State state, int id, TableModelView model)
- {
- try
- {
- AppLog.Info("Campaigns GetRequestedSamples started with input information [id= " + id + "]");
- var campaign = _campaignRepository.GetCampaign(id, ClientId) as SampleCampaign;
- if (campaign == null)
- {
- return StatusCode(StatusCodes.Status404NotFound, new ServiceResponse()
- {
- MessageTitle = "Wrong",
- Message = "Wrong identifier for sample campaign.",
- InternalStatusCode = 404
- });
- }
- var getTotalProfilesResponse = this._campaignAudienceSubscribers.GetAllPresentCampaignAudienceMembers(id);
- if (!getTotalProfilesResponse.IsResponseCodeOK())
- {
- return StatusCode(getTotalProfilesResponse.Code, getTotalProfilesResponse.Message);
- }
- IQueryable<CampaignPresentSubscribersTable> campaignSubscribers = getTotalProfilesResponse.ObjectNeeded as IQueryable<CampaignPresentSubscribersTable>;
- if (campaignSubscribers == null || campaignSubscribers.Count() == 0)
- {
- PageResponse<SubscriberViewModel> emptyResponse = new PageResponse<SubscriberViewModel>();
- emptyResponse.Elems = new List<SubscriberViewModel>();
- emptyResponse.Direction = model.Direction;
- emptyResponse.OrderBy = model.OrderBy;
- emptyResponse.PageSize = model.PageSize;
- emptyResponse.Search = model.Search;
- emptyResponse.Page = model.Page;
- return StatusCode(200, emptyResponse);
- }
- campaignSubscribers = campaignSubscribers.Where(x => x.Status == (int)state);
- if (campaign.Campaign.CampaignAudiences != null)
- {
- //var audienceIds = campaign.Campaign.CampaignAudiences.Select(cmp => cmp.AudienceId);
- AppLog.Info("Campaigns GetRequestedSamples finished");
- return Ok(this._audiencePresentPaginatedViewModelFactory.Create(
- () => campaignSubscribers,
- subscriber => new SubscriberViewModel
- {
- FirstName = subscriber.FirstName,
- LastName = subscriber.LastName,
- City = subscriber.City,
- State = subscriber.State,
- ZipCode = subscriber.ZipCode,
- CreatedOn = subscriber.CreatedOn,
- IsActive = subscriber.IsActive,
- ProfileScore=subscriber.ProfileScore,
- UserScore=subscriber.UserScore,
- ReviewScore=subscriber.ReviewScore,
- Id = subscriber.Id
- },
- model.Page,
- model.PageSize,
- model.Search,
- model.OrderBy,
- model.Direction
- ));
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return StatusCode(StatusCodes.Status400BadRequest, new ServiceResponse()
- {
- MessageTitle = "Error",
- Message = "Error on getting samples requests.",
- InternalStatusCode = 400
- });
- }
- return StatusCode(StatusCodes.Status400BadRequest, new ServiceResponse()
- {
- MessageTitle = "Error",
- Message = "Error on getting samples requests.",
- InternalStatusCode = 400
- });
- }
- [HttpGet]
- [EnableCors("CorsPolicy")]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/mailchimpEmailCampaignDetails/{id}")]
- public ActionResult GetMailChimpEmailCampaignDetails(int id)
- {
- try
- {
- AppLog.Info("Campaigns GetMailChimpEmailCampaignDetails started with input information [id= " + id + "]");
- var ExternalClientObject = _clientRepository.GetExternalServices(ClientId).Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim()).FirstOrDefault();
- var client = _clientRepository.GetById(ClientId);
- var emailCampaign = (EmailCampaign)_campaignRepository.GetCampaign(id, ClientId);
- MailChimpKeyStore manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
- string mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
- MailChimpNewService mailchimp = new MailChimpNewService();
- if (emailCampaign.ServiceId == null)
- {
- return BadRequest(new Exception("Campaign does not exist in mailChimp"));
- }
- else
- {
- var mailChimpResponse = mailchimp.GetCampaignInformationById(emailCampaign.ServiceId, mailchimpKey);
- if (mailChimpResponse == null)
- {
- return BadRequest(new Exception("Error Calling MailChimp"));
- }
- AppLog.Info("Campaigns GetMailChimpEmailCampaignDetails finished");
- return Ok(mailChimpResponse.RedirectLink);
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [EnableCors("CorsPolicy")]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/mailchimpSurveyCampaignDetails/{id}")]
- public ActionResult GetMailChimpSurveyCampaignDetails(int id)
- {
- try
- {
- AppLog.Info("Campaigns GetMailChimpSurveyCampaignDetails started with input information [id= " + id + "]");
- var ExternalClientObject = _clientRepository.GetExternalServices(ClientId).Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim()).FirstOrDefault();
- var client = _clientRepository.GetById(ClientId);
- var emailCampaign = (SurveyCampaign)_campaignRepository.GetCampaign(id, ClientId);
- MailChimpKeyStore manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
- string mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
- MailChimpNewService mailchimp = new MailChimpNewService();
- if (emailCampaign.ServiceId == null)
- {
- return BadRequest(new Exception("Campaign does not exist in mailChimp"));
- }
- else
- {
- var mailChimpResponse = mailchimp.GetCampaignInformationById(emailCampaign.ServiceId, mailchimpKey);
- if (mailChimpResponse == null)
- {
- return BadRequest(new Exception("Error Calling MailChimp"));
- }
- AppLog.Info("Campaigns GetMailChimpSurveyCampaignDetails finished");
- return Ok(mailChimpResponse.RedirectLink);
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [EnableCors("CorsPolicy")]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/ExportEmailCampaign/{id}")]
- public ActionResult ExportEmailCampaign(int id)
- {
- try
- {
- AppLog.Info("Campaigns ExportEmailCampaign started with input information [id= " + id + "]");
- MailChimpCreateCampaignResponseModel campaignResponse;
- using (var scope = new TransactionScope())
- {
- var emailCampaign = (EmailCampaign)_campaignRepository.GetCampaign(id, ClientId);
- if (emailCampaign.ServiceId != null)
- {
- return BadRequest("Campaign already in MailChimp");
- }
- if(emailCampaign==null || emailCampaign.Campaign.CampaignAudiences==null || emailCampaign.Campaign.CampaignAudiences.Count() == 0)
- {
- return StatusCode(600,"Campaign Without Audiences Associated");
- }
- var ExternalClientObject = _clientRepository.GetExternalServices(ClientId)
- .Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
- .FirstOrDefault();
- var client = _clientRepository.GetById(ClientId);
- var mailchimp = new MailChimpNewService();
- var manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
- var mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
- var mailChimpListModel = ExportAudienceToMailChimp(id).Result;
- if (mailChimpListModel.Errors.Count() > 0)
- {
- mailchimp.DeleteAudience(mailChimpListModel.ListId, mailchimpKey);
- var errors = string.Join(", ", mailChimpListModel.Errors);
- return BadRequest($"Error to export audience to MailChimp: {errors}");
- }
- var segId = mailChimpListModel.ListId;
- if (segId == null)
- {
- throw new Exception("This campaign's audience has not been exported yet");
- }
- campaignResponse = mailchimp.CreateNewMailChimpCampaign(segId, id, null, emailCampaign.Campaign.Name, mailchimpKey);
- if (campaignResponse == null)
- {
- throw new Exception("No API Key associated with this client.");
- }
- bool updateExternalIdResult = _campaignRepository.UpdateEmailCampaignExternalCampaignId(emailCampaign.Id, campaignResponse.Id);
- if (!updateExternalIdResult)
- {
- return BadRequest("Error Setting ExternalId");
- }
- scope.Complete();
- }
- AppLog.Info("Campaigns ExportEmailCampaign finished");
- return Ok(campaignResponse.RedirectLink);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/audienceLists")]
- public IActionResult GetCampaignLists(TableModelView model)
- {
- try
- {
- AppLog.Info("GetCampaignLists started");
- AppLog.Info("GetCampaignLists finished");
- return Ok(this._campaignListsPaginatedViewModelFactory.Create(
- () => this._campaignRepository.GetCampaignAudienceLists(model.Id),
- list => new CampaignListViewModel
- {
- Id = list.Id,
- Name = list.Name,
- AudienceId = list.AudienceId,
- CampaignId = list.CampaignId,
- CreatedOn = list.CreatedOn,
- ClientId = list.ClientId,
- NumberSubscribers = list.NumberSubscribers
- },
- model.Page,
- model.PageSize,
- model.Search,
- model.OrderBy,
- model.Direction));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [EnableCors("CorsPolicy")]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/exportSurvey/{id}")]
- public ActionResult ExportSurveyCampaign(int id, string textToAppend = "")
- {
- try
- {
- AppLog.Info("Campaigns ExportSurveyCampaign started with input information [id= " + id + "]");
- MailChimpCreateCampaignResponseModel campaignResponse;
- using (var scope = new TransactionScope())
- {
- var surveyCampaign = (SurveyCampaign)_campaignRepository.GetCampaign(id, ClientId);
- if (surveyCampaign.ServiceId != null)
- {
- return BadRequest("Campaign already in MailChimp");
- }
- if(surveyCampaign.Campaign.CampaignAudiences==null ||surveyCampaign.Campaign.CampaignAudiences.Count()==0)
- {
- return StatusCode(600,"Campaign Without Audiences Associated");
- }
- var ExternalClientObject = _clientRepository.GetExternalServices(ClientId)
- .Where(x => x.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
- .FirstOrDefault();
- var client = _clientRepository.GetById(ClientId);
- var mailchimp = new MailChimpNewService();
- var manageKeyStore = new MailChimpKeyStore(client.Email, client.Salt);
- var mailchimpKey = manageKeyStore.Decrypt(ExternalClientObject.encKey);
- var mailChimpListModel = ExportAudienceToMailChimp(id).Result;
- if (mailChimpListModel.Errors.Count() > 0)
- {
- var errors = string.Join(", ", mailChimpListModel.Errors);
- return BadRequest($"Error to export audience to MailChimp: {errors}");
- }
- var databaseModel = _campaignAudienceSubscribers.BuildCampaignSubscribers(mailChimpListModel.CampaignGuid, mailChimpListModel.ListId, UserId()).Result; // Distinc data to send to Mail Chimp
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
- var subscribersEmail = campaignSubscribers
- .Select(cmp => cmp.SubscriberEmail)
- .ToList();
- if (subscribersEmail.Count() == 0)
- {
- return StatusCode(StatusCodes.Status406NotAcceptable, "Audience without subscribers");
- }
- var segId = mailChimpListModel.ListId;
- if (segId == null)
- {
- throw new Exception("This campaign's audience has not been exported yet");
- }
- var uri = HttpContext.Request.Host;
- var url = string.Concat(HttpContext.Request.Scheme, "://", uri);
- AppLog.Info(uri.ToString());
- var getEmailSurveyResponse = _surveyRepository.GetSurveyEmail(surveyCampaign.SurveyId, ClientId, Environment.GetEnvironmentVariable("APPSETTING_CallbackURL") ?? url, new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("DMP.Web.Resources.SurveyEmailTemplate.html")).ReadToEnd(), textToAppend);
- if (!getEmailSurveyResponse.IsResponseCodeOK())
- {
- return StatusCode(getEmailSurveyResponse.Code, getEmailSurveyResponse.Message);
- }
- var survey = getEmailSurveyResponse.ObjectNeeded as string;
- var audienceIds = surveyCampaign.Campaign.CampaignAudiences.Select(cmp => cmp.AudienceId);
- var createRequestsResponse = _surveyRepository.CreateRequests(surveyCampaign.SurveyId, UserId(), audienceIds);
- if (!createRequestsResponse.IsResponseCodeOK())
- {
- return StatusCode(createRequestsResponse.Code, createRequestsResponse.Message);
- }
- campaignResponse = mailchimp.CreateNewMailChimpCampaign(segId, id, survey, surveyCampaign.Campaign.Name, mailchimpKey);
- if (campaignResponse == null)
- {
- throw new Exception("No API Key associated with this client.");
- }
- _campaignRepository.AssociateSegmentId(surveyCampaign.Id, campaignResponse.Id);
- var subscriberIds = _audienceRepository.GetAudienceSubscribersByCampaign(surveyCampaign.Campaign.Id)
- .Select(cmp => cmp.Id);
- foreach (var subscriberId in subscriberIds)
- {
- _subscriberAggregateDataRepository.AddSubscriberSurveyToCount(subscriberId);
- }
- scope.Complete();
- //Task<DataBaseFunctionReturnModel> task = Task<DataBaseFunctionReturnModel>.Factory.StartNew(() =>
- //{
- //DataBaseFunctionReturnModel recomputeAllScoresReponse;
- //recomputeAllScoresReponse = ;
- //if (!recomputeAllScoresReponse.IsResponseCodeOK())
- //{
- // return StatusCode(recomputeAllScoresReponse.Code, recomputeAllScoresReponse.Message);
- //}
- //recomputeAllScoresReponse = _subscriberScoresRepository.RecomputeAllProfileScores();
- //if (!recomputeAllScoresReponse.IsResponseCodeOK())
- //{
- // return StatusCode(recomputeAllScoresReponse.Code, recomputeAllScoresReponse.Message);
- //}
- // return StatusCode(200, "Scores Updated");
- //});
- //if(task.Result.)
- }
- var jobId = Hangfire.BackgroundJob.Enqueue(() => _subscriberScoresRepository.RecomputeAllUserScores(ClientId));
- Hangfire.BackgroundJob.ContinueWith(jobId, () => _subscriberScoresRepository.RecomputeAllProfileScores(ClientId));
- AppLog.Info("Campaigns ExportSurveyCampaign finished");
- return Ok(campaignResponse.RedirectLink);
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/ExportSampleCampaign/{id}")]
- public ActionResult ExportSampleCampaign(int id)
- {
- try
- {
- AppLog.Info($"Campaigns ExportSampleCampaign started with input information [id= {id}]");
- var sampleCampaign = (SampleCampaign)_campaignRepository.GetCampaign(id, ClientId);
- if (sampleCampaign == null || sampleCampaign.Campaign.CampaignAudiences == null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
- {
- return StatusCode(600, "Campaign Without Audiences Associated");
- }
- var getProductResponse = _productRepository.GetProduct(sampleCampaign.ProductId);
- if (!getProductResponse.IsResponseCodeOK())
- {
- return StatusCode(getProductResponse.Code, getProductResponse.Message);
- }
- var prod = getProductResponse.ObjectNeeded as Product;
- var prodInfo = new List<(string, string)>
- {
- ("Product Name:", prod.Name),
- ("Product ID: ", prod.ExternalId.Split('_')[1]),
- ("Sample Campaign Name: ", sampleCampaign.Campaign.Name),
- ("Supplied Samples: ", sampleCampaign.SamplesNumber.ToString())
- };
- if (!sampleCampaign.Campaign.IsActive)
- {
- return StatusCode(StatusCodes.Status406NotAcceptable, new ServiceResponse()
- {
- MessageTitle = "Audience has not been generated",
- Message = "Audience has not been generated",
- InternalStatusCode = 406
- });
- }
- if (sampleCampaign.Campaign.CampaignAudiences != null)
- {
- var subscribers = _audienceRepository.GetAudienceSubscribersByCampaign(sampleCampaign.Campaign.Id)
- .GroupBy(x => x.Id)
- .Select(x => x.First())
- .ToList();
- DataBaseFunctionReturnModel databaseModel;
- databaseModel = _campaignAudienceSubscribers.GetCampaignSubscribers(id);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
- var items = subscribers
- .Where(cmp => campaignSubscribers.Any(cmp2 => cmp2.SubscriberId == cmp.Id))
- .Select(cmp => new[]
- {
- string.Concat(cmp.FirstName, " ", cmp.LastName),
- cmp.Email,
- $"{cmp.State}, {cmp.City}, {cmp.AddressLineOne}, {cmp.AddressLineTwo}, {cmp.ZipCode} "
- });
- var doc = _documentHandler.initFile()
- .AddInfo(prodInfo, "Product")
- .AddList(items, "Adressee Info", new[] { "Name", "Email", "Address" });
- var httpResponse = Response;
- httpResponse.Clear();
- httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
- httpResponse.Headers.Add("content-disposition", "attachment;filename=\"Fullfillment_List.xlsx\"");
- using (var memoryStream = new MemoryStream())
- {
- doc.SaveAs(memoryStream);
- memoryStream.Position = 0;
- var res = memoryStream.ReadFully();
- AppLog.Info("Campaigns ExportSampleCampaign finished");
- return File(res, "application/octet-stream");
- }
- }
- throw new Exception("This campaign does not have any subscribers associated");
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult GetAudienceToData(TableModelView model)
- {
- try
- {
- AppLog.Info("Campaigns GetAudienceToData started");
- AppLog.Info("Campaigns GetAudienceToData finished");
- //MISSING IS PENDING FROM CAMPAIGN AND SYNCED FROM AUDIENCE
- return Ok(this.audiencePaginatedViewModelFactory.Create(
- () => this._campaignRepository.GetCampaignAudiences(model.Id, ClientId),
- audience => new AudiencesViewModel
- {
- Id = audience.Id,
- Name = audience.Name,
- CreatedOn = audience.CreatedOn,
- UpdatedOn = audience.UpdatedOn,
- IsActive = audience.IsActive,
- AudienceMembers = audience.AudienceSubscriberCount
- },
- model.Page,
- model.PageSize,
- model.Search,
- model.OrderBy,
- model.Direction));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- public IActionResult GetCampaignToData(TableModelView model, CampaignType? type)
- {
- try
- {
- AppLog.Info("Campaigns GetCampaignToData Paging started");
- AppLog.Info("Campaigns GetCampaignToData Paging finished");
- //MISSING IS PENDING FROM CAMPAIGN AND SYNCED FROM AUDIENCE
- return Ok(this.campaignPaginatedViewModelFactory.Create(
- () => this._campaignRepository.GetAll(ClientId, type),
- campaign => new CampaignsViewModel
- {
- Id = campaign.Id,
- Name = campaign.Name,
- JobNumber = campaign.JobNumber,
- Account = campaign.Account,
- Brand = campaign.Brand,
- CreatedOn = campaign.CreatedOn,
- Type = campaign.Type,
- IsActive = campaign.IsActive,
- IsPending = campaign.IsPending
- },
- model.Page,
- model.PageSize,
- model.Search,
- model.OrderBy,
- model.Direction));
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/ExportToExcel")]
- public ActionResult ExportToExcel()
- {
- try
- {
- AppLog.Info("ExportToExcel started");
- var clientName = _clientRepository.GetById(ClientId).Name;
- var campaigns = _campaignRepository.GetAll(ClientId);
- var sampleCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Sample);
- var emailCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Email);
- var surveyCampaigns = campaigns.Where(campaign => campaign.Type == CampaignType.Survey);
- if (campaigns.Count() == 0)
- {
- return StatusCode(600, "This Client does not have any Campaigns associated");
- }
- var itemsCampaigns = campaigns.Select(campaign => new[]
- {
- campaign.Name ?? "--",
- campaign.JobNumber ?? "--",
- campaign.Account ?? "--",
- campaign.Brand ?? "--",
- campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
- campaign.Type.ToString() ?? "--",
- campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
- }).ToList();
- List<string[]> itemsSampleCampaigns = new List<string[]>();
- List<string[]> itemsEmailCampaigns = new List<string[]>();
- List<string[]> itemsSurveyCampaigns = new List<string[]>();
- if (sampleCampaigns.Count() != 0)
- {
- itemsSampleCampaigns = sampleCampaigns.Select(campaign => new[]
- {
- campaign.Name ?? "--",
- campaign.JobNumber ?? "--",
- campaign.Account ?? "--",
- campaign.Brand ?? "--",
- campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
- campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
- }).ToList();
- }
- if (emailCampaigns.Count() != 0)
- {
- itemsEmailCampaigns = emailCampaigns.Select(campaign => new[]
- {
- campaign.Name ?? "--",
- campaign.JobNumber ?? "--",
- campaign.Account ?? "--",
- campaign.Brand ?? "--",
- campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
- campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") :"Inactive"
- }).ToList();
- }
- if (emailCampaigns.Count() != 0)
- {
- itemsSurveyCampaigns = surveyCampaigns.Select(campaign => new[]
- {
- campaign.Name ?? "--",
- campaign.JobNumber ?? "--",
- campaign.Account ?? "--",
- campaign.Brand ?? "--",
- campaign.CreatedOn.ToString("MM-dd-yyyy hh:mm tt") ?? "--",
- campaign.IsActive == true ? (campaign.IsDeleted ? "Inactive" : "Active") : "Inactive"
- }).ToList();
- }
- var doc = _documentHandler.initFile().AddList(itemsCampaigns, $"Campaigns",
- new[]
- {
- "Name:",
- "Job Number:",
- "Account:",
- "Brand:",
- "Created On:",
- "Type:",
- "Status:"
- }
- ).AddList(itemsSampleCampaigns, $"Sample Campaigns",
- new[]
- {
- "Name:",
- "Job Number:",
- "Account:",
- "Brand:",
- "Created On:",
- "Status:"
- }
- ).AddList(itemsEmailCampaigns, $"Email Campaigns",
- new[]
- {
- "Name:",
- "Job Number:",
- "Account:",
- "Brand:",
- "Created On:",
- "Status:"
- }
- ).AddList(itemsSurveyCampaigns, $"Survey Campaigns",
- new[]
- {
- "Name:",
- "Job Number:",
- "Account:",
- "Brand:",
- "Created On:",
- "Status:"
- }
- );
- HttpResponse httpResponse = Response;
- httpResponse.Clear();
- httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
- httpResponse.Headers.Add("content-disposition", $"attachment;filename=\"{clientName}'s Campaigns.xlsx\"");
- using (MemoryStream memoryStream = new MemoryStream())
- {
- doc.SaveAs(memoryStream);
- memoryStream.Position = 0;
- var res = memoryStream.ReadFully();
- AppLog.Info("ExportToExcel finished");
- return File(res, "application/octet-stream");
- }
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- [HttpGet]
- [Authorize(Policy = "Read")]
- [Authorize(Policy = "Cadet")]
- [Route("campaigns/RedirectSampleAudience/Campaigns/{campaignId}")]
- public IActionResult RedirectCampaignSampleAudience(int campaignId)
- {
- AppLog.Info($"RedirectCampaignSampleAudience started with input information [campaignId= {campaignId}]");
- try
- {
- var databaseModel = _audienceRepository.GetAudienceByCampaign(campaignId, ClientId);
- if (!databaseModel.IsResponseCodeOK())
- {
- return StatusCode(databaseModel.Code, databaseModel.Message);
- }
- var campaign = databaseModel.ObjectNeeded as Campaign;
- var campaignAudiences = campaign.CampaignAudiences
- .Where(cmp => cmp.Audience.SampleAudience);
- if (campaignAudiences==null ||campaignAudiences.Count() == 0)
- {
- return StatusCode(600, "There is no Sample Audience type for Campaign");
- }
- var audienceId = campaignAudiences
- .FirstOrDefault().AudienceId;
- AppLog.Info("RedirectCampaignSampleAudience finished");
- return RedirectToAction("Details", "Audiences", new { Id = audienceId });
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- return BadRequest(e.Problem.Description);
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return BadRequest(e.Message);
- }
- }
- #endregion
- #region PRIVATE
- private bool CreateSampleCampaignLists(int id)
- {
- try
- {
- var sampleCampaign = (SampleCampaign)_campaignRepository.GetCampaign(id, ClientId);
- if (sampleCampaign == null || sampleCampaign.Campaign.CampaignAudiences == null || sampleCampaign.Campaign.CampaignAudiences.Count() == 0)
- {
- return false;
- }
- if (sampleCampaign.Campaign.CampaignAudiences != null)
- {
- DataBaseFunctionReturnModel databaseModel;
- using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
- {
- databaseModel = _campaignAudienceSubscribers.CreateCampaignAudienceSubscribers(id, UserId()).Result; // Create core data to send to Mail Chimp
- if (!databaseModel.IsResponseCodeOK() && databaseModel.Code != DatabaseCodes.AlreadyExists)
- {
- return false ;
- }
- if (databaseModel.IsResponseCodeOK())
- {
- var guid = (Guid)databaseModel.ObjectNeeded;
- databaseModel = _campaignAudienceSubscribers.CreateCampaignSubscribers(guid, string.Empty, UserId()).Result; // Create distinct data by subscriber
- }
- scope.Complete();
- return true;
- }
- }
- return false;
- }catch(Exception e)
- {
- return false;
- }
- }
- private async Task<MailChimpListModel> ExportAudienceToMailChimp(int campaignId)
- {
- var mailChimpListModel = new MailChimpListModel()
- {
- Errors = new List<MailChimpErrorModel>()
- };
- try
- {
- AppLog.Info($"ExportAudienceToMailChimp with input information [campaignId= {campaignId}]");
- using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
- {
- var campaign = _campaignRepository.GetById(campaignId, ClientId);
- if (campaign == null)
- {
- mailChimpListModel.Errors.Add(AddMailChimpError("Campaign do not exists"));
- return mailChimpListModel;
- }
- var databaseModel = await _campaignAudienceSubscribers.CreateCampaignAudienceSubscribers(campaignId, UserId()); // Create core data to send to Mail Chimp
- if (!databaseModel.IsResponseCodeOK())
- {
- mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
- return mailChimpListModel;
- }
- var guid = (Guid)databaseModel.ObjectNeeded;
- var client = _clientRepository.GetById(ClientId);
- var mailChimpUtil = new MailChimpUtil();
- var manageKeyStore = mailChimpUtil.CreateMailChimpKeyStore(client.Email, client.Salt);
- if (manageKeyStore == null)
- {
- mailChimpListModel.Errors.Add(AddMailChimpError("Error Creating MailChimp Key Store"));
- return mailChimpListModel;
- }
- var externalService = _clientRepository.GetExternalServices(ClientId)
- .Where(cmp => cmp.ServiceName.ToLower().Trim() == "MailChimp_Service".ToLower().Trim())
- .FirstOrDefault();
- var mailchimpKey = manageKeyStore.Decrypt(externalService.encKey);
- if (!mailChimpUtil.MailChimpKeyIsNull(mailchimpKey))
- {
- mailChimpListModel.Errors.Add(AddMailChimpError("Invalid MailChimp key"));
- return mailChimpListModel;
- }
- var audienceInfo = new AudienceInfo
- {
- Contact = new Contact(client.Name, client.AddressLineOne ?? string.Empty, client.AddressLineTwo ?? string.Empty,
- client.City, client.State, client.ZipCode, client.Country, client.Phone),
- ListName = campaign.Name,
- FromName = client.Name,
- FromEmail = client.Email,
- Reminder = "_",
- Language = "EN",
- Subject = string.Concat(campaign.Name, " - ", campaign.Type.ToString())
- };
- var mailchimpService = new MailChimpNewService();
- mailchimpService.mailChimpHttpClient = mailChimpUtil.CreateNewHttpClient();
- var mailChimpAudience = mailchimpService.CreateNewAudience(audienceInfo, mailchimpKey);
- string serviceId = mailChimpAudience.ListId;
- if (mailChimpAudience == null || mailChimpAudience.MailChimpOperationError != null || mailChimpAudience.ListId == null)
- {
- if (mailChimpAudience.MailChimpOperationError != null)
- {
- AppLog.Error($"MailChimp Error StatusCode: {mailChimpAudience.MailChimpOperationError.StatusCode} Message: {mailChimpAudience.MailChimpOperationError.ErrorMessage}");
- }
- mailChimpListModel.Errors.Add(AddMailChimpError("Error creating mailchimp audience"));
- return mailChimpListModel;
- }
- mailchimpService.mailChimpHttpClient = mailChimpUtil.CreateNewHttpClient();
- databaseModel = await _campaignAudienceSubscribers.BuildCampaignSubscribers(guid, mailChimpAudience.ListId, UserId()); // Distinc data to send to Mail Chimp
- if (!databaseModel.IsResponseCodeOK())
- {
- mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
- return mailChimpListModel;
- }
- var campaignSubscribers = databaseModel.ObjectNeeded as IEnumerable<CampaignSubscribers>;
- var subscribersEmail = campaignSubscribers
- .Select(cmp => cmp.SubscriberEmail)
- .ToList();
- mailChimpListModel = mailchimpService.UpdateMailChimpAudience(mailChimpAudience.ListId, subscribersEmail, client.Salt, "subscribed", mailchimpKey);
- if (mailChimpListModel == null || mailChimpListModel.Errors.Count() != 0)
- {
- if (mailChimpListModel.MailChimpOperationError != null)
- {
- AppLog.Error($"MailChimp Error StatusCode: {mailChimpListModel.MailChimpOperationError.StatusCode} Message: {mailChimpListModel.MailChimpOperationError.ErrorMessage}");
- }
- foreach (var error in mailChimpListModel.Errors)
- {
- AppLog.Error($"MailChimp Error: {(error.Email ?? "null")} Error: {(error.Error ?? "null")}");
- }
- mailChimpListModel.Errors.Add(AddMailChimpError("Error Updating Subscriber Audience"));
- mailChimpListModel.ListId = serviceId;
- return mailChimpListModel;
- }
- databaseModel = await _campaignAudienceSubscribers.CreateCampaignSubscribers(campaignSubscribers, mailChimpAudience.ListId); // Create distinct data to send to Mail Chimp
- if (!databaseModel.IsResponseCodeOK())
- {
- mailChimpListModel.Errors.Add(AddMailChimpError(databaseModel.Message));
- return mailChimpListModel;
- }
- mailChimpListModel.CampaignGuid = guid;
- mailChimpListModel.ListId = serviceId;
- scope.Complete();
- }
- AppLog.Info($"ExportAudienceToMailChimp finished");
- }
- catch (DmpException e)
- {
- AppLog.Error(e.Problem.Description);
- mailChimpListModel.Errors.Add(AddMailChimpError(e.Problem.Description));
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- mailChimpListModel.Errors.Add(AddMailChimpError(e.ToString()));
- }
- return mailChimpListModel;
- }
- private bool CreateSampleCampaignEntries(List<int> SampleIds, int sampleCampaignId, out List<SampleCampaignSample> addSampleCampaignSamples)
- {
- try
- {
- AppLog.Info("CreateSampleCampaignEntries started with input information [sampleCampaignId=" + sampleCampaignId + "]");
- List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
- foreach (int sampleId in SampleIds)
- {
- SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
- sampleCampaignSample.SampleCampaignId = sampleCampaignId;
- sampleCampaignSample.SampleId = sampleId;
- AuditCreate(sampleCampaignSample, UserId());
- sampleCampaignSampleList.Add(sampleCampaignSample);
- }
- AppLog.Info("CreateSampleCampaignEntries finished");
- addSampleCampaignSamples = sampleCampaignSampleList;
- return true;
- }
- catch (Exception e)
- {
- addSampleCampaignSamples = null;
- return false;
- }
- }
- private bool UpdateCampaignSamples(List<int> SampleIds, int sampleCampaignId)
- {
- try
- {
- using (var scope = new TransactionScope())
- {
- AppLog.Info("UpdateCampaignSamples started");
- var getAllSampleCampaignSampleResponse = _sampleCampaignSampleRepository.GetById(sampleCampaignId);
- if (!getAllSampleCampaignSampleResponse.IsResponseCodeOK())
- {
- return false;
- }
- IQueryable<SampleCampaignSample> sampleCampaignSamples = getAllSampleCampaignSampleResponse.ObjectNeeded as IQueryable<SampleCampaignSample>;
- List<SampleCampaignSample> sampleCampaignSamplesList = sampleCampaignSamples.ToList();
- if (sampleCampaignSamplesList == null || sampleCampaignSamplesList.Count() == 0)
- {
- List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
- foreach (int sampleId in SampleIds)
- {
- SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
- sampleCampaignSample.SampleCampaignId = sampleCampaignId;
- sampleCampaignSample.SampleId = sampleId;
- AuditCreate(sampleCampaignSample, UserId());
- sampleCampaignSampleList.Add(sampleCampaignSample);
- }
- var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
- if (!createSampleCampaignsResponse.IsResponseCodeOK())
- {
- return false;
- }
- }
- List<SampleCampaignSample> InactiveSampleCampaigns = sampleCampaignSamplesList.Where(x => !SampleIds.Contains(x.SampleId)).ToList();
- if (InactiveSampleCampaigns != null && InactiveSampleCampaigns.Count() > 0)
- {
- foreach (var inactivate in InactiveSampleCampaigns)
- {
- inactivate.IsActive = false;
- inactivate.IsDeleted = false;
- AuditEdit(inactivate);
- }
- var updateInactiveSampleCampaignSamples = _sampleCampaignSampleRepository.Update(InactiveSampleCampaigns);
- if (!updateInactiveSampleCampaignSamples.IsResponseCodeOK())
- {
- return false;
- }
- }
- List<SampleCampaignSample> ActivateSampleCampaigns = sampleCampaignSamplesList.Where(x => !x.IsActive && SampleIds.Contains(x.SampleId)).ToList();
- if (ActivateSampleCampaigns != null && ActivateSampleCampaigns.Count() > 0)
- {
- foreach (var activate in ActivateSampleCampaigns)
- {
- activate.IsActive = true;
- activate.IsDeleted = false;
- AuditEdit(activate);
- }
- var updateActiveSampleCampaignSamples = _sampleCampaignSampleRepository.Update(ActivateSampleCampaigns);
- if (!updateActiveSampleCampaignSamples.IsResponseCodeOK())
- {
- return false;
- }
- }
- List<int> presentSampleCampaignIds = sampleCampaignSamplesList.Select(x => x.SampleId).ToList();
- List<int> createSampleCampaignIds = SampleIds.Except(presentSampleCampaignIds).ToList();
- if (createSampleCampaignIds != null && createSampleCampaignIds.Count() > 0)
- {
- List<SampleCampaignSample> sampleCampaignSampleList = new List<SampleCampaignSample>();
- foreach (int sampleId in createSampleCampaignIds)
- {
- SampleCampaignSample sampleCampaignSample = new SampleCampaignSample();
- sampleCampaignSample.SampleCampaignId = sampleCampaignId;
- sampleCampaignSample.SampleId = sampleId;
- AuditCreate(sampleCampaignSample, UserId());
- sampleCampaignSampleList.Add(sampleCampaignSample);
- }
- var createSampleCampaignsResponse = _sampleCampaignSampleRepository.Create(sampleCampaignSampleList);
- if (!createSampleCampaignsResponse.IsResponseCodeOK())
- {
- return false;
- }
- }
- scope.Complete();
- }
- AppLog.Info("UpdateCampaignSamples finished");
- return true;
- }
- catch (Exception e)
- {
- AppLog.Error(e.ToString());
- return false;
- }
- }
- private MailChimpErrorModel AddMailChimpError(string errorMessage)
- {
- try
- {
- return new MailChimpErrorModel()
- {
- Error = errorMessage
- };
- }
- catch (Exception)
- {
- throw;
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement