public async Task CreateCouponAsync(CreateCouponCodeDTO model, int amount)
        {
            var couponList = new List <CouponCode>();
            var code       = string.Empty;

            for (var i = 0; i < amount; i++)
            {
                code = this.m_generator.Generate();

                while (await this.Repository.ExistAsync(x => x.Code == code))
                {
                    code = this.m_generator.Generate();
                }

                var coupon = new CouponCode {
                    Active     = true,
                    CreatedBy  = this.HttpContext.User.Claims.FirstOrDefault()?.Value,
                    Discount   = model.Discount,
                    ExpiryDate = model.ExpiryDate,
                    Code       = code
                };

                couponList.Add(coupon);
            }

            await this.Repository.Context.CouponCodes.AddRangeAsync(couponList);

            var res = await this.Repository.Context.SaveChangesAsync();

            if (res <= 0)
            {
                throw new Exception("Creating coupon error.");
            }
        }
Exemple #2
0
        public async Task <IActionResult> GenerateCode(int amount = 1)
        {
            try {
                var model = new CreateCouponCodeDTO {
                    Discount   = 10,
                    ExpiryDate = DateTime.UtcNow + TimeSpan.FromDays(10)
                };

                await this.m_couponService.CreateCouponAsync(model, amount);

                return(this.Ok());
            } catch (Exception ex) {
                return(this.BadRequest(ex.Message));
            }
        }