Beispiel #1
0
        public async Task <ActionResult> Stock(string prizeName, int count)
        {
            var prize = AllPrizes.FirstOrDefault(p => p.PrizeName == prizeName);

            if (prize == null || count > 100)
            {
                return(BadRequest());
            }
            string item = prize.RedeemItemName;
            var    kind = UserVoucher.Kind.Prize;

            if (prize.IsVoucher)
            {
                kind = UserVoucher.Kind.LuckyPoint;
            }
            for (int i = 0; i < count; i++)
            {
                var voucher = new UserVoucher
                {
                    IssueTime   = DateTime.Now,
                    RedeemItem  = item,
                    VoucherID   = Guid.NewGuid(),
                    VoucherKind = kind,
                };
                _udb.UserVouchers.Add(voucher);
            }
            await _udb.SaveChangesAsync();

            return(Ok());
        }
Beispiel #2
0
        private async Task <ActionResult> SpinCAsync()
        {
            if (_wheelConfig.Value.WheelCLPCost <= 0 || _wheelConfig.Value.WheelCPrizes.Count == 0)
            {
                return(BadRequest());
            }
            var user = await _userManager.GetUserAsync(User);

            var success = await TrySpendLPAsync(user, _wheelConfig.Value.WheelCLPCost);

            if (!success)
            {
                return(BadRequest(new { err = "not enough lp" }));
            }
            var prize = DrawPrize(_wheelConfig.Value.WheelCPrizes);
            var v     = new UserVoucher
            {
                VoucherID   = Guid.NewGuid(),
                VoucherKind = UserVoucher.Kind.WheelC,
                IssueTime   = DateTime.Now,
                UserID      = user.Id,
                UseTime     = DateTime.Now,
                RedeemItem  = prize.PrizeName,
            };

            _udb.UserVouchers.Add(v);
            SpinWheelResult result = await ProcessPrizeAsync(user, prize);

            await _udb.SaveChangesAsync();

            return(Json(result));
        }
Beispiel #3
0
        public async Task <ActionResult> RedeemCoupon(int spentPoints)
        {
            var coupon = _wheelConfig.Value.CouponPrizes.FirstOrDefault(v => v.PrizeLPValue == spentPoints);

            if (coupon == null)
            {
                return(BadRequest());
            }
            var user = await _userManager.GetUserAsync(User);

            var success = await TrySpendLPAsync(user, coupon.PrizeLPValue);

            if (!success)
            {
                return(BadRequest(new { err = "not enough lp" }));
            }
            var v = new UserVoucher
            {
                IssueTime   = DateTime.Now,
                UserID      = user.Id,
                VoucherID   = Guid.NewGuid(),
                RedeemItem  = coupon.PrizeName,
                VoucherKind = UserVoucher.Kind.Coupon,
            };

            _udb.UserVouchers.Add(v);
            await _udb.SaveChangesAsync();

            return(Json(new SpinWheelResult
            {
                Prize = coupon,
                Voucher = Vouchers.FromUserVoucher(v, User.Identity.Name),
            }));
        }
Beispiel #4
0
        public Kv CheckoutAccount()
        {
            Kv          kv          = new Kv();
            string      VoucherNo   = Kv.Get("VoucherNo");
            UserVoucher UserVoucher = UserVoucher.CheckoutAccount(base.Kv.Cxt, VoucherNo);

            if (UserVoucher != null)
            {
                User User = User.GetUserByID(base.Kv.Cxt, UserVoucher.UserID);
                kv.Set("Payment", User.Fini);
                kv.Set("ExpiryDate", UserVoucher.ExpiryDate);
                if (UserVoucher.IsUsed == false)
                {
                    kv.Set("Message", "0");
                }
                else
                {
                    kv.Set("Message", "1");
                }
            }
            else
            {
                kv.Set("Message", "2");
            }
            return(kv);
        }
 public void Add(UserVoucher uservoucher)
 {
     if (uservoucher == null)
     {
         return;
     }
     DB.UserVouchers.Add(uservoucher);
     DB.SaveChanges();
 }
