예제 #1
0
 private void CreateCoupons()
 {
     _couponService.AddCoupon(CouponHelper.GetCoupon(CouponTypeEnum.AmountCoupon5For50));
     _couponService.AddCoupon(CouponHelper.GetCoupon(CouponTypeEnum.AmountCoupon50For300));
     _couponService.AddCoupon(CouponHelper.GetCoupon(CouponTypeEnum.RateCoupon10For150));
     _couponService.GetCoupons().Print();
 }
예제 #2
0
        public void TestAddCouponToCart()
        {
            var category = _categoryService.Get("food");

            var product = _productService.Get("Apple", 100, category);
            var cart    = _cartService.Get();

            _cartService.AddItem(cart, product, 5);

            var coupon = _discountService.GetAmountCouponDiscountRule(100, 10);

            _couponService.AddCoupon(cart, coupon);

            Assert.True(cart.Coupon != null);
        }
        public async Task <IActionResult> Create(Coupon coupon)
        {
            if (!ModelState.IsValid)
            {
                return(View(coupon));
            }
            var files = HttpContext.Request.Form.Files;

            if (files.Count > 0)
            {
                byte[] p1 = null;
                using (var fs1 = files[0].OpenReadStream())
                {
                    using (var ms1 = new MemoryStream())
                    {
                        fs1.CopyTo(ms1);
                        p1 = ms1.ToArray();
                    }
                }
                coupon.Picture = p1;
            }
            if (await couponService.AddCoupon(coupon))
            {
                return(RedirectToAction(nameof(Index)));
            }
            return(View(coupon));
        }
예제 #4
0
        public IActionResult SaveCoupon()
        {
            int id = Request.Form["ID"].TryToInt(0);

            if (id > 0)
            {
                var info = _couponService.GetCouponById(id);
                info.Code         = Request.Form["Code"].TryToString();
                info.Password     = Request.Form["Password"].TryToString();
                info.ValidityDate = Request.Form["ValidityDate"].TryToDateTime();
                info.TotalCount   = Request.Form["TotalCount"].TryToInt();
                if (info.TotalCount < info.AvaliableCount)
                {
                    info.AvaliableCount = info.TotalCount;
                }
                info.UpdateTime = DateTime.Now;
                info.BatchId    = Request.Form["BatchId"].TryToInt();
                _couponService.UpdateCoupon(info);
                return(Json(new { code = 1, msg = "OK", id = info.Id }));
            }
            else
            {
                Coupon couponInfo = new Coupon();
                couponInfo.Code = Request.Form["Code"].TryToString();
                var ret = _couponService.CheckIfCouponAlreadyExist(couponInfo.Code);
                if (ret)
                {
                    return(Json(new { code = -1, msg = "券已存在" }));
                }
                couponInfo.Password       = Request.Form["Password"].TryToString();
                couponInfo.ValidityDate   = Request.Form["ValidityDate"].TryToDateTime();
                couponInfo.TotalCount     = Request.Form["TotalCount"].TryToInt();
                couponInfo.AvaliableCount = couponInfo.TotalCount;
                couponInfo.BatchId        = Request.Form["BatchId"].TryToInt();
                couponInfo.CreateTime     = DateTime.Now;
                id = _couponService.AddCoupon(couponInfo);
                if (id > 0)
                {
                    return(Json(new { code = 1, msg = "OK", id = id }));
                }
                else
                {
                    return(Json(new { code = 0, msg = "保存失败" }));
                }
            }
        }
예제 #5
0
        public async Task <IActionResult> Create(Coupon addCoupon)
        {
            // var addCoupon = JsonConvert.DeserializeObject<Coupon>(form["coupon"]);
            string message;

            try
            {
                // TODO: Add insert logic here
                await _service.AddCoupon(addCoupon);

                message = "Success";
            }
            catch (Exception ex)
            {
                message = ex.Message.ToString();
            }
            return(RedirectToAction("Index"));
        }
