Exemplo n.º 1
0
        public ActionResult CreateCampaign(CampaignFormViewModel formCampaign)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Campaign newCampaign =
                        Mapper.Map <CampaignFormViewModel, Campaign>(formCampaign);

                    campaignService.CreateCampaign(newCampaign);
                    campaignService.CommitChanges();
                }
                else
                {
                    return(View(formCampaign));
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ViewBag["error"] = ex.Message;
                return(View(formCampaign));
            }
        }
        public async Task <IActionResult> CreateCampaign([FromBody] CreateCampaignInputDto request)
        {
            try
            {
                var user = await _userManager.FindByEmailFromClaimsPrinciple(HttpContext.User);

                var validationResponse = await _campaignService.ValidateCreateInput(request);

                if (!validationResponse.IsSuccess)
                {
                    return(BadRequest(new ApiResponse(validationResponse.StatusCode, validationResponse.Message)));
                }

                var campaignMapped = _mapper.Map <Campaign>(request);
                campaignMapped.CreatedDate = DateTime.UtcNow;
                campaignMapped.CreatedBy   = user.Id.ToString();
                await _campaignService.CreateCampaign(campaignMapped);

                return(Ok(new ApiResponse(200, "Success")));
            }
            catch
            {
                return(BadRequest(new ApiResponse(400, "Something went wrong.")));
            }
        }