Beispiel #6
0
 static public Vouchers FromUserVoucher(UserVoucher userVoucher, string userName)
 {
     return(new Vouchers
     {
         VoucherID = userVoucher.VoucherID.ToString(),
         IssueTime = userVoucher.IssueTime,
         UseTime = userVoucher.UseTime,
         RedeemItem = userVoucher.RedeemItem,
         Kind = userVoucher.VoucherKind,
         UserName = userName,
     });
 }
        public void Update(UserVoucher uservoucher)
        {
            if (uservoucher == null)
            {
                return;
            }
            var usrvcr = DB.UserVouchers.FirstOrDefault(u => u.ID == uservoucher.ID);

            if (usrvcr == null)
            {
                return;
            }
            DB.Entry(usrvcr).CurrentValues.SetValues(uservoucher);
            DB.SaveChanges();
        }
Beispiel #8
0
        public async Task <ActionResult> Exchange(string voucherId)
        {
            if (!Guid.TryParse(voucherId, out Guid guid))
            {
                return(BadRequest());
            }
            var v = await _udb.UserVouchers.Where(v => v.User.UserName == User.Identity.Name && v.VoucherID == guid).FirstOrDefaultAsync();

            if (v == null || v.UseTime != null || (v.VoucherKind != UserVoucher.Kind.Prize && v.VoucherKind != UserVoucher.Kind.Coupon))
            {
                return(BadRequest());
            }
            var prizeName = new Regex("(.+)").Replace(v.RedeemItem, "");
            var item      = AllPrizes.FirstOrDefault(p => p.RedeemItemName == prizeName);

            if (item == null || item.PrizeLPValue == 0)
            {
                return(BadRequest());
            }
            v.RedeemItem = string.Format("{0}(已折换)", prizeName);
            v.UseTime    = DateTime.Now;
            var subVoucher = new UserVoucher
            {
                VoucherID   = Guid.NewGuid(),
                UserID      = v.UserID,
                IssueTime   = DateTime.Now,
                VoucherKind = UserVoucher.Kind.LuckyPoint,
                RedeemItem  = string.Format("{0}/{0}", item.PrizeLPValue),
            };

            if (v.VoucherKind == UserVoucher.Kind.Prize)
            {
                var returnedVoucher = new UserVoucher
                {
                    VoucherID   = Guid.NewGuid(),
                    IssueTime   = DateTime.Now,
                    RedeemItem  = item.PrizeName,
                    VoucherKind = UserVoucher.Kind.Prize,
                };
                _udb.UserVouchers.Add(returnedVoucher);
            }
            _udb.UserVouchers.Add(subVoucher);
            await _udb.SaveChangesAsync();

            return(Json(Vouchers.FromUserVoucher(subVoucher, User.Identity.Name)));
        }
