private int GetWinCount(CouponDto coupon, Cekilis cekilis)
        {
            string[] couponNumbers  = coupon.Numbers.Split('-');
            string[] cekilisNumbers = cekilis.numbers.Split('-');

            return(couponNumbers.Where(n => cekilisNumbers.Contains(n)).Count());
        }
Esempio n. 2
0
        public void Map_MapFromCouponDtoToCoupon_CorrectType()
        {
            var couponDto = new CouponDto();
            var coupon    = uut.Map <Coupon>(couponDto);

            Assert.That(coupon, Is.TypeOf <Coupon>());
        }
Esempio n. 3
0
        public async Task <ApiRequestResult> AddAsync(CouponDto dto)
        {
            var command = dto.EntityMap <CouponDto, Coupon>();

            command.Id = Guid.NewGuid();
            if (dto.ProductRelationList.Count > 0)
            {
                var newEntitys = dto.ProductRelationList.Select(c => new CouponProductRelation
                {
                    CouponId    = command.Id,
                    ProductId   = c.ProductId,
                    ProductName = c.ProductName,
                    ProductSn   = c.ProductSn,
                }).ToList();
                await _couponProductRelationRepository.MultiAddAsync(newEntitys);
            }

            if (dto.ProductCategoryRelationList.Count > 0)
            {
                var newEntitys = dto.ProductCategoryRelationList.Select(c => new CouponProductCategoryRelation
                {
                    CouponId            = command.Id,
                    ProductCategoryId   = c.ProductCategoryId,
                    ProductCategoryName = c.ProductCategoryName,
                    ParentCategoryName  = c.ParentCategoryName,
                }).ToList();
                await _couponProductCategoryRelationRepository.MultiAddAsync(newEntitys);
            }
            await _couponRepository.AddAsync(command);

            return(ApiRequestResult.Success("添加成功"));
        }
        public CheckoutDto CalculateTotals(string cartId, CouponDto couponDto)
        {
            var coupon = _mapper.Map <Coupon>(couponDto);
            var cart   = GetCartFromDb(cartId);

            return(_checkOutEngine.CalculateTotals(cart, coupon));
        }
Esempio n. 5
0
        public void BatchSendCouponsByUserEmailsAsync(IList <string> emails, CouponDto coupon)
        {
            foreach (var email in emails)
            {
                // step 1: Create payloads: user email, coupon ID
                IList <object> payloads = new List <object>()
                {
                    "emails", coupon.Id.ToString()
                };

                // Step 2: Generate email confirm token
                var    token     = JwtTokenHelper.GenerateToken(payloads, coupon.EndTimeUTC, _tokenConfig.Key);
                string tokenHtml = HttpUtility.UrlEncode(token);

                // Step 3: Generate email data
                var from = _emailConfigs.SenderGeneral;
                var tos  = new List <string>()
                {
                    email
                };
                var ccs         = new List <string>();
                var subject     = "Course Studio New Coupon Is Coming";
                var confirmUrl  = _emailConfigs.CouponRedeemUrl + "?userId=" + email + "&coupon=" + coupon.Id + "&token=" + tokenHtml;
                var HtmlContent = "<p>Course Studio new coupon is comingwer</p><br>" + confirmUrl;

                // Step 4: send email
                // TODO: shouldn't use the ASYNC method
                SendAsync(from, tos.ToArray(), ccs.ToArray(), subject, HtmlContent);
            }
        }
        public async Task <CouponResponseDto> SaveCoupon(CouponDto couponDto)
        {
            if (couponDto is null)
            {
                throw new ArgumentNullException(nameof(CouponDto));
            }

            try
            {
                UnitOfWork.StartTransaction();

                var coupon = new Coupon(couponDto.AdvertisementId, couponDto.UserId);
                coupon.ExpiredAt = coupon.CreatedAt.AddHours(4);

                await UnitOfWork.CouponRepository.InsertOne(coupon);

                await UnitOfWork.CommitTransaction();

                return(Mapper.Map <Coupon, CouponResponseDto>(coupon));
            }
            catch (Exception ex)
            {
                await UnitOfWork.RollBackTransaction();

                throw new InvalidOperationException(ex.Message);
            }
        }