Exemplo n.º 3
0
        public IActionResult Create(Campaign campaign)
        {
            try
            {
                if (campaign.StartedDate >= campaign.EndDate)
                {
                    ModelState.AddModelError("StartedDate", "Kampanya baþlangýç tarihi bitiþ tarihinden sonra olamaz.");
                }
                else if (ModelState.IsValid)
                {
                    campaign.CreatedBy = User.Identity.Name;
                    campaign.UpdateBy  = User.Identity.Name;
                    CampaignService.CreateCampaign(campaign);
                    CampaignService.SaveCampaign();
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Create"));

                throw ex;
            }

            return(View(campaign));
        }
        public async Task <IHttpActionResult> Post(CampaignCreateViewModel model)
        {
            if (model == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var brand = await _brandService.GetBrand(model.BrandUuid.GetValueOrDefault(Guid.Empty)).ConfigureAwait(false);

            if (brand == null)
            {
                return(BadRequest("The specified brand was not found."));
            }

            var campaign = _mapping.Map <Campaign>(model);
            await _campaignService.CreateCampaign(campaign).ConfigureAwait(false);

            campaign = await _campaignService.GetCampaign(campaign.CampaignUuid).ConfigureAwait(false);

            var campaignViewModel = _mapping.Map <CampaignViewModel>(campaign);

            return(CreatedAtRoute("Campaigns.GetById", new { Id = campaignViewModel.CampaignUuid }, campaignViewModel));
        }
Exemplo n.º 5
0
 public void it_should_throw_exception_due_to_invalid_amount(double amount)
 {
     action = () =>
     {
         campaignService.CreateCampaign(categoryTitle, amount, discountMinItemCount, discountType);
     };
     action.Should().Throw <Exception>();
 }
Exemplo n.º 6
0
        private string CreateCampaignCommand(string[] splittedArray)
        {
            string name                   = splittedArray[1];
            string productCode            = splittedArray[2];
            int    duration               = splittedArray[3].ToInt();
            double priceManipulationLimit = splittedArray[4].ToDouble();
            int    targetSalesCount       = splittedArray[5].ToInt();

            return(_campaignService.CreateCampaign(name, productCode, duration, priceManipulationLimit, targetSalesCount));
        }
        public void Setup()
        {
            SetUpMocks();
            campaignService = new CampaignService(campaignRepo, categoryService.Object, productService.Object);

            action = () =>
            {
                campaignService.CreateCampaign(categoryTitle, discountAmount, discountMinItemCount, discountType);
            };
        }
Exemplo n.º 8
0
        public ActionResult Campaign(CreateCampaignViewModel campaign)
        {
            if (ModelState.IsValid)
            {
                var newCampaign = _campaignService.CreateCampaign(campaign.Name, campaign.Description);

                return(Json(new { state = "Success", additional = Url.Action("Campaign", new { id = newCampaign.CampaignId }) }));
            }

            return(Json(new { state = "Fail", additional = "Need to fill in all data" }));
        }
Exemplo n.º 9
0
 public void CreateCampaign([FromBody] CampaignDTO data)
 {
     _logger.LogInformation(0, "inside method");
     try
     {
         campaignService.CreateCampaign(data);
     }
     catch (Exception ex)
     {
         _logger.LogInformation(4, ex.Message);
     }
 }
Exemplo n.º 10
0
        public async Task <IActionResult> CreateTarget(CreateCampaignTargetViewModel model)
        {
            if (ModelState.IsValid)
            {
                var valid = true;
                if (valid)
                {
                    var info = JsonConvert.DeserializeObject <CreateCampaignInfoViewModel>(model.InfoModel);

                    var id = await _campaignService.CreateCampaign(CurrentUser.Id, info, model, CurrentUser.Username);

                    if (id > 0)
                    {
                        if (model.AccountIds != null)
                        {
                            var accountids = model.AccountIds.Distinct().ToList();

                            for (var i = 0; i < accountids.Count; i++)
                            {
                                var amount = model.AmountMax; //model.AccountType.Contains(AccountType.Regular) ? model.AccountChargeAmount ?? 0 : model.AccountChargeAmounts[i];

                                //Anh Long sửa lại, không cần thiết phải BackgroundJob
                                await _campaignService.CreateCampaignAccount(CurrentUser.Id, id, accountids[i], amount, CurrentUser.Username);

                                //BackgroundJob.Enqueue<ICampaignService>(m => m.CreateCampaignAccount(CurrentUser.Id, id, accountids[i], amount, CurrentUser.Username));
                            }
                        }
                        //########### Longhk add create notification ##########################################################

                        string _msg  = string.Format("Chiến dịch \"{0}\" đã được tạo bởi \"{1}\".", info.Title, CurrentUser.Name);
                        string _data = "Campaign";
                        await _notificationService.CreateNotification(id, EntityType.System, 0, NotificationType.CampaignCreated, _msg, _data);

                        //#####################################################################################################

                        TempData["MessageSuccess"] = "Tạo chiến dịch thành công, bạn vui lòng chờ hệ thống duyệt chiến dịch của bạn!";

                        return(RedirectToAction("Details", new { id = id }));
                    }
                    else
                    {
                        TempData["MessageError"] = "Lỗi khi tạo chiến dịch vui lòng thử lại";
                    }
                }
            }
            await ViewbagData();

            return(View("CreateTarget", model));
            //await ViewbagData();
            //return View(model);
        }
Exemplo n.º 11
0
        public bool StartApp(string action)
        {
            var commandLine = Console.ReadLine();

            var commandArray = commandLine?.Split(' ');

            action = commandArray.FirstOrDefault();

            var result = true;

            switch (action?.ToLower())
            {
            case "create_product":
                Console.WriteLine(_productService.CreateProduct(commandArray));
                break;

            case "get_product_info":
                Console.WriteLine(_productService.GetProductInfo(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "create_campaign":
                Console.WriteLine(_campaignService.CreateCampaign(commandArray));
                _timerService.Start();
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "get_campaign_info":
                Console.WriteLine(_campaignService.GetCampaignInfo(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "increase_time":
                Console.WriteLine(_appTimeService.IncreaseTime(commandArray));
                result = _campaignService.IsExistActiveCampaign();
                break;

            case "exit":
                _timerService.End();
                Console.WriteLine("bye bye");
                result = false;
                break;

            default:
                Console.WriteLine("Incorrect command usage!");
                break;
            }

            return(result);
        }
Exemplo n.º 12
0
        public IActionResult Create(Campaign campaign)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    campaign.CreatedBy = User.Identity.Name;
                    campaign.UpdateBy  = User.Identity.Name;
                    campaignService.CreateCampaign(campaign);
                    campaignService.SaveCampaign();

                    campaign.CategoryCampaign.Clear();
                    campaign.ProductCampaign.Clear();

                    if (campaign.CategoryIds != null)
                    {
                        foreach (var categoryId in campaign.CategoryIds)
                        {
                            campaign.CategoryCampaign.Add(new CategoryCampaign()
                            {
                                CampaignId = campaign.Id, CategoryId = categoryId
                            });
                        }
                    }
                    if (campaign.ProductIds != null)
                    {
                        foreach (var productId in campaign.ProductIds)
                        {
                            campaign.ProductCampaign.Add(new ProductCampaign()
                            {
                                CampaignId = campaign.Id, ProductId = productId
                            });
                        }
                    }
                    categoryService.SaveCategory();

                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Create"));

                throw ex;
            }
            ViewData["Categories"] = new MultiSelectList(categoryService.GetCategories(), "Id", "Name", campaign.CategoryIds);
            ViewData["Products"]   = new MultiSelectList(productService.GetProducts(), "Id", "Name", campaign.ProductIds);
            return(View(campaign));
        }
Exemplo n.º 13
0
 private void ExecuteCreateCampaignCommand(string[] input)
 {
     try
     {
         var          categoryTitle = input[1];
         double       amount        = ParseToDouble(input[2]);
         int          minItemCount  = Int32.Parse(input[3]);
         DiscountType type          = (DiscountType)Int32.Parse(input[4]);
         CampaignService.CreateCampaign(categoryTitle, amount, minItemCount, type);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
Exemplo n.º 14
0
        public ActionResult Save(Campaign campaign)
        {
            if (!Session.IsSignedIn())
            {
                return(Json(new { saved = false }));
            }

            campaign.ManagerId = Session.GetSignedInManager().Id;

            if (!campaignService.IsValidCampaign(campaign, out var cause))
            {
                return(Json(new { saved = false, cause = cause }));
            }
            else
            {
                var saved = campaignService.CreateCampaign(campaign);

                return(Json(new { saved }));
            }
        }
Exemplo n.º 15
0
 private void CreateProductCampaignAndOrder()
 {
     _productService.CreateProduct("create_product P11 100 1000");
     _campaignService.CreateCampaign("create_campaign C11 P11 10 20 100");
     _orderService.CreateOrder("create_order P11 10");
 }
Exemplo n.º 16
0
        public ActionResult <string> CreateCampaign(string name, string productCode, int duration, int priceManipulationLimit, int targetSalesCount)
        {
            var result = _campaignService.CreateCampaign(name, productCode, duration, priceManipulationLimit, targetSalesCount);

            return("Campaign created; name " + result.Name + ", product " + result.ProductCode + ", duration " + result.Duration + ", limit " + result.PriceManipulationLimit + ", target sales count " + result.TargetSalesCount);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Create(CreateCampaignViewModel model, int submittype = 0)
        {
            var error = "";

            if (ModelState.IsValid)
            {
                var valid = true;

                if (model.Method == CampaignMethod.ChooseAccount)
                {
                    if (model.AccountType.Contains(AccountType.Regular))
                    {
                        //generate accountids

                        var matchedAccountIds           = new List <int>();
                        var matchedAccountChargeAmounts = new List <int>();
                        var matchedAccounts             = await _accountService.GetListAccount(model.AccountType, model.CategoryId, model.Gender, model.CityId, model.AgeStart, model.AgeEnd, string.Empty, 1, model.Quantity, null, 0, 0);

                        foreach (var matchedAccount in matchedAccounts.Accounts)
                        {
                            matchedAccountIds.Add(matchedAccount.Id);
                            matchedAccountChargeAmounts.Add(0);
                        }
                        model.AccountIds           = matchedAccountIds;
                        model.AccountChargeAmounts = matchedAccountChargeAmounts;
                    }



                    if (model.AccountType == null || model.AccountType.Count == 0)
                    {
                        valid = false;
                        error = "Hãy chọn đối tượng ";
                    }
                    else if (model.AccountIds == null || model.AccountIds.Count == 0 || model.AccountIds.Count != model.AccountChargeAmounts.Count)
                    {
                        valid = false;
                        error = "Không có Kol phù hợp. Vui lòng chộn các tiêu chí khác";
                    }
                }
                else
                {
                    model.AccountIds           = new List <int>();
                    model.AccountChargeAmounts = new List <int>();
                }

                if (valid)
                {
                    if (!string.IsNullOrEmpty(model.Image))
                    {
                        model.Image = _fileHelper.MoveTempFile(model.Image, "campaign");
                    }
                    var id = await _campaignService.CreateCampaign(CurrentUser.Id, model, CurrentUser.Username);

                    if (id > 0)
                    {
                        for (var i = 0; i < model.AccountIds.Count; i++)
                        {
                            var amount = model.AccountType.Contains(AccountType.Regular) ? model.AccountChargeAmount ?? 0 : model.AccountChargeAmounts[i];
                            BackgroundJob.Enqueue <ICampaignService>(m => m.CreateCampaignAccount(CurrentUser.Id, id, model.AccountIds[i], amount, CurrentUser.Username));
                        }
                        return(Json(new
                        {
                            status = 1,
                            message = "Thêm chiến dịch mới thành công",
                            campaignid = id,
                            url = Url.Action("Details", new { id = id })
                        }));
                    }
                    else
                    {
                        error = "Lỗi khi khởi tạo chiến dịch. Vui lòng thử lại";
                    }
                }
            }
            return(Json(new
            {
                status = -1,
                message = error
            }));
            //await ViewbagData();
            //return View(model);
        }
Exemplo n.º 18
0
 public CampaignViewModel Post(CampaignViewModel campaign)
 {
     CampaignService.SetUser(User);
     return(CampaignService.CreateCampaign(campaign));
 }
Exemplo n.º 19
0
 public IActionResult CreateCampaign([FromBody] CreateCampaignRequest createCampaignRequest)
 {
     _campaignService.CreateCampaign(createCampaignRequest.ParseCreateCampaignRequest());
     return(Ok());
 }
Exemplo n.º 20
0
 public void Create_Campaign_Should_Throw_Exception()
 {
     Assert.Throws <Exception>(() => _campaignService.CreateCampaign("create_campaign C1 P4 5 20 sds"));
 }
Exemplo n.º 21
0
        public void ApplyCommands(List <string> commands)
        {
            foreach (var command in commands)
            {
                var commandProperties = command.Split(" ");
                var commandName       = commandProperties.First();

                switch (commandName)
                {
                case "create_product":

                    _productService.CreateProduct(command);
                    SleepScreen();
                    break;

                case "create_campaign":

                    _campaignService.CreateCampaign(command);
                    SleepScreen();
                    break;

                case "get_product_info":

                    if (commandProperties.Length > 1)
                    {
                        var productCode = commandProperties[1];
                        _productService.GetProductInfo(productCode);
                    }
                    SleepScreen();
                    break;

                case "create_order":
                    _orderService.CreateOrder(command);
                    SleepScreen();

                    break;

                case "get_campaign_info":

                    _campaignService.GetCampaignInfo();
                    SleepScreen();
                    break;

                case "increase_time":

                    Console.WriteLine(command);

                    var hour = int.Parse(commandProperties[1]);

                    var product = _productService.GetProduct();

                    if (_campaignService.IsCampaignExist(product.ProductCode))
                    {
                        _campaignService.DecreaseCampaignDuration(hour);

                        var campaignStatus = _campaignService.GetCampaign().Status;

                        if (campaignStatus == Status.Active)
                        {
                            var orderQuantityInPerPeriodOfCampaign = _orderService.GetOrderQuantityInPerPeriodOfCampaign();

                            var targetSalesCountInHour = _campaignService.GetTargetSalesCountInHour();

                            var orderCountInCampaignPeriod = orderQuantityInPerPeriodOfCampaign / hour;

                            _productService.TryToChangeProductPrice(orderCountInCampaignPeriod, targetSalesCountInHour);
                        }
                    }
                    _orderService.SetZeroOrderQuantityInPerPeriodOfCampaign();

                    SleepScreen();
                    break;

                default:
                    throw new InvalidDataException("Invalid Command");
                }
            }
        }
 public void Setup()
 {
     SetUpMocks();
     campaignService = new CampaignService(campaignRepo, categoryService.Object, productService.Object);
     campaignService.CreateCampaign(ParentCategory, discountAmount, discountMinItemCount, discountType);
 }