예제 #6
0
 /// <summary>
 /// 商家添加一个优惠券
 /// </summary>
 /// <param name="info"></param>
 public static void AddCoupon(CouponInfo info)
 {
     _iCouponService.AddCoupon(info);
 }
예제 #7
0
        public async Task   ShoppingCartAsync(ShoppingCartVM cart)
        {
            Check check = new Check()
            {
                Price           = cart.totalprice,
                TotalPrice      = cart.totalprice,
                DateTime        = DateTime.Now,
                PaymentMethodID = cart.paymentmethodId,
                FirstName       = cart.firstname,
                LastName        = cart.lastname
            };

            if (cart.coupon != null)
            {
                var coupon = _context.Coupon.First(a => a.Code == cart.coupon);
                coupon.IsValid = false;
                _context.SaveChanges();
                check.CouponID = coupon.ID;
                check.Discount = coupon.Value;
            }
            _context.Add(check);
            _context.SaveChanges();
            ShoppingCart ShoppingCart = new ShoppingCart()
            {
                TotalPrice = cart.totalprice,
                Date       = DateTime.Now,
                Address    = cart.adress,
                City       = cart.city,
                CustomerID = cart.customerId,
                BranchID   = cart.branchId,
                CheckID    = check.ID
            };

            _context.Add(ShoppingCart);
            _context.SaveChanges();
            foreach (var x in cart.Orders)
            {
                var itemsizeID = _context.Inventory.First(a => a.ID == x.inventoryId && a.BranchID == cart.branchId).ItemSizeID;
                var order      = new Order()
                {
                    Date           = DateTime.Now,
                    UnitCost       = x.unitcost,
                    TotalPrice     = x.totalpriceitem,
                    Quantity       = x.quantity,
                    ItemSizeID     = itemsizeID,
                    ShoppingCartID = ShoppingCart.ID
                };
                var inventory = _context.Inventory.First(a => a.ID == x.inventoryId && a.ItemSizeID == itemsizeID && a.BranchID == cart.branchId);
                inventory.Quantity = inventory.Quantity - x.quantity;
                if (inventory.Quantity <= 0)
                {
                    inventory.IsAvailable = false;
                }
                _context.SaveChanges();
                _context.Add(order);
                _context.SaveChanges();
            }
            var customer = _context.Customer.First(a => a.ID == ShoppingCart.CustomerID);

            customer.TotalSpent += ShoppingCart.TotalPrice;
            if (customer.TotalSpent >= 1000)
            {
                Coupon coupon = new Coupon()
                {
                    Code    = _couponService.GenerateChode(),
                    IsValid = true,
                    Value   = 0.10
                };
                _couponService.AddCoupon(coupon);
                var user = await _userManager.FindByIdAsync(cart.customerId);

                await _emailService.SendEmailAsync(user.Email, "E-commerce", "<h1>Congratulations, you have won a gift bonus</h1>" +
                                                   $"<p>Use the following discount code for your next purchase " + coupon.Code + "</p>");

                customer.TotalSpent = 0;
            }
            _context.SaveChanges();
            var vm = new PaymentVM()
            {
                CardNumber = cart.cardnumber,
                Month      = cart.month,
                Year       = cart.year,
                Cvc        = cart.cvc,
                TotalPrice = cart.totalprice
            };

            if (cart.paymentmethodId == 1)
            {
                await _paymentService.PayAsync(vm);

                if (_context.CreditCard.FirstOrDefault(a => a.CardNumber == vm.CardNumber && a.CustomerID == cart.customerId) == null)
                {
                    var card = new CreditCard()
                    {
                        CardNumber = vm.CardNumber,
                        ExpMonth   = vm.Month,
                        ExpYear    = vm.Year,
                        Cvc        = vm.Cvc,
                        CustomerID = cart.customerId
                    };
                    _context.Add(card);
                    _context.SaveChanges();
                    ShoppingCart.CreditCardID = card.ID;
                    _context.SaveChanges();
                }
                else
                {
                    ShoppingCart.CreditCardID = _context.CreditCard.FirstOrDefault(a => a.CardNumber == vm.CardNumber && a.CustomerID == cart.customerId).ID;
                    _context.SaveChanges();
                }
            }
            var history = new HistoryOfPayments()
            {
                CustomerID = cart.customerId,
                CheckID    = check.ID,
                Date       = DateTime.Now,
                Price      = cart.totalprice
            };

            _context.Add(history);
            _context.SaveChanges();
        }