Esempio n. 7
0
        public JsonResult Update(CouponDto dto)
        {
            Coupon coupon = _couponContract.Coupons.Where(x => x.Id == dto.Id).FirstOrDefault();
            var    res    = _couponContract.Update(dto);

            return(Json(res));
        }
        public async Task <dynamic> DeleteAsync(string couponId)
        {
            CouponSelectorForId couponSelector = CouponSelectorForId.Build(couponId);

            using (var client = CloudantClient())
            {
                CouponDto item     = null;
                var       response = await client.PostAsync(_dbName + "/_find", new StringContent(JsonConvert.SerializeObject(couponSelector), Encoding.UTF8, "application/json"));

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();

                    CouponListDto couponList = JsonConvert.DeserializeObject <CouponListDto>(responseJson);
                    if (couponList != null && couponList.docs != null && couponList.docs.Count > 0)
                    {
                        item = couponList.docs[0];
                    }
                }
                if (item != null)
                {
                    response = await client.DeleteAsync(_dbName + "/" + _urlEncoder.Encode(item._id.ToString()) + "?rev=" + _urlEncoder.Encode(item._rev.ToString()));

                    if (response.IsSuccessStatusCode)
                    {
                        return(true);
                    }
                    string msg = "Failure to DELETE. Status Code: " + response.StatusCode + ". Reason: " + response.ReasonPhrase;
                    Console.WriteLine(msg);
                }
                return(false);;
            }
        }
Esempio n. 9
0
        public async Task <ActionResult <Coupon> > UpdateBasket([FromBody] CouponDto coupon)
        {
            var couponEntity = _mapper.Map <Coupon>(coupon);

            _repository.UpdateCoupon(couponEntity);
            await _repository.SaveChangesAsync();

            return(Ok(coupon));
        }
Esempio n. 10
0
        public bool Validate(CouponDto request)
        {
            if (_context.Coupons.Any(x => x.Code == Functions.CreateSha256Hash(request.Code)))
            {
                throw new EntityAlreadyExistsException();
            }

            return(true);
        }
Esempio n. 11
0
        public async Task <ActionResult <Coupon> > CreateDiscount([FromBody] CouponDto coupon)
        {
            var couponEntity = _mapper.Map <Coupon>(coupon);

            _repository.CreateCoupon(couponEntity);
            await _repository.SaveChangesAsync();

            var couponToReturn = _mapper.Map <CouponDto>(couponEntity);

            return(CreatedAtRoute("GetCoupon", new { id = couponToReturn.Id }, couponToReturn));
        }
Esempio n. 12
0
        public JsonResult Create(CouponDto dto)
        {
            if (dto.UniqueNum == null)
            {
                int           adminId = AuthorityHelper.OperatorId ?? 0;
                Administrator admin   = _administratorContract.Administrators.Where(x => x.Id == adminId).FirstOrDefault();
                dto.UniqueNum = admin.Member.UniquelyIdentifies;
            }
            var result = _couponContract.Insert(dto);

            return(Json(result));
        }
        public async Task <CouponDto> Update(CouponDto coupon)
        {
            var entity        = _mapper.Map <Coupon>(coupon);
            var modelToUpdate = await _couponRepository.FindByCondition(x => x.Id == entity.Id);

            if (!modelToUpdate.Any())
            {
                throw new ApiException("No se pudo editar el coupon", HttpStatusCode.NotFound);
            }
            _couponRepository.Update(entity);
            return(_mapper.Map <CouponDto>(entity));
        }
Esempio n. 14
0
 public async Task <IActionResult> Update([FromBody] CouponDto coupon)
 {
     try
     {
         return(Ok(await _couponService.Update(coupon)));
     }
     catch (Exception e)
     {
         _loggerManager.LogError($"Ocurrio un error mientras se modificaba el coupon: {e}");
         throw new ApiException(AppResources.BadRequest, HttpStatusCode.BadRequest);
     }
 }