Beispiel #9
0
        public IResponse <NoValue> AddUserVoucher(UserVoucherCreateModel model)
        {
            Logger.Message($"AddUserVoucher(UserID: {model.UserID}, VoucherID: {model.VoucherID}, OfferID: {model.OfferID})");

            var result  = new Response <NoValue>();
            var voucher = _uow.Vouchers.Get(model.VoucherID);
            var user    = _uow.Users.Get(model.UserID);

            if (voucher.PointCost > user.PointBalance)
            {
                result.Message = Message.NotEnoughtPoints;
                result.Status  = Status.Error;
                Logger.Error(Message.NotEnoughtPoints);
            }
            else
            {
                try
                {
                    var date = DateTime.Compare(voucher.ExpirationDate, voucher.Offer.DateTo);

                    var userVoucher = new UserVoucher
                    {
                        Code       = user.UserID + DateTime.Now.ToString("yyyyMMddHHmmss") + voucher.Code,
                        OfferID    = model.OfferID,
                        VoucherID  = model.VoucherID,
                        UserID     = model.UserID,
                        ValidFrom  = voucher.Offer.DateFrom,
                        ValidTo    = (date < 1) ? voucher.ExpirationDate : voucher.Offer.DateTo,
                        RedeemDate = DateTime.UtcNow,
                        Valid      = true
                    };

                    _uow.UserVouchers.Add(userVoucher);
                    user.PointBalance = user.PointBalance - voucher.PointCost;
                    _uow.Complete();
                    result.Status = Status.Success;
                }
                catch (Exception ex)
                {
                    result.Message = Message.SomethingWrongError;
                    result.Status  = Status.Error;
                    Logger.ErrorWithException(ex);
                }
            }
            return(result);
        }
        private void btnSubmitKey_Click(object sender, EventArgs e)
        {
            DataSet ds = SocketClient.CheckoutAccount(txtVoucherNo.Text);

            MsgE msgID = UserVoucher.GetMessage(ds);

            if (msgID != MsgE.VoucherInvalid)
            {
                lblcp.Text       = ds.Tables[0].Rows[2][1].ToString();
                lblExpDate2.Text = ds.Tables[0].Rows[3][1].ToString();
                if (msgID == MsgE.CreditCardValid)
                {
                    MessageForm.Show(this.ParentForm, msgID);
                    this.ParentForm.Close();
                }
            }
            else
            {
                MessageForm.Show(this.ParentForm, msgID);
            }
        }
Beispiel #11
0
        private async Task <ActionResult> SpinAAsync()
        {
            if (_wheelConfig.Value.WheelACost <= 0 || _wheelConfig.Value.WheelAPrizes.Count == 0)
            {
                return(BadRequest());
            }
            var user = await _userManager.GetUserAsync(User);

            var todayDrawCount = await _udb.UserVouchers
                                 .Where(v => v.UserID == user.Id && v.VoucherKind == UserVoucher.Kind.WheelA && DbFunctions.DiffDays(v.IssueTime, DateTime.Today) == 0)
                                 .CountAsync();

            if (todayDrawCount >= 3 && !User.IsInRole("AdManager") && !User.IsInRole("Administrator"))
            {
                return(BadRequest(new { drawCount = todayDrawCount }));
            }
            if (user.Points < _wheelConfig.Value.WheelACost)
            {
                return(BadRequest(new { points = user.Points }));
            }
            _expUtil.AddPoint(user, -_wheelConfig.Value.WheelACost);
            var prize = DrawPrize(_wheelConfig.Value.WheelAPrizes);
            var v     = new UserVoucher
            {
                VoucherID   = Guid.NewGuid(),
                VoucherKind = UserVoucher.Kind.WheelA,
                IssueTime   = DateTime.Now,
                UserID      = user.Id,
                UseTime     = DateTime.Now,
                RedeemItem  = prize.PrizeName,
            };

            _udb.UserVouchers.Add(v);
            SpinWheelResult result = await ProcessPrizeAsync(user, prize);

            await _udb.SaveChangesAsync();

            return(Json(result));
        }
Beispiel #12
0
        public async Task <ActionResult> RedeemCeiling()
        {
            if (_wheelConfig.Value.CeilingCost <= 0)
            {
                return(BadRequest());
            }
            var user = await _userManager.GetUserAsync(User);

            var ceilCount = await _udb.UserVouchers
                            .CountAsync(v => v.UserID == user.Id && v.VoucherKind == UserVoucher.Kind.CeilingPrize);

            var lps = await _udb.UserVouchers
                      .Where(v => v.UserID == user.Id && v.VoucherKind == UserVoucher.Kind.LuckyPoint).ToListAsync();

            var spentLp = lps.Aggregate(0, (sum, v) =>
            {
                var tokens     = v.RedeemItem.Split('/');
                int curValue   = int.Parse(tokens[0]);
                int totalValue = int.Parse(tokens[1]);
                return(sum + totalValue - curValue);
            });

            if ((ceilCount + 1) * _wheelConfig.Value.CeilingCost > spentLp)
            {
                return(BadRequest());
            }
            var v = new UserVoucher
            {
                IssueTime   = DateTime.Now,
                UserID      = user.Id,
                VoucherID   = Guid.NewGuid(),
                VoucherKind = UserVoucher.Kind.CeilingPrize,
            };

            _udb.UserVouchers.Add(v);
            await _udb.SaveChangesAsync();

            return(Json(Vouchers.FromUserVoucher(v, User.Identity.Name)));
        }