예제 #8
0
        public JsonResult Edit(CouponInfo info)
        {
            bool flag = false;

            if (info.Id == 0)
            {
                flag = true;
            }
            ICouponService couponService = ServiceHelper.Create <ICouponService>();
            long           shopId        = base.CurrentSellerManager.ShopId;

            info.ShopId = shopId;
            string shopName = ServiceHelper.Create <IShopService>().GetShop(shopId, false).ShopName;

            info.ShopName = shopName;
            if (flag)
            {
                info.CreateTime = DateTime.Now;
                if (info.StartTime >= info.EndTime)
                {
                    Result result = new Result()
                    {
                        success = false,
                        msg     = "开始时间必须小于结束时间"
                    };
                    return(Json(result));
                }
                info.IsSyncWeiXin = 0;
                if (info.FormIsSyncWeiXin)
                {
                    info.IsSyncWeiXin = 1;
                    if (string.IsNullOrWhiteSpace(info.FormWXColor))
                    {
                        Result result1 = new Result()
                        {
                            success = false,
                            msg     = "错误的卡券颜色"
                        };
                        return(Json(result1));
                    }
                    if (string.IsNullOrWhiteSpace(info.FormWXCTit))
                    {
                        Result result2 = new Result()
                        {
                            success = false,
                            msg     = "请填写卡券标题"
                        };
                        return(Json(result2));
                    }
                    if (!WXCardLogInfo.WXCardColors.Contains(info.FormWXColor))
                    {
                        Result result3 = new Result()
                        {
                            success = false,
                            msg     = "错误的卡券颜色"
                        };
                        return(Json(result3));
                    }
                    Encoding @default = Encoding.Default;
                    if (@default.GetBytes(info.FormWXCTit).Count() > 18)
                    {
                        Result result4 = new Result()
                        {
                            success = false,
                            msg     = "卡券标题不得超过9个汉字"
                        };
                        return(Json(result4));
                    }
                    if (!string.IsNullOrWhiteSpace(info.FormWXCSubTit) && @default.GetBytes(info.FormWXCSubTit).Count() > 36)
                    {
                        Result result5 = new Result()
                        {
                            success = false,
                            msg     = "卡券副标题不得超过18个汉字"
                        };
                        return(Json(result5));
                    }
                }
            }
            string item = base.Request.Form["chkShow"];

            info.CanVshopIndex = base.CurrentSellerManager.VShopId > 0;
            switch (info.ReceiveType)
            {
            case CouponInfo.CouponReceiveType.IntegralExchange:
            {
                if (!couponService.CanAddIntegralCoupon(shopId, info.Id))
                {
                    Result result6 = new Result()
                    {
                        success = false,
                        msg     = "当前己有积分优惠券,每商家只可以推广一张积分优惠券!"
                    };
                    return(Json(result6));
                }
                info.Himall_CouponSetting.Clear();
                if (!info.EndIntegralExchange.HasValue)
                {
                    Result result7 = new Result()
                    {
                        success = false,
                        msg     = "错误的兑换截止时间"
                    };
                    return(Json(result7));
                }
                DateTime?endIntegralExchange = info.EndIntegralExchange;
                DateTime date = info.EndTime.AddDays(1).Date;
                if ((endIntegralExchange.HasValue ? endIntegralExchange.GetValueOrDefault() > date : false))
                {
                    Result result8 = new Result()
                    {
                        success = false,
                        msg     = "错误的兑换截止时间"
                    };
                    return(Json(result8));
                }
                if (info.NeedIntegral >= 10)
                {
                    break;
                }
                Result result9 = new Result()
                {
                    success = false,
                    msg     = "积分最少10分起兑"
                };
                return(Json(result9));
            }

            case CouponInfo.CouponReceiveType.DirectHair:
            {
                info.Himall_CouponSetting.Clear();
                break;
            }

            default:
            {
                if (string.IsNullOrEmpty(item))
                {
                    Result result10 = new Result()
                    {
                        success = false,
                        msg     = "必须选择一个推广类型"
                    };
                    return(Json(result10));
                }
                info.Himall_CouponSetting.Clear();
                string[] strArrays = item.Split(new char[] { ',' });
                if (strArrays.Contains <string>("WAP") && info.CanVshopIndex)
                {
                    ICollection <CouponSettingInfo> himallCouponSetting = info.Himall_CouponSetting;
                    CouponSettingInfo couponSettingInfo = new CouponSettingInfo()
                    {
                        Display  = new int?(1),
                        PlatForm = PlatformType.Wap
                    };
                    himallCouponSetting.Add(couponSettingInfo);
                }
                if (!strArrays.Contains <string>("PC"))
                {
                    break;
                }
                ICollection <CouponSettingInfo> couponSettingInfos = info.Himall_CouponSetting;
                CouponSettingInfo couponSettingInfo1 = new CouponSettingInfo()
                {
                    Display  = new int?(1),
                    PlatForm = PlatformType.PC
                };
                couponSettingInfos.Add(couponSettingInfo1);
                break;
            }
            }
            Server.MapPath(string.Format("/Storage/Shop/{0}/Coupon/{1}", shopId, info.Id));
            if (!flag)
            {
                couponService.EditCoupon(info);
            }
            else
            {
                couponService.AddCoupon(info);
            }
            return(Json(new { success = true }));
        }