Esempio n. 15
0
        public ResponseOutput ExchangeCoupon(CouponInputDto couponInputDto)
        {
            CouponDto dto = new CouponDto();

            try
            {
                _logger.LogInformation("进入ExchangeCoupon方法");
                //先判断券是否有效
                var ret = _couponService.VerifyCoupon(couponInputDto.Code, couponInputDto.Password);
                if (ret)
                {
                    var coupon = _couponService.GetCouponByCode(couponInputDto.Code);
                    //判断此券是不是此批次号
                    if (coupon.BatchId != couponInputDto.BatchId)
                    {
                        return(new ResponseOutput(null, "-1", $"此券不属于批次号{ couponInputDto.BatchId}", HttpContext.TraceIdentifier));
                    }
                    dto = new CouponDto
                    {
                        Code           = coupon.Code,
                        BatchId        = coupon.BatchId,
                        ValidityDate   = coupon.ValidityDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        AvaliableCount = coupon.AvaliableCount,
                        TotalCount     = coupon.TotalCount
                    };
                    //判断是否过期 t1<t2
                    if (DateTime.Compare(coupon.ValidityDate, DateTime.Now) < 0)
                    {
                        dto.IsOutDate = true;
                        return(new ResponseOutput(dto, "-1", "此券已过期", HttpContext.TraceIdentifier));
                    }
                    else
                    {
                        dto.IsOutDate = false;
                    }
                    if (coupon.AvaliableCount <= 0)
                    {
                        return(new ResponseOutput(dto, "0", "此券次数已用完", HttpContext.TraceIdentifier));
                    }
                    return(new ResponseOutput(dto, "0", "兑换成功,可用次数为" + coupon.AvaliableCount--, HttpContext.TraceIdentifier));
                }
                else
                {
                    return(new ResponseOutput(null, "-1", "劵信息获取失败", HttpContext.TraceIdentifier));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"异常为{ex.ToString()}");
                return(new ResponseOutput(null, "-1", ex.Message, HttpContext.TraceIdentifier));
            }
        }
Esempio n. 16
0
        public ActionResult <CheckoutDto> CalculateTotals(string id, [FromBody] CouponDto coupon)
        {
            try
            {
                return(_shoppingCartManager.CalculateTotals(id, coupon));
            }
            catch (ShoppingCartNotFoundException)
            {
                _logger.LogError($"Shopping cart {id} not found");

                return(NotFound());
            }
        }