Beispiel #13
0
        public async Task<IActionResult> Order(CheckOutViewModel model)
        {

            if (ModelState.IsValid)
            {
                decimal SumPriceCart = 0;

                //lấy ra danh sách đơn hàng
                var item = GetCartItems();
                // ngày giao hàng
                model.Order.TransportDate = DateTime.TryParse(model.Order.TransportDate.ToString(), new CultureInfo("vi-VN"), DateTimeStyles.None, out var tDate) ? tDate : DateTime.Now;
                _unitOfWork.OrderRepository.Insert(model.Order);
                await _unitOfWork.Save();
                model.Order.MaDonHang = DateTime.Now.ToString("yyyyMMddHHmm") + "C" + model.Order.Id;
                foreach (var odetails in from cart1 in item
                                         select new OrderDetail
                                         {
                                             OrderId = model.Order.Id,
                                             ProductId = cart1.ProductID,
                                             Quantity = cart1.Count,
                                             Price = cart1.Price,
                                             Color = cart1.Color == null ? "null" : cart1.Color,
                                             Size = cart1.Size == null ? "null" : cart1.Size
                                         })
                {
                    _unitOfWork.OrderDetailRepository.Insert(odetails);
                }
                await _unitOfWork.Save();

                var typepay = "Thanh toán khi nhận hàng";
                switch (model.Order.TypePay)
                {
                    case 1:
                        typepay = "Tiền mặt";
                        break;
                    case 2:
                        typepay = "Chuyển khoản";
                        break;
                    case 3:
                        typepay = "Hình thức khác";
                        break;
                }

                var giaohang = "Đến địa chỉ người nhận";
                switch (model.Order.Transport)
                {
                    case 3:
                        giaohang = "Khách đến nhận hàng";
                        break;
                    case 1:
                        giaohang = "Qua bưu điện";
                        break;
                    case 4:
                        giaohang = "Hình thức khác";
                        break;
                }
                var tongtien = 0m;
                StringBuilder sb = new StringBuilder();
                sb.Append("<p>Mã đơn hàng: <strong>" + model.Order.MaDonHang + "</strong></p>");
                sb.Append("<p>Họ và tên: <strong>" + model.Order.Fullname + "</strong></p>");
                sb.Append("<p>Địa chỉ: <strong>" + model.Order.Address + "</strong></p>");
                sb.Append("<p>Email: <strong>" + model.Order.Email + "</strong></p>");
                sb.Append("<p>Điện thoại: <strong>" + model.Order.Mobile + "</strong></p>");
                sb.Append("<p>Yêu cầu thêm: <strong>" + model.Order.Body + "</strong></p>");
                sb.Append("<p>Ngày đặt hàng: <strong>" + model.Order.CreateDate.ToString("dd-MM-yyyy HH:mm") + "</strong></p>");
                //sb.Append("<p>Ngày giao hàng: <strong>" + model.Order.TransportDate.ToString("dd-MM-yyyy") + "</strong></p>");
                sb.Append("<p>Hình thức giao hàng: <strong>" + giaohang + "</strong></p>");
                sb.Append("<p>Hình thức thanh toán: <strong>" + typepay + "</strong></p>");
                sb.Append("<p>Thông tin đơn hàng</p>");
                sb.Append("<table border='1' cellpadding='10' style='border:1px #ccc solid;border-collapse: collapse'>" +
                      "<tr>" +
                      "<th>Ảnh sản phẩm</th>" +
                      "<th>Tên sản phẩm</th>" +
                      "<th>Số lượng</th>" +
                      "<th>Giá tiền</th>" +
                      "<th>Thành tiền</th>" +
                      "</tr>");
                foreach (var odetails in model.Order.OrderDetails)
                {
                    var thanhtien = Convert.ToDecimal(odetails.Price * odetails.Quantity);
                    tongtien += thanhtien;

                    var img = "NO PICTURE";
                    if (odetails.Product.Image != null)
                    {
                        img = "<img src='http://" + Request.Host.Value + "/" + odetails.Product.Image.Split(',')[0] + "' width='100' height='100' />";
                    }
                    string size, color = "";
                    color = odetails.Color.Equals("null") ? "" : "-Color:" + odetails.Color + "";
                    size = odetails.Size.Equals("null") ? "" : "-Size:" + odetails.Size + "";
                    sb.Append("<tr>" +
                          "<td>" + img + "</td>" +
                          "<td>" + "" + odetails.Product.Name + "" + color + "" + size + "");

                    sb.Append("</td>" +
                          "<td style='text-align:center'>" + odetails.Quantity + "</td>" +
                          "<td style='text-align:center'>" + Convert.ToDecimal(odetails.Price).ToString("N0") + "</td>" +
                          "<td style='text-align:center'>" + thanhtien.ToString("N0") + " đ</td>" +
                          "</tr>");
                }
                string VoucherCode = "";
                if (_httpContextAccessor.HttpContext.Session.GetString("Voucher").Length > 0)
                {
                    SumPriceCart = decimal.Parse(_httpContextAccessor.HttpContext.Session.GetString("Voucher"));
                }
                else
                    SumPriceCart = tongtien < 1000000 ? tongtien + 30000 : tongtien;
                if (_httpContextAccessor.HttpContext.Session.GetString("VoucherCode").Length > 0)
                {
                    VoucherCode = _httpContextAccessor.HttpContext.Session.GetString("VoucherCode");
                    var user = new UserVoucher
                    {
                        MaDonHang = model.Order.MaDonHang,
                        SumHD = SumPriceCart,
                        Code = VoucherCode
                    };
                    _unitOfWork.UserVoucherRepository.Insert(user);
                    await _unitOfWork.Save();
                    _httpContextAccessor.HttpContext.Session.SetString("VoucherCode", "");
                    var voucher = _unitOfWork.VoucherRepository.Get(x => x.Code.Equals(VoucherCode)).FirstOrDefault();
                    if (voucher != null)
                    {
                        voucher.SumUse = voucher.SumUse - 1;
                        _unitOfWork.VoucherRepository.Update(voucher);
                        await _unitOfWork.Save();
                    }
                }
                sb.Append("<tr><td colspan='5' style='text-align:right'><strong>Tổng tiền (đã bao gồm cả phí ship và Voucher (Nếu có)): " + SumPriceCart.ToString("N0") + " đ</strong></td></tr>");
                sb.Append("</table>");
                sb.Append("<p>Cảm ơn bạn đã tin tưởng và mua hàng của chúng tôi.</p>");
                await _mailer.SendEmailSync(model.Order.Email, "[" + model.Order.MaDonHang + "] Đơn đặt hàng từ website ShopAsp.Net", sb.ToString());
                if (model.Order.TypePay == 2)
                    return RedirectToAction("ShopOnline", new { orderID = model.Order.MaDonHang, Price = SumPriceCart });
                return RedirectToAction("CheckOutComplete", new { orderId = model.Order.MaDonHang });
            }
            model.Carts = GetCartItems();
            if (_httpContextAccessor.HttpContext.Session.GetString("Voucher").Length > 0)
            {
                model.CartTotal = decimal.Parse(_httpContextAccessor.HttpContext.Session.GetString("Voucher"));
                ViewBag.session = "ha";
            }
            else
                model.CartTotal = GetTotal() < 1000000 ? (GetTotal() + 30000) : GetTotal();
            return View(model);
        }