예제 #9
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterVM model)
        {
            if (model == null)
            {
                throw new NullReferenceException("Register model is null");
            }
            if (ModelState.IsValid)
            {
                var role = _roleManager.FindByIdAsync("4").Result;
                var user = new Account
                {
                    UserName    = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    PhoneNumber = model.PhoneNumber,
                    Email       = model.Email,
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var roleResult = await _userManager.AddToRoleAsync(user, role.Name);

                    if (!roleResult.Succeeded)
                    {
                        throw new NullReferenceException("Role is not good");
                    }
                    Customer customer = new Customer();
                    customer.Account = user;
                    _customerService.AddCustomer(customer);
                    var confirmEmailToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var encodedEmailToken = Encoding.UTF8.GetBytes(confirmEmailToken);
                    var validEmailToken   = WebEncoders.Base64UrlEncode(encodedEmailToken);

                    string url = $"https://www.api.customer.app.fit.ba/account/confirmemail?userid={user.Id}&token={validEmailToken}";

                    await _emailService.SendEmailAsync(user.Email, "Confirm your email", $"<h1>Hi,</h1>" +
                                                       $"<p>Please confirm your email by <a href='{url}'>Clicking here</a></p>");

                    if (_friendService.CheckFriend(user.Email))
                    {
                        var CustomerID = _friendService.GetUserID(user.Email);
                        var customer1  = await _userManager.FindByIdAsync(CustomerID);

                        Coupon coupon = new Coupon()
                        {
                            Code    = _couponService.GenerateChode(),
                            IsValid = true,
                            Value   = 0.10
                        };
                        _couponService.AddCoupon(coupon);

                        await _emailService.SendEmailAsync(customer1.Email, "E-commerce", "<h1>Your friend accepted your invitation</h1>" +
                                                           $"<p>Use the following discount code for your next purchase " + coupon.Code + "</p>");
                    }

                    return(Ok(new { message = "User created successfully!" })); // Status Code: 200
                }


                return(BadRequest(result));
            }

            return(BadRequest("Some properties are not valid")); // Status code: 400
        }