Esempio n. 17
0
 public ActionResult Edit(CouponDto couponDto)
 {
     if (ModelState.IsValid)
     {
         var userId = User.Identity.GetUserId();
         var coupon = db.Coupons.SingleOrDefault(x => x.Id == couponDto.Id);
         coupon = Mapper.Map(couponDto, coupon);
         coupon.SetModifiedData(userId);
         db.Entry(coupon).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.UserId = User.Identity.GetUserId(); return(View(couponDto));
 }
Esempio n. 18
0
 public async Task <IActionResult> Add([FromBody] CouponDto coupon)
 {
     try
     {
         coupon.Id = Guid.NewGuid();
         _couponService.Create(coupon);
         return(CreatedAtAction(nameof(GetById), new { version = HttpContext.GetRequestedApiVersion().ToString(), id = coupon.Id }, coupon));
     }
     catch (Exception e)
     {
         _loggerManager.LogError($"Ocurrio un error cuando se intentaba guardar el cupon: {e}");
         throw new ApiException(AppResources.BadRequest, HttpStatusCode.BadRequest);
     }
 }
Esempio n. 19
0
 public IActionResult EditCoupon([FromBody] CouponDto couponDto)
 {
     try
     {
         var coupon = _mapper.Map <Coupon>(couponDto);
         _unitOfWork.CouponRepository.Edit(coupon);
         _unitOfWork.Complete();
         return(Created(string.Format($"api/bars/{coupon.BarName}/coupons/{coupon.CouponID}"), couponDto));
     }
     catch (Exception e)
     {
         return(BadRequest());
     }
 }
Esempio n. 20
0
        public ActionResult Index(CouponDto couponDto)
        {
            if (ModelState.IsValid)
            {
                var userId = User.Identity.GetUserId();
                var coupon = Mapper.Map <CouponDto, Coupon>(couponDto);
                coupon.NewCreatedData(userId);
                db.Coupons.Add(coupon);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.UserId = User.Identity.GetUserId(); return(View(couponDto));
        }
Esempio n. 21
0
        public static CouponModel ToModel(this CouponDto source)
        {
            if (source == null)
            {
                return(null);
            }

            return(new CouponModel
            {
                Amount = source.Amount,
                Code = source.Code,
                AlreadyUsed = source.AlreadyUsed,
                CouponId = source.CouponId
            });
        }
Esempio n. 22
0
        // 比分投注单
        // GET: /Casino/MyCoupon

        public ActionResult MyCoupon()
        {
            var model = new MyCouponDto();

            var days = ConfigGlobal_AcnCasino.CasinoValidDays;

            var query = _repo.Query <MatchView>(
                x => x.PlayTime > DateTime.Now && x.PlayTime < DateTime.Now.AddDays(days))
                        .FindAll(x => !x.ResultHome.HasValue && !x.ResultAway.HasValue)
                        .OrderBy(x => x.PlayTime)
                        .Many <MatchView, ChoiceOption, Guid>(t => t.CasinoItem.ID);

            var mapper = MatchDto.ConfigMapper().CreateMapper();

            var mList = mapper.Map <IEnumerable <MatchDto> >(query.AsEnumerable());

            mapper = new MapperConfiguration(cfg => cfg.CreateMap <MatchDto, CouponDto>()
                                             .ForMember(d => d.MatchGuid, opt => opt.MapFrom(s => s.ID))).CreateMapper();

            var list = mapper.Map <IEnumerable <CouponDto> >(mList).ToList();

            if (list.Count > 0)
            {
                // 查找当前用户的比分投注项
                var coupons = _repo.Query <CouponView>(x => x.UserID == AcnID);

                if (coupons.Count > 0)
                {
                    mapper = CouponDto.ConfigMapper().CreateMapper();

                    foreach (var c in coupons)
                    {
                        var i = list.FindIndex(x => x.MatchGuid.Equals(c.MatchGuid));

                        if (i >= 0)
                        {
                            list[i] = mapper.Map <CouponDto>(c);
                        }
                    }
                }
            }

            model.Coupons            = list;
            model.CasinoValidDays    = days;
            model.IsShowSubmitButton = list.Count > 0 && list.Any(x => !x.BetResultHome.HasValue && !x.BetResultAway.HasValue);

            return(View(model));
        }
Esempio n. 23
0
        public void Setup()
        {
            mockUnitOfWork = Substitute.For <IUnitOfWork>();

            var profile       = new MappingProfile();
            var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));

            mapper = new Mapper(configuration);

            uut = new CouponController(mockUnitOfWork, mapper);

            defaultList = new List <Coupon>()
            {
                new Coupon()
                {
                    BarName        = "TestBar",
                    CouponID       = "10 Kr af alt",
                    ExpirationDate = DateTime.Now,
                    Bar            = null,
                },
                new Coupon()
                {
                    BarName        = "TestBar",
                    CouponID       = "5 Kr af alt",
                    ExpirationDate = DateTime.Now,
                    Bar            = null,
                }
            };
            defaultCoupon = defaultList[0];

            // Direct conversion without navigational property
            correctResultList = new List <CouponDto>()
            {
                new CouponDto()
                {
                    BarName        = "TestBar",
                    CouponID       = "10 Kr af alt",
                    ExpirationDate = DateTime.Now,
                },
                new CouponDto()
                {
                    BarName        = "TestBar",
                    CouponID       = "5 Kr af alt",
                    ExpirationDate = DateTime.Now,
                }
            };
            defaultCouponDto = correctResultList[0];
        }
 public IActionResult Post([FromForm] CouponDto dto)
 {
     try
     {
         _createCoupon.Execute(dto);
         return(Ok());
     }
     catch (EntityAlreadyExistsException e)
     {
         return(Conflict(e.Message));
     }
     catch (Exception e)
     {
         return(StatusCode(500, e.Message));
     }
 }
Esempio n. 25
0
        public void Execute(CouponDto request)
        {
            if (Validate(request))
            {
                _context.Coupons.Add(new Coupons
                {
                    Active       = true,
                    DateCreated  = DateTime.Now,
                    Name         = request.Name,
                    Code         = Functions.CreateSha256Hash(request.Code),
                    Discount     = request.Discount,
                    FreeShipping = request.FreeShipping
                });

                _context.SaveChanges();
            }
        }