Beispiel #14
0
        private async Task <SpinWheelResult> ProcessPrizeAsync(UserProfile user, WheelPrize prize)
        {
            SpinWheelResult result = new SpinWheelResult
            {
                Prize = new WheelPrize {
                    PrizeName    = prize.PrizeName,
                    PrizePic     = prize.PrizePic,
                    PrizeLPValue = prize.PrizeLPValue,
                    IsVoucher    = prize.IsVoucher,
                    IsRealItem   = prize.IsRealItem,
                    IsCoupon     = prize.IsCoupon,
                    ItemLink     = prize.ItemLink,
                },
            };

            if (prize.IsRealItem)
            {
                await _semaphoreSlim.WaitAsync();

                try
                {
                    if (await _udb.UserVouchers.AnyAsync(v => v.RedeemItem == prize.PrizeName && v.VoucherKind == UserVoucher.Kind.Prize && v.UserID == user.Id))
                    {
                        result.Prize.PrizeName = string.Format("{0}(已折换)", prize.PrizeName);
                        var subVoucher = new UserVoucher
                        {
                            VoucherID   = Guid.NewGuid(),
                            UserID      = user.Id,
                            IssueTime   = DateTime.Now,
                            VoucherKind = UserVoucher.Kind.LuckyPoint,
                            RedeemItem  = string.Format("{0}/{0}", prize.PrizeLPValue),
                        };
                        _udb.UserVouchers.Add(subVoucher);
                        result.Voucher = Vouchers.FromUserVoucher(subVoucher, user.UserName);
                    }
                    else
                    {
                        var stock = await _udb.UserVouchers
                                    .Where(v => v.RedeemItem == prize.PrizeName && v.VoucherKind == UserVoucher.Kind.Prize && v.UserID == null)
                                    .FirstOrDefaultAsync();

                        if (stock != null)
                        {
                            stock.UserID    = user.Id;
                            stock.IssueTime = DateTime.Now;
                            result.Voucher  = Vouchers.FromUserVoucher(stock, user.UserName);
                        }
                        else
                        {
                            result.Prize.PrizeName = string.Format("{0}(售罄)", prize.PrizeName);
                            var subVoucher = new UserVoucher
                            {
                                VoucherID   = Guid.NewGuid(),
                                UserID      = user.Id,
                                IssueTime   = DateTime.Now,
                                VoucherKind = UserVoucher.Kind.LuckyPoint,
                                RedeemItem  = string.Format("{0}/{0}", prize.PrizeLPValue),
                            };
                            _udb.UserVouchers.Add(subVoucher);
                            result.Voucher = Vouchers.FromUserVoucher(subVoucher, user.UserName);
                        }
                    }
                    await _udb.SaveChangesAsync();
                }
                finally
                {
                    _semaphoreSlim.Release();
                }
            }
            else if (prize.IsCoupon)
            {
                var subVoucher = new UserVoucher
                {
                    VoucherID   = Guid.NewGuid(),
                    UserID      = user.Id,
                    IssueTime   = DateTime.Now,
                    VoucherKind = UserVoucher.Kind.Coupon,
                    RedeemItem  = prize.PrizeName,
                };
                _udb.UserVouchers.Add(subVoucher);
                result.Voucher = Vouchers.FromUserVoucher(subVoucher, user.UserName);
            }
            else if (prize.IsVoucher)
            {
                var subVoucher = new UserVoucher
                {
                    VoucherID   = Guid.NewGuid(),
                    UserID      = user.Id,
                    IssueTime   = DateTime.Now,
                    VoucherKind = UserVoucher.Kind.LuckyPoint,
                    RedeemItem  = string.Format("{0}/{0}", prize.PrizeLPValue),
                };
                _udb.UserVouchers.Add(subVoucher);
                result.Voucher = Vouchers.FromUserVoucher(subVoucher, user.UserName);
            }
            return(result);
        }