Esempio n. 26
0
        public async Task <object> Checkout(CheckoutHeaderDto checkoutHeader)
        {
            try
            {
                CartDto cartDto = await _cartRepository.GetCartByUserId(checkoutHeader.UserId);

                if (cartDto == null)
                {
                    return(BadRequest());
                }

                if (!string.IsNullOrEmpty(checkoutHeader.CouponCode))
                {
                    CouponDto coupon = await _couponRepository.GetCoupon(checkoutHeader.CouponCode);

                    if (checkoutHeader.DiscountTotal != coupon.DiscountAmount)
                    {
                        _response.IsSuccess     = false;
                        _response.ErrorMessages = new List <string>()
                        {
                            "Coupon Price has changed, please confirm"
                        };
                        _response.DisplayMessage = "Coupon Price has changed, please confirm";
                        return(_response);
                    }
                }

                checkoutHeader.CartDetails = cartDto.CartDetails;
                //logic to add message to process order.
                await _messageBus.PublishMessage(checkoutHeader, "checkoutqueue");

                ////rabbitMQ
                //_rabbitMQCartMessageSender.SendMessage(checkoutHeader, "checkoutqueue");
                await _cartRepository.ClearCart(checkoutHeader.UserId);
            }
            catch (Exception ex)
            {
                _response.IsSuccess     = false;
                _response.ErrorMessages = new List <string>()
                {
                    ex.ToString()
                };
            }
            return(_response);
        }
Esempio n. 27
0
 public IActionResult AddCoupon([FromBody] CouponDto couponDto)
 {
     try
     {
         var coupon = _mapper.Map <Coupon>(couponDto);
         _unitOfWork.CouponRepository.Add(coupon);
         _unitOfWork.Complete();
         return(Created(string.Format($"api/bars/{coupon.BarName}/coupons/{coupon.CouponID}"), couponDto));
     }
     catch (Exception e)
     {
         if (e.InnerException is SqlException exception && exception.Number == 2627)
         {
             return(BadRequest("Duplicate Key"));
         }
         return(BadRequest());
     }
 }
Esempio n. 28
0
        /// <summary>
        /// 初始化修改数据界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Update(int Id)
        {
            int           adminId = AuthorityHelper.OperatorId ?? 0;
            Administrator admin   = _administratorContract.Administrators.Where(x => x.Id == adminId).FirstOrDefault();
            int           count   = admin.Roles.Where(x => x.Weight == 100).Count();
            bool          isShow  = false;

            if (count > 0)
            {
                isShow = true;
            }
            ViewBag.IsShow = isShow;
            CouponDto dto = _couponContract.Edit(Id);

            admin = _administratorContract.Administrators.Where(x => x.Member.MemberName == dto.UniqueNum).FirstOrDefault();
            string realName = string.Empty;

            if (admin != null)
            {
                realName = admin.Member.RealName;
            }

            int quantity = 0;

            if (dto.PartnerId != null)
            {
                Partner       partner    = _partnerContract.View(dto.PartnerId ?? 0);
                DateTime      current    = DateTime.Now;
                List <Coupon> listCoupon = partner.Coupons.Where(x => x.IsForever == true || (x.StartDate.CompareTo(current) <= 0 && x.EndDate.CompareTo(current) >= 0)).ToList();
                foreach (Coupon coupon in listCoupon)
                {
                    quantity = quantity + coupon.CouponItems.Where(x => x.IsUsed == false && x.MemberId == null).Count();
                }
                if (partner.PartnerLevelId != null)
                {
                    quantity = partner.PartnerLevel.CouponQuantity - quantity;
                }
            }
            ViewBag.Quantity = quantity;
            dto.RealName     = realName;
            return(PartialView(dto));
        }
Esempio n. 29
0
        public void FindById_HasOneCouponWithSameId_returnAllCouponInformation()
        {
            const string couponId = "coupon-1";

            var coupon = CreateCoupon(couponId, CouponType.Percentage, 10);

            var fakeCouponRepository = _mocker.GetMock <ICouponRepository>();

            fakeCouponRepository
            .Setup(x => x.FindById(couponId))
            .Returns(coupon);

            var target = _mocker.CreateInstance <CouponController>();

            var actual = target.FindById(coupon.Id);

            var expected = new CouponDto(couponId, CouponType.Percentage, 10, coupon.Expiration);

            Assert.Equal(expected, actual.Value);
        }
        public void FindById_HasOneCartWithSameId_returnAllShoppingCartsInformation()
        {
            var repository = new CouponRepository(_databaseSettings);

            var coupon = new Coupon
            {
                CouponType = CouponType.Percentage,
                Value      = 10
            };

            repository.Create(coupon);

            var target = new CouponController(new CouponManager(repository, _mapper));

            var actual = target.FindById(coupon.Id);


            var expected = new CouponDto(coupon.Id, CouponType.Percentage, 10, coupon.Expiration);

            Assert.Equal(expected, actual.Value);
        }