// GET: UtilityBill/Details/5
 public ActionResult Details(string id)
 {
     var billInfo = MachineManager.GetMachineInstance().InvokeQueryBill(id);
     if (billInfo == null)
     {
         TempData["message"] = "Can not find any bill with number " + id;
         return RedirectToAction("Index");
     }
     else
     {
         BillViewModel model = new BillViewModel();
         model.BillNumber = id;
         model.Amount = billInfo.TotalAmount;
         model.CompanyCode = billInfo.CompanyCode;
         model.CustomerName = billInfo.CustomerName;
         model.DueDate = billInfo.DueDate;
         TempData["BillId"] = id;
         return View(model);
     }
 }
 public static Bill AddModel(this BillViewModel addModel)
 {
     return(Mapper.Map <Bill>(addModel));
 }
Example #3
0
 public async Task <bool> PaidBill([FromBody] BillViewModel billViewModel)
 {
     return(await _billsInqueryAppService.SetBillPaidForRolloutTeam(billViewModel));
 }
Example #4
0
        public async Task <IActionResult> Checkout(CheckoutViewModel model)
        {
            var session = HttpContext.Session.Get <List <ShoppingCartViewModel> >(CommonConstants.CartSession);

            if (ModelState.IsValid)
            {
                if (session != null)
                {
                    var details = new List <BillDetailViewModel>();

                    decimal totalMoney = 0;
                    bool    canBuy     = true;
                    foreach (var item in session)
                    {
                        totalMoney += item.Price * item.Quantity;

                        details.Add(new BillDetailViewModel()
                        {
                            Product   = item.Product,
                            Price     = item.Price,
                            ColorId   = item.Color.Id,
                            SizeId    = item.Size.Id,
                            Quantity  = item.Quantity,
                            ProductId = item.Product.Id
                        });

                        canBuy = await _quantityService.SellProduct(item.Product.Id, item.Quantity);

                        if (!canBuy)
                        {
                            break;
                        }
                    }

                    if (canBuy)
                    {
                        var billViewModel = new BillViewModel()
                        {
                            CustomerMobile  = model.CustomerMobile,
                            BillStatus      = BillStatus.New,
                            CustomerAddress = model.CustomerAddress,
                            CustomerName    = model.CustomerName,
                            CustomerMessage = model.CustomerMessage,
                            BillDetails     = details,
                            DateCreated     = DateTime.Now,
                            PaymentMethod   = model.PaymentMethod
                        };
                        if (User.Identity.IsAuthenticated)
                        {
                            billViewModel.CustomerId = Guid.Parse(User.GetSpecificDefault("UserId"));
                        }
                        var dataReturn = await _billService.Create(billViewModel);

                        _billService.Save();
                        HttpContext.Session.Set(CommonConstants.BillSession, dataReturn);
                        string vnp_Returnurl         = _configuration["VNPAY:vnp_Returnurl"];  //URL nhan ket qua tra ve
                        string vnp_Url               = _configuration["VNPAY:vnp_Url"];        //URL thanh toan cua VNPAY
                        string vnp_TmnCode           = _configuration["VNPAY:vnp_TmnCode"];    //Ma website
                        string vnp_HashSecret        = _configuration["VNPAY:vnp_HashSecret"]; //Chuoi bi mat
                        HttpContextAccessor accessor = new HttpContextAccessor();
                        VnPayLibrary        vnpay    = new VnPayLibrary(accessor);
                        vnpay.AddRequestData("vnp_Version", "2.0.0");
                        vnpay.AddRequestData("vnp_Command", "pay");
                        vnpay.AddRequestData("vnp_TmnCode", vnp_TmnCode);
                        vnpay.AddRequestData("vnp_Locale", "vn");
                        vnpay.AddRequestData("vnp_CurrCode", "VND");
                        vnpay.AddRequestData("vnp_TxnRef", DateTime.Now.Ticks.ToString());
                        vnpay.AddRequestData("vnp_OrderInfo", "Noi dung thanh toan:20190421030204");
                        vnpay.AddRequestData("vnp_OrderType", "topup"); //default value: other
                        vnpay.AddRequestData("vnp_Amount", ((int)totalMoney * 100).ToString());
                        vnpay.AddRequestData("vnp_ReturnUrl", vnp_Returnurl);
                        vnpay.AddRequestData("vnp_IpAddr", vnpay.GetIpAddress());
                        vnpay.AddRequestData("vnp_CreateDate", DateTime.Now.ToString("yyyyMMddHHmmss"));
                        vnpay.AddRequestData("vnp_BankCode", "NCB");
                        string paymentUrl = vnpay.CreateRequestUrl(vnp_Url, vnp_HashSecret);
                        return(new OkObjectResult(new
                        {
                            status = true,
                            url = paymentUrl
                        }));
                    }

                    return(new OkObjectResult(new
                    {
                        status = false,
                        message = "Hiện số lượng sản phẩm không đủ."
                    }));
                }

                model.Carts = session;
                HttpContext.Session.Set(CommonConstants.CartSession, new List <ShoppingCartViewModel>());
                return(View(model));
            }
            return(new OkObjectResult(""));
        }
        public GenericResult Create(AnnouncementViewModel announcementViewModel, List <AnnouncementUserViewModel> announcementUsers, BillViewModel billViewModel)
        {
            try
            {
                var order        = _mapper.Map <BillViewModel, Bill>(billViewModel);
                var orderDetails = _mapper.Map <List <BillDetailViewModel>, List <BillDetail> >(billViewModel.BillDetails);
                foreach (var productDetail in orderDetails)
                {
                    var product = _productRepository.FindById(productDetail.ProductId);
                    productDetail.Price = product.Price;
                }

                order.Total       = orderDetails.Sum(x => x.Price * x.Quantity);
                order.BillDetails = orderDetails;
                _orderRepository.Add(order);
                // Real Time
                var announcement = _mapper.Map <AnnouncementViewModel, Announcement>(announcementViewModel);
                _announceRepository.Add(announcement);
                foreach (var announcementUserViewModel in announcementUsers)
                {
                    _announceUserRepository.Add(_mapper.Map <AnnouncementUserViewModel, AnnouncementUser>(announcementUserViewModel));
                }
                return(new GenericResult(true, "Add Successful", "Successful"));
            }
            catch (Exception)
            {
                return(new GenericResult(false, "Add Failed", "Error"));
            }
        }
Example #6
0
        /// <summary>
        /// 加入 小計&總計
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public List <BillViewModel> SetBillTakeOutViewModelGroup(List <BillViewModel> data)
        {
            var result = new List <BillViewModel>();

            if (data.Any())
            {
                int _vCheckTotalNum    = 0;
                int _intReMainTotalNum = 0;
                int rownum             = 1;
                data = data.OrderBy(x => x.vIssuingBank)
                       .ThenBy(x => x.vCheckType)
                       .ToList();

                data.ForEach(x =>
                {
                    //x.vRowNum = rownum.ToString();
                    if (x.vStatus == Ref.AccessInventoryType._3.GetDescription())
                    {
                        x.vReMainTotalNum   = x.vCheckTotalNum;
                        _intReMainTotalNum += TypeTransfer.stringToInt(x.vReMainTotalNum);
                        x.vCheckTotalNum    = "";
                    }
                    else
                    {
                        var _vReMainTotalNum =
                            (x.vStatus == Ref.AccessInventoryType._1.GetDescription() || !x.vTakeOutE.IsNullOrWhiteSpace()) ?
                            TypeTransfer.stringToInt(x.vCheckTotalNum) - TypeTransfer.stringToInt(x.vTakeOutTotalNum) : 0;
                        _intReMainTotalNum += _vReMainTotalNum;
                        x.vReMainTotalNum   = _vReMainTotalNum == 0 ? "" : _vReMainTotalNum.ToString();
                    }

                    //rownum += 1;
                });

                data.GroupBy(x => new { x.vIssuingBank, x.vCheckType })
                .OrderBy(x => x.Key.vIssuingBank)
                .ThenBy(x => x.Key.vCheckType)
                .ToList()
                .ForEach(x =>
                {
                    rownum = 1;
                    foreach (var item in x)
                    {
                        item.vRowNum = rownum.ToString();
                        rownum      += 1;
                    }
                    result.AddRange(x);
                    //資料欄位狀態文字為未包含'取出'的資料 - 料欄位狀態文字為包含'取出'的資料
                    var _groupvCheckTotalNum = x.Sum(y => TypeTransfer.stringToInt(y.vCheckTotalNum));
                    //var _groupvCheckTotalNum =
                    //(x.Where(y => !y.vStatus.Contains(AccessProjectTradeType.G.GetDescription()) || !y.vTakeOutE.IsNullOrWhiteSpace())
                    //  .Sum(y => TypeTransfer.stringToInt(y.vCheckTotalNum)) -
                    // x.Where(y => y.vStatus.Contains(AccessProjectTradeType.G.GetDescription()) && y.vTakeOutE.IsNullOrWhiteSpace())
                    //  .Sum(y => TypeTransfer.stringToInt(y.vCheckTotalNum)));
                    var _group = new BillViewModel()
                    {
                        vStatus         = "小計",
                        vIssuingBank    = x.Key.vIssuingBank,
                        vCheckType      = x.Key.vCheckType,
                        vCheckTotalNum  = _groupvCheckTotalNum.ToString(),
                        vReMainTotalNum = x.Sum(y => TypeTransfer.stringToInt(y.vReMainTotalNum)).ToString()
                    };
                    _vCheckTotalNum += _groupvCheckTotalNum;
                    result.Add(_group);
                });
                result.Add(new BillViewModel()
                {
                    vStatus         = "總計",
                    vCheckTotalNum  = _vCheckTotalNum.ToString(),
                    vReMainTotalNum = _intReMainTotalNum.ToString()
                });
            }
            return(result);
        }
Example #7
0
 public void Update(BillViewModel billVm)
 {
     _billRepository.Update(_mapper.Map <Bill>(billVm));
 }
Example #8
0
        public ActionResult Edit(FormCollection formCollection, [FetchBill(KeyName = "billid")] BillEntity model, BillViewModel vo)
        {
            var jsonResult = new JsonResult {
                ContentEncoding = Encoding.UTF8
            };

            var result = new ExecuteResult <int>();

            if (ModelState.IsValid)
            {
                var tmp = Mapper.Map <BillViewModel, BillEntity>(vo);
                tmp.UpdatedDate = DateTime.Now;
                tmp.UpdatedUser = CurrentUser.CustomerId;
                tmp.Status      = model.Status;
                tmp.CreatedDate = model.CreatedDate;
                tmp.CreatedUser = model.CreatedUser;
                tmp.Status      = model.Status;
                tmp.IsDeleted   = model.IsDeleted;

                Mapper.Map(tmp, model);

                Update(model);
            }
            else
            {
                result.StatusCode = StatusCode.ClientError;
                result.Message    = "参数验证错误";
            }

            jsonResult.Data = result;

            return(jsonResult);
        }
        public async Task <IActionResult> Checkout(CheckoutViewModel model)
        {
            var session = HttpContext.Session.Get <List <ShoppingCartViewModel> >(CommonConstants.CartSession);
            var random  = new System.Random();

            if (ModelState.IsValid)
            {
                if (session != null)
                {
                    var details = new List <BillDetailViewModel>();
                    foreach (var item in session)
                    {
                        details.Add(new BillDetailViewModel()
                        {
                            Product   = item.Product,
                            Price     = item.Price,
                            ColorId   = item.Color.Id,
                            SizeId    = item.Size.Id,
                            Quantity  = item.Quantity,
                            ProductId = item.Product.Id,
                        });
                    }
                    var billViewModel = new BillViewModel()
                    {
                        CustomerMobile  = model.CustomerMobile,
                        BillStatus      = BillStatus.New,
                        CustomerAddress = model.Province + ", " + model.District + ", " + model.Ward + ", " + model.Street,
                        CustomerName    = model.CustomerName,
                        CustomerMessage = model.CustomerMessage,
                        BillDetails     = details,
                        DateCreated     = DateTime.Now,
                        Code            = random.Next().ToString(),
                        ShipCodeId      = model.ShipCodeId,
                        PaymentMethod   = model.PaymentMethod
                    };

                    if (User.Identity.IsAuthenticated == true)
                    {
                        billViewModel.CustomerId = Guid.Parse(User.GetSpecificClaim("UserId"));
                    }
                    _billService.Create(billViewModel);
                    try
                    {
                        _billService.Save();

                        var content = await _viewRenderService.RenderToStringAsync("Cart/_BillMail", billViewModel);

                        var contentAdmin = await _viewRenderService.RenderToStringAsync("Cart/_BillMailForAdmin", billViewModel);

                        List <string> images = new List <string>();

                        foreach (var item in details)
                        {
                            images.Add(@item.Product.Image.Replace('/', '\\'));
                        }

                        var addmessage = "<h4>Tài Khoản " + User.FindFirst("Email").Value.ToString() + " Đã mua hàng của bạn!!! Click + <a href='/admin/bill/index'>Vào Đây</a> + để kiểm tra thông tin!</h4>";
                        await _emailSender.SendEmailBillMailAsync(User.FindFirst("Email").Value.ToString(), "Đơn hàng mới từ shop Thành Vượng", content, images);

                        await _emailSender.SendEmailBillMailAsync("*****@*****.**", "Đơn hàng mới", addmessage.ToString() + contentAdmin, images);

                        ViewData["Success"] = true;

                        //Clear All product In HeaderCart
                        HttpContext.Session.Remove(CommonConstants.CartSession);
                    }
                    catch (Exception ex)
                    {
                        ViewData["Success"] = false;
                        ModelState.AddModelError("", ex.Message);
                    }
                }
            }

            model.Carts = session;

            return(View(model));
        }
Example #10
0
        public async Task <IActionResult> Checkout(CheckoutViewModel model)
        {
            var session = HttpContext.Session.Get <List <ShoppingCartViewModel> >(CommonConstants.CartSession);

            if (ModelState.IsValid)
            {
                if (session != null)
                {
                    var details = new List <BillDetailViewModel>();
                    foreach (var item in session)
                    {
                        details.Add(new BillDetailViewModel()
                        {
                            Product   = item.Product,
                            Price     = item.Price,
                            ColorId   = item.Color.Id,
                            SizeId    = item.Size.Id,
                            Quantity  = item.Quantity,
                            ProductId = item.Product.Id
                        });
                    }

                    Guid?guidUserId = (Guid?)null;
                    var  userId     = User.GetSpecificClaim(CommonConstants.UserId);
                    guidUserId = string.IsNullOrEmpty(userId) ? (Guid?)null : Guid.Parse(userId);

                    var billViewModel = new BillViewModel()
                    {
                        CustomerMobile  = model.CustomerMobile,
                        BillStatus      = BillStatus.New,
                        CustomerAddress = model.CustomerAddress,
                        CustomerName    = model.CustomerName,
                        CustomerMessage = model.CustomerMessage,
                        BillDetails     = details,
                        DateCreated     = DateTime.Now,
                        CustomerId      = guidUserId
                    };

                    _billService.Create(billViewModel);
                    try
                    {
                        _billService.Save();
                        var content = await _viewRenderService.RenderToStringAsync("~/Views/Cart/_BillMail.cshtml", billViewModel);

                        //Send mail
                        await _emailSender.SendEmailAsync(_configuration["MailSettings:AdminMail"], "Đơn hàng mới", content);

                        ViewData["Success"] = true;
                        model.Carts         = session;
                        HttpContext.Session.Remove(CommonConstants.CartSession);
                        ViewComponent("HeaderCart");
                    }
                    catch (Exception ex)
                    {
                        ViewData["Success"] = false;
                        ModelState.AddModelError("", ex.Message);
                        _logger.LogError("Send Mail" + ex.ToString());
                    }
                }
            }
            return(View(model));
        }
Example #11
0
        public static async Task <bool> SyncSalesData(BillViewModel SalesModel, byte isRealTime = 0)
        {
            try
            {
                SalesModel.username = username;
                SalesModel.password = password;
                var request = (HttpWebRequest)WebRequest.Create(Url + "/bill");
                var data    = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(SalesModel));
                request.Method        = "POST";
                request.ContentType   = "application/json";
                request.ContentLength = data.Length;

                using (var stream = (await request.GetRequestStreamAsync()))
                {
                    stream.Write(data, 0, data.Length);
                }
                var response = (HttpWebResponse)await request.GetResponseAsync();

                var  responseString = new System.IO.StreamReader(response.GetResponseStream()).ReadToEnd();
                byte status         = 0;
                switch (responseString)
                {
                case "200":
                case "101":
                    responseString = "200 : Success [" + responseString + "]";
                    status         = 1;
                    break;

                case "102":
                    responseString = "102 : Exception while saving bill details";
                    status         = 0;
                    break;

                case "103":
                    responseString = "103 : Unknown exceptions";
                    status         = 0;
                    break;

                case "100":
                    responseString = "100 : API credentials do not match";
                    status         = 0;
                    break;
                }
                await LogSyncStatus(SalesModel.invoice_number, SalesModel.fiscal_year, JsonConvert.SerializeObject(SalesModel), status, responseString, isRealTime);

                return(responseString == "200");
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    string           Response = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                    FunctionResponse res      = JsonConvert.DeserializeObject <FunctionResponse>(Response);
                    if (res != null && res.result != null)
                    {
                        await LogSyncStatus(SalesModel.invoice_number, SalesModel.fiscal_year, JsonConvert.SerializeObject(SalesModel), 0, res.result.ToString());
                    }
                    else
                    {
                        await LogSyncStatus(SalesModel.invoice_number, SalesModel.fiscal_year, JsonConvert.SerializeObject(SalesModel), 0, Response);
                    }
                }
                else
                {
                    await LogSyncStatus(SalesModel.invoice_number, SalesModel.fiscal_year, JsonConvert.SerializeObject(SalesModel), 0, ex.GetBaseException().Message);
                }
                return(false);
            }
            catch (Exception ex)
            {
                await LogSyncStatus(SalesModel.invoice_number, SalesModel.fiscal_year, JsonConvert.SerializeObject(SalesModel), 0, ex.GetBaseException().Message);

                return(false);
            }
        }
Example #12
0
        public void Update(BillViewModel billVm)
        {
            //Mapping to order domain
            var order = _orderRepository.FindById(billVm.Id, i => i.BillDetails);

            //Get order Detail
            var newDetails = Mapper.Map <List <BillDetailViewModel>, List <BillDetail> >(billVm.BillDetails);

            //new details added
            var addedDetails = newDetails.Where(x => x.Id == 0).ToList();

            //get updated details
            var updatedDetailVms = newDetails.Where(x => x.Id != 0).ToList();

            //Existed details
            var existedDetails = _orderDetailRepository.FindAll(x => x.BillId == billVm.Id);

            //Clear db

            List <BillDetail> updatedDetails = new List <BillDetail>();

            foreach (var detailVm in updatedDetailVms)
            {
                var detail = _orderDetailRepository.FindById(detailVm.Id);
                detail.Quantity  = detailVm.Quantity;
                detail.ProductId = detailVm.ProductId;
                var product = _productRepository.FindById(detailVm.ProductId);
                detail.Price = product.PromotionPrice ?? product.Price;
                _orderDetailRepository.Update(detail);
                updatedDetails.Add(detail);
            }

            foreach (var detail in addedDetails)
            {
                var product = _productRepository.FindById(detail.ProductId);
                detail.Price  = product.PromotionPrice ?? product.Price;
                detail.BillId = order.Id;
                _orderDetailRepository.Add(detail);
            }

            _orderDetailRepository.RemoveMultiple(existedDetails.Except(updatedDetails).ToList());

            if (order.BillStatus != BillStatus.Completed && billVm.BillStatus == BillStatus.Completed)
            {
                ConfirmBill(order.Id);
            }
            if (order.BillStatus != BillStatus.Cancelled && billVm.BillStatus == BillStatus.Cancelled)
            {
                CancelBill(order.Id);
            }
            order.CustomerName     = billVm.CustomerName;
            order.CustomerAddress  = billVm.CustomerAddress;
            order.CustomerFacebook = billVm.CustomerFacebook;
            order.CustomerMessage  = billVm.CustomerMessage;
            order.CustomerMobile   = billVm.CustomerMobile;
            order.BillStatus       = billVm.BillStatus;
            order.PaymentMethod    = billVm.PaymentMethod;
            order.ShippingFee      = billVm.ShippingFee;

            _orderRepository.Update(order);
        }
Example #13
0
        public async Task <IActionResult> Update([FromBody] BillViewModel billVmPost)
        {
            var hasPermission = await _authorizationService.AuthorizeAsync(User, "BILL", Operations.Update);

            if (hasPermission.Succeeded == false)
            {
                return(new BadRequestObjectResult(CommonConstants.Forbidden));
            }
            if (ModelState.IsValid)
            {
                if (billVmPost.BillStatus == BillStatus.Completed)
                {
                    List <BillDetailViewModel> billDetailVm = _billService.GetBillDetails(billVmPost.Id);
                    foreach (var item in billDetailVm)
                    {
                        Product productDb = _productService.GetProductDbById(item.ProductId);
                        productDb.ViewCount = productDb.ViewCount + item.Quantity;
                        _productService.UpdateDb(productDb);
                        ProductQuantity productQuantityDb = _productQuantityService.GetSingleDb(item.ProductId, item.SizeId, item.ColorId);
                        productQuantityDb.Quantity = productQuantityDb.Quantity - item.Quantity;
                        _productQuantityService.UpdateDb(productQuantityDb);
                        _billService.SaveChanges();
                    }
                }
                if (string.IsNullOrEmpty(billVmPost.CustomerId.ToString()))
                {
                    _billService.Update(billVmPost);
                    _billService.SaveChanges();
                    return(new OkObjectResult(billVmPost.Id));
                }
                else
                {
                    BillStatus billStauts = billVmPost.BillStatus;
                    if (billStauts == BillStatus.Cancelled || billStauts == BillStatus.Returned)
                    {
                        AppUser appUser = await _userManger.FindByIdAsync(billVmPost.CustomerId.ToString());

                        var totalBalance = appUser.Balance;

                        appUser.Balance = appUser.Balance + (decimal)billVmPost.TotalMoneyOrder + (decimal)billVmPost.FeeShipping
                                          - (decimal)billVmPost.BalanceForBill - (decimal)billVmPost.TotalMoneyPayment;

                        var result = await _userManger.UpdateAsync(appUser);

                        if (result.Succeeded)
                        {
                            _billService.Update(billVmPost);
                            _billService.SaveChanges();
                            return(new OkObjectResult(billVmPost.Id));
                        }
                        else
                        {
                            return(new BadRequestObjectResult(ModelState));
                        }
                    }
                    else
                    {
                        _billService.Update(billVmPost);
                        _billService.SaveChanges();
                        return(new OkObjectResult(billVmPost.Id));
                    }
                }
            }
            return(new BadRequestObjectResult(ModelState));
        }
Example #14
0
 public MasterTabbedPage()
 {
     InitializeComponent();
     BindingContext = new BillViewModel();
 }
        public async Task <IActionResult> Checkout(BillViewModel billVm, decimal feeShipping, decimal totalMoneyOrder, decimal balanceForBill, decimal totalMoneyPayment)
        {
            try
            {
                var           shoppingCart = HttpContext.Session.GetList <ShoppingCardViewModel>(CommonConstants.SesstionCart);
                BillViewModel billViewModel;
                billViewModel                   = billVm;
                billViewModel.FeeShipping       = feeShipping;
                billViewModel.TotalMoneyOrder   = totalMoneyOrder;
                billViewModel.TotalMoneyPayment = totalMoneyPayment;
                billViewModel.BillStatus        = Data.Enums.BillStatus.New;
                billViewModel.Status            = Data.Enums.Status.Active;
                if (User.Identity.IsAuthenticated)
                {
                    var user = await _userManager.FindByNameAsync(User.Identity.Name);

                    billViewModel.BalanceForBill = balanceForBill;
                    billViewModel.CustomerId     = user.Id;
                }
                var     listBillDetails    = new List <BillDetailViewModel>();
                decimal totalOriginalPrice = 0;
                foreach (var item in shoppingCart)
                {
                    decimal salePrice;
                    if (item.ProductVm.PromotionPrice.HasValue)
                    {
                        salePrice = (decimal)item.ProductVm.PromotionPrice;
                    }
                    else
                    {
                        salePrice = item.ProductVm.Price;
                    }
                    BillDetailViewModel billDetailVm = new BillDetailViewModel()
                    {
                        ProductId     = item.ProductId,
                        ColorId       = item.ColorVm.Id,
                        SizeId        = item.SizeVm.Id,
                        Quantity      = item.Quantity,
                        Price         = salePrice,
                        OriginalPrice = item.ProductVm.OriginalPrice
                    };
                    totalOriginalPrice = totalOriginalPrice + item.Quantity * item.ProductVm.OriginalPrice;
                    listBillDetails.Add(billDetailVm);
                }
                billViewModel.BillDetails        = listBillDetails;
                billViewModel.TotalOriginalPrice = totalOriginalPrice;
                int billId = _billService.Add(billViewModel);
                billViewModel.Id          = billId;
                billViewModel.DateCreated = DateTime.Now;
                if (User.Identity.IsAuthenticated)
                {
                    AppUser appUser = await _userManager.FindByNameAsync(User.Identity.Name);

                    if (totalMoneyPayment > 0)
                    {
                        appUser.Balance = balanceForBill;
                    }
                    else
                    {
                        appUser.Balance = appUser.Balance - totalMoneyOrder - feeShipping + balanceForBill;
                    }
                    await _userManager.UpdateAsync(appUser);
                }
                HttpContext.Session.SetList <ShoppingCardViewModel>(CommonConstants.SesstionCart, null);
                return(new OkObjectResult(new { status = true, billVm = billViewModel }));
            }
            catch
            {
                return(new OkObjectResult(new { status = false }));
            }
        }
 public void Put(int id, [FromBody] BillViewModel billVm)
 {
 }
Example #17
0
        public async Task <IActionResult> Checkout(BillViewModel bill)
        {
            ViewData["BodyClass"] = "checkout_page";
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError(string.Empty, "Your information is invalid. Please check again.");
                return(View());
            }
            var session = HttpContext.Session.Get <List <CartViewModel> >(CommonConstants.CartSession);

            if (User.Identity.IsAuthenticated)
            {
                var user = await _userService.FindByNameAsync(User.Identity.Name);

                if (user != null)
                {
                    bill.CustomerId = user.Id;
                }
            }
            else
            {
                bill.CustomerId = Guid.NewGuid();
            }

            foreach (var item in session)
            {
                var billDetail = new BillDetailViewModel();
                billDetail.ProductId = item.Product.Id;
                billDetail.Quantity  = item.Quantity;
                billDetail.Price     = item.Price;
                billDetail.ColorId   = item.ColorId;
                billDetail.SizeId    = item.SizeId;
                billDetail.Status    = Status.Active;
                bill.BillDetails.Add(billDetail);
            }
            try
            {
                _billService.CreateBill(bill);
                _billService.Save();
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Your information is invalid. Please check again.");
            }

            // Send email to customer and admin
            var    rootPath = $@"{_hostingEnvironment.WebRootPath}\templates\OrderSuccess\EmailTemplate.html";
            string content  = System.IO.File.ReadAllText(rootPath);

            var billid = _billService.GetLatestBillByCustomerId(bill.CustomerId);

            content = content.Replace("{{OrderId}}", billid.Id.ToString());
            content = content.Replace("{{OrderDate}}", billid.CreatedDate.ToString("dd MMM yyyy - hh: mm: ss tt"));
            content = content.Replace("{{PaymentMethod}}", billid.PaymentMethod.ToString());
            content = content.Replace("{{Email}}", billid.CustomerEmail);
            content = content.Replace("{{Fullname}}", billid.CustomerName);
            content = content.Replace("{{Address}}", billid.CustomerAddress);
            content = content.Replace("{{Phone}}", billid.CustomerPhone);
            content = content.Replace("{{Message}}", billid.CustomerMessage);
            decimal totalBill = 0;

            foreach (var item in billid.BillDetails)
            {
                totalBill += item.Quantity * item.Price;
            }
            content = content.Replace("{{TotalCost}}", totalBill.ToString());

            await _emailSender.SendEmailAsync(billid.CustomerEmail, $"ShopMart order confirmation - Order number: #{billid.Id}", content);

            await _emailSender.SendEmailAsync(CommonConstants.mailAdmin, $"ShopMart order confirmation - Order number: #{billid.Id}", content);

            var customId = $"{billid.CustomerId}_{DateTime.Now.Ticks}";

            return(RedirectToAction(nameof(CartController.OrderSuccess), new { id = customId }));
        }
        public void SetUp()
        {
            validViewModel = new BillViewModel
            {
                Amount            = 10,
                Category          = "TEST",
                Id                = Guid.NewGuid(),
                Name              = "TEST",
                ReoccurringPeriod = TimePeriod.Daily,
                StartDate         = DateTime.Now,
                UserId            = Guid.NewGuid()
            };

            validBillProxy = new BillProxy
            {
                Amount   = 10,
                Category = new CategoryProxy {
                    Id = Guid.NewGuid(), Name = "TEST"
                },
                CategoryId        = Guid.NewGuid(),
                Id                = Guid.NewGuid(),
                Name              = "TEST",
                ReoccurringPeriod = 1,
                StartDate         = DateTime.Now,
                UserId            = Guid.NewGuid()
            };

            validManageBillsViewModel = new ManageBillsViewModel();

            validDeleteBillRequest = new DeleteBillRequest {
                BillId = validBillProxy.Id
            };
            validDeleteBillResponse = new DeleteBillResponse {
                DeleteSuccess = true
            };
            validAddBillRequest = new AddBillRequest {
                Bill = validBillProxy
            };
            validAddBillResponse = new AddBillResponse {
                Bill = validBillProxy
            };
            validGetBillRequest = new GetBillRequest {
                BillId = validBillProxy.Id
            };
            validGetBillResponse = new GetBillResponse {
                Bill = validBillProxy
            };
            validGetBillsForUserRequest = new GetBillsForUserRequest {
                UserId = validBillProxy.Id
            };
            validGetBillsForUserResponse =
                new GetBillsForUserResponse {
                Bills = new List <BillProxy> {
                    validBillProxy
                }
            };
            validEditBillRequest = new EditBillRequest {
                Bill = validBillProxy
            };
            validEditBillResponse = new EditBillResponse {
                Bill = validBillProxy
            };
            validGetBillsForUserForMonthRequest = new GetBillsForUserForMonthRequest {
                UserId = validBillProxy.Id
            };
            validGetBillsForUserForMonthResponse =
                new GetBillsForUserForMonthResponse {
                Data = new List <KeyValuePair <DateTime, double> >()
            };

            invalidBillViewModel = new BillViewModel {
                Id = Guid.NewGuid()
            };
            invalidAddBillRequest  = new AddBillRequest();
            invalidAddBillResponse = new AddBillResponse {
                Errors = { new ResponseErrorWrapper() }
            };
            invalidGetBillRequest  = new GetBillRequest();
            invalidGetBillResponse = new GetBillResponse {
                Errors = { new ResponseErrorWrapper() }
            };
            invalidDeleteBillRequest  = new DeleteBillRequest();
            invalidDeleteBillResponse = new DeleteBillResponse {
                Errors = { new ResponseErrorWrapper() }
            };
            invalidGetBillsForUserRequest  = new GetBillsForUserRequest();
            invalidGetBillsForUserResponse = new GetBillsForUserResponse {
                Errors = { new ResponseErrorWrapper() }
            };
            invalidEditBillRequest  = new EditBillRequest();
            invalidEditBillResponse = new EditBillResponse {
                Errors = { new ResponseErrorWrapper() }
            };
            invalidGetBillsForUserForMonthRequest  = new GetBillsForUserForMonthRequest();
            invalidGetBillsForUserForMonthResponse =
                new GetBillsForUserForMonthResponse {
                Errors = { new ResponseErrorWrapper() }
            };

            assembler   = Substitute.For <IBillAssembler>();
            dataAccess  = Substitute.For <IBillDataAccess>();
            errorHelper = Substitute.For <IErrorHelper>();

            errorHelper.Create(Arg.Any <Exception>(), Arg.Any <string>(), Arg.Any <Type>(), Arg.Any <string>())
            .Returns(new ResponseErrorWrapper());
            errorHelper.Create(Arg.Any <string>(), Arg.Any <string>(), Arg.Any <Type>(), Arg.Any <string>())
            .Returns(new ResponseErrorWrapper());

            assembler.NewAddBillRequest(validViewModel, validUsername).Returns(validAddBillRequest);
            assembler.NewAddBillRequest(invalidBillViewModel, validUsername).Returns(invalidAddBillRequest);
            assembler.NewAddBillRequest(null, validUsername).Throws(new Exception("TEST EXCEPTION"));
            assembler.NewBillViewModel(validAddBillResponse).Returns(validViewModel);
            assembler.NewBillViewModel(validEditBillResponse).Returns(validViewModel);
            assembler.NewDeleteBillRequest(validViewModel.Id, validUsername).Returns(validDeleteBillRequest);
            assembler.NewDeleteBillRequest(invalidBillViewModel.Id, validUsername).Returns(invalidDeleteBillRequest);
            assembler.NewDeleteBillRequest(Guid.Empty, validUsername).Throws(new Exception("TEST EXCEPTION"));
            assembler.NewGetBillRequest(validViewModel.Id, validUsername).Returns(validGetBillRequest);
            assembler.NewGetBillRequest(invalidBillViewModel.Id, validUsername).Returns(invalidGetBillRequest);
            assembler.NewGetBillRequest(Guid.Empty, validUsername).Throws(new Exception("TEST EXCEPTION"));
            assembler.NewGetBillsForUserRequest(validViewModel.Id, validUsername).Returns(validGetBillsForUserRequest);
            assembler.NewGetBillsForUserRequest(invalidBillViewModel.Id, validUsername)
            .Returns(invalidGetBillsForUserRequest);
            assembler.NewGetBillsForUserRequest(Guid.Empty, validUsername).Throws(new Exception("TEST EXCEPTION"));
            assembler.NewEditBillRequest(validViewModel, validUsername).Returns(validEditBillRequest);
            assembler.NewEditBillRequest(invalidBillViewModel, validUsername).Returns(invalidEditBillRequest);
            assembler.NewEditBillRequest(null, validUsername).Throws(new Exception("TEST EXCEPTION"));
            assembler.NewGetBillsForUserForMonthRequest(1, validViewModel.Id, validUsername)
            .Returns(validGetBillsForUserForMonthRequest);
            assembler.NewGetBillsForUserForMonthRequest(1, invalidBillViewModel.Id, validUsername)
            .Returns(invalidGetBillsForUserForMonthRequest);
            assembler.NewManageBillsViewModel(validGetBillsForUserResponse).Returns(validManageBillsViewModel);
            assembler.NewExportViewModel(ExportType.Json, Arg.Any <IList <BillProxy> >()).Throws(new Exception("TEST"));

            dataAccess.AddBill(validAddBillRequest).Returns(validAddBillResponse);
            dataAccess.AddBill(invalidAddBillRequest).Returns(invalidAddBillResponse);
            dataAccess.DeleteBill(validDeleteBillRequest).Returns(validDeleteBillResponse);
            dataAccess.DeleteBill(invalidDeleteBillRequest).Returns(invalidDeleteBillResponse);
            dataAccess.GetBill(validGetBillRequest).Returns(validGetBillResponse);
            dataAccess.GetBill(invalidGetBillRequest).Returns(invalidGetBillResponse);
            dataAccess.GetBillsForUser(validGetBillsForUserRequest).Returns(validGetBillsForUserResponse);
            dataAccess.GetBillsForUser(invalidGetBillsForUserRequest).Returns(invalidGetBillsForUserResponse);
            dataAccess.EditBill(validEditBillRequest).Returns(validEditBillResponse);
            dataAccess.EditBill(invalidEditBillRequest).Returns(invalidEditBillResponse);
            dataAccess.GetBillsForUserForMonth(validGetBillsForUserForMonthRequest)
            .Returns(validGetBillsForUserForMonthResponse);
            dataAccess.GetBillsForUserForMonth(invalidGetBillsForUserForMonthRequest)
            .Returns(invalidGetBillsForUserForMonthResponse);

            assembler.NewExportViewModel(ExportType.Csv, new List <BillProxy> {
                validBillProxy
            })
            .Returns(new ExportViewModel());

            orchestrator = new BillOrchestrator(assembler, dataAccess, errorHelper);
        }
        public async Task <IActionResult> Checkout(CheckoutViewModel model)
        {
            var session = HttpContext.Session.Get <List <ShoppingCartViewModel> >(CommonConstants.CartSession);

            if (ModelState.IsValid)
            {
                if (session != null)
                {
                    var details = new List <BillDetailViewModel>();
                    foreach (var item in session)
                    {
                        details.Add(new BillDetailViewModel()
                        {
                            Price     = item.Price,
                            ColorId   = item.Color.Id,
                            SizeId    = item.Size.Id,
                            Quantity  = item.Quantity,
                            ProductId = item.Product.Id
                        });
                    }

                    var billViewModel = new BillViewModel()
                    {
                        CustomerMobile  = model.CustomerMobile,
                        BillStatus      = BillStatus.New,
                        CustomerAddress = model.CustomerAddress,
                        CustomerName    = model.CustomerName,
                        CustomerMessage = model.CustomerMessage,
                        BillDetails     = details,
                        Status          = Status.Active,
                        ShipperId       = 1
                    };

                    if (User.Identity.IsAuthenticated == true)
                    {
                        billViewModel.CustomerId = Guid.Parse(User.GetSpecificClaim("UserId"));
                    }

                    var notificationId = Guid.NewGuid().ToString();


                    var announcement = new AnnouncementViewModel()
                    {
                        Title       = "New bill",
                        DateCreated = DateTime.Now,
                        UserId      = Guid.Parse(User.GetSpecificClaim("UserId")),
                        Content     = $"New bill has been created",
                        Id          = notificationId
                    };

                    var users = await _userService.AnnouncementUsers("BILL");

                    var announUsers = new List <AnnouncementUserViewModel>();

                    foreach (var item in users)
                    {
                        announUsers.Add(new AnnouncementUserViewModel()
                        {
                            AnnouncementId = notificationId,
                            HasRead        = false,
                            UserId         = (Guid)item.Id
                        });
                    }

                    announcement.AnnouncementUsers = announUsers;

                    _billService.Create(billViewModel, announcement);

                    try
                    {
                        _billService.Save();

                        //var content = await _viewRenderService.RenderToStringAsync("Cart/_BillMail", billViewModel);
                        ////Send mail
                        //await _emailSender.SendEmailAsync(_configuration["MailSettings:AdminMail"], "New bill from ShopMart", content);

                        ViewData["Success"] = true;

                        await _hubContext.Clients.All.SendAsync("ReceiveMessage", announcement);
                    }
                    catch (Exception ex)
                    {
                        ViewData["Success"] = false;
                        ModelState.AddModelError("", ex.Message);
                    }
                }
            }

            model.Carts = session;
            return(View(model));
        }
Example #20
0
 public void Init()
 {
     this._mockRepository    = new Mock <IRepository>();
     this._mockDialogService = new Mock <IDialogService>();
     this._billViewModel     = new BillViewModel(Resources.Workspace_Title_Bills, Resources.img_bills, this._mockRepository.Object, this._mockDialogService.Object);
 }
Example #21
0
        public async Task <IActionResult> PayBillAsync(BillViewModel model)
        {
            var result = await _payBillCommand.ExecuteAsync(model);

            return(StatusCode(result.GetStatusCode(), result.GetData()));
        }
Example #22
0
 public void Cleanup()
 {
     this._mockRepository    = null;
     this._mockDialogService = null;
     this._billViewModel     = null;
 }
Example #23
0
 public void Put(int id, BillViewModel billVm)
 {
 }
Example #24
0
 public async Task NewMessage(BillViewModel message)
 {
     await Clients.All.SendAsync("messageReceived", message);
 }
        public GenericResult Update(AnnouncementViewModel announcementViewModel, List <AnnouncementUserViewModel> announcementUsers, BillViewModel billViewModel)
        {
            try
            {
                // Mapping to order domain
                var order = _mapper.Map <BillViewModel, Bill>(billViewModel);
                // Lấy Toàn Bộ Chi Tiết Hóa Đơn Ra Sau Khi Mapping Vào
                var orderDetails = order.BillDetails;
                // Them 1 chi tiet hoa don
                var addDetails = orderDetails.Where(x => x.Id == 0).ToList();
                // Update Chi Tiet hoa don
                var updateDetails = orderDetails.Where(x => x.Id != 0).ToList();
                // Existed Details
                var existedDetails = _orderDetailRepository.FindAll(x => x.BillId == billViewModel.Id).ToList();
                //Clear db
                order.BillDetails.Clear();
                _orderDetailRepository.RemoveMultiple(existedDetails.Except(updateDetails).ToList());
                foreach (var productDetail in updateDetails)
                {
                    var product = _productRepository.FindById(productDetail.ProductId);
                    productDetail.Price = product.Price;
                    _orderDetailRepository.Update(productDetail);
                }

                foreach (var productDetail in addDetails)
                {
                    var product = _productRepository.FindById(productDetail.ProductId);
                    productDetail.Price = product.Price;
                    _orderDetailRepository.Add(productDetail);
                }

                order.Total = updateDetails.Sum(x => x.Quantity * x.Price) + addDetails.Sum(x => x.Quantity * x.Price);
                _orderRepository.Update(order);
                // Real Time
                var announcement = _mapper.Map <AnnouncementViewModel, Announcement>(announcementViewModel);
                _announceRepository.Add(announcement);
                foreach (var announcementUserViewModel in announcementUsers)
                {
                    _announceUserRepository.Add(_mapper.Map <AnnouncementUserViewModel, AnnouncementUser>(announcementUserViewModel));
                }
                return(new GenericResult(true, "Update Successful", "Successful"));
            }
            catch (Exception)
            {
                return(new GenericResult(false, "Update Failed", "Error"));
            }
        }
Example #26
0
        public virtual ActionResult Bill(int billId)
        {
            var vm = new BillViewModel();

            var bill = _accountService.GetBill(billId);
            if (bill.HasErrors)
            {
                return new HttpNotFoundResult();
            }

            // predictions
            var predictionCutoff = DateTime.Now.AddDays(10);
            foreach (var billTransaction in bill.Result.BillTransactions)
            {
                if (billTransaction.Timestamp < predictionCutoff && (!billTransaction.IsPaid || !billTransaction.Transactions.Any()))
                {
                    var billPredictionResult = _accountService.PredictBillTransactionMatch(billTransaction.Id);
                    if (!billPredictionResult.HasErrors)
                        billTransaction.TransactionPredictions = billPredictionResult.Result;
                }
            }

            vm.Bill = bill.Result;

            return View(vm);
        }
Example #27
0
        public IActionResult Index()
        {
            ViewBag.Title       = "System Statistics";
            ViewBag.Description = "Current statistics for the services.";

            StatsViewModel model = new StatsViewModel();

            // Load initial status info
            #region Statistics
            model.UploadCount = _dbContext.Uploads.Count();
            model.UploadSize  = _dbContext.Uploads.Sum(u => u.ContentLength);

            model.PasteCount = _dbContext.Pastes.Count();

            model.UserCount = _dbContext.Users.Count();

            model.ShortenedUrlCount = _dbContext.ShortenedUrls.Count();

            model.VaultCount = _dbContext.Vaults.Count();
            #endregion

            // Get Transaction Inforomation
            #region Transactions
            DateTime curTime = DateTime.Now;

            var billSums = _dbContext.Transactions.OfType <Bill>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
            foreach (var sum in billSums)
            {
                decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
                decimal realValue    = sum.total * exchangeRate;
                model.Transactions.TotalBills += realValue;
                model.Transactions.TotalNet   += realValue;
                if (curTime.Month == sum.month && curTime.Year == sum.year)
                {
                    model.Transactions.CurrentMonthBills += Math.Abs(realValue);
                }
            }

            var oneSums = _dbContext.Transactions.OfType <OneTime>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
            foreach (var sum in oneSums)
            {
                decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
                decimal realValue    = sum.total * exchangeRate;
                model.Transactions.TotalOneTimes += realValue;
                model.Transactions.TotalNet      += realValue;
                if (curTime.Month == sum.month && curTime.Year == sum.year)
                {
                    model.Transactions.CurrentMonthBills += Math.Abs(realValue);
                }
            }

            var donationSums = _dbContext.Transactions.OfType <Donation>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
            foreach (var sum in donationSums)
            {
                decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
                decimal realValue    = sum.total * exchangeRate;
                model.Transactions.TotalDonations += realValue;
                model.Transactions.TotalNet       += realValue;
                if (curTime.Month == sum.month && curTime.Year == sum.year)
                {
                    model.Transactions.CurrentMonthIncome += Math.Abs(realValue);
                }
            }

            List <Bill> bills = _dbContext.Transactions.OfType <Bill>().OrderByDescending(b => b.DateSent).ToList();
            if (bills != null)
            {
                foreach (Bill bill in bills)
                {
                    BillViewModel billModel = new BillViewModel();
                    billModel.Amount    = bill.Amount;
                    billModel.Currency  = bill.Currency;
                    billModel.Reason    = bill.Reason;
                    billModel.DateSent  = bill.DateSent;
                    billModel.Recipient = bill.Recipient;
                    model.Transactions.Bills.Add(billModel);
                }
            }

            List <OneTime> oneTimes = _dbContext.Transactions.OfType <OneTime>().OrderByDescending(b => b.DateSent).ToList();
            if (oneTimes != null)
            {
                foreach (OneTime oneTime in oneTimes)
                {
                    OneTimeViewModel oneTimeModel = new OneTimeViewModel();
                    oneTimeModel.Amount    = oneTime.Amount;
                    oneTimeModel.Currency  = oneTime.Currency;
                    oneTimeModel.Reason    = oneTime.Reason;
                    oneTimeModel.DateSent  = oneTime.DateSent;
                    oneTimeModel.Recipient = oneTime.Recipient;
                    model.Transactions.OneTimes.Add(oneTimeModel);
                }
            }

            List <Donation> donations = _dbContext.Transactions.OfType <Donation>().OrderByDescending(b => b.DateSent).ToList();
            if (donations != null)
            {
                foreach (Donation donation in donations)
                {
                    DonationViewModel donationModel = new DonationViewModel();
                    donationModel.Amount   = donation.Amount;
                    donationModel.Currency = donation.Currency;
                    donationModel.Reason   = donation.Reason;
                    donationModel.DateSent = donation.DateSent;
                    donationModel.Sender   = donation.Sender;
                    model.Transactions.Donations.Add(donationModel);
                }
            }
            #endregion

            // Takedown information
            #region Takedowns
            List <Takedown> takedowns = _dbContext.Takedowns.OrderByDescending(b => b.DateRequested).ToList();
            if (takedowns != null)
            {
                foreach (Takedown takedown in takedowns)
                {
                    TakedownViewModel takedownModel = new TakedownViewModel();
                    takedownModel.Requester        = takedown.Requester;
                    takedownModel.RequesterContact = takedown.RequesterContact;
                    takedownModel.Reason           = takedown.Reason;
                    takedownModel.ActionTaken      = takedown.ActionTaken;
                    takedownModel.DateRequested    = takedown.DateRequested;
                    takedownModel.DateActionTaken  = takedown.DateActionTaken;

                    model.Takedowns.Add(takedownModel);
                }
            }
            #endregion
            return(View(model));
        }
Example #28
0
        public async Task <EcPayTradeModel> BeginPayAsync(int billId, BillViewModel model, string userId)
        {
            // BeginPay 支付帳單
            var existingBill = _billsService.GetById(billId);

            if (existingBill == null)
            {
                return(null);
            }

            int paywayId = model.PayWayId;
            var payway   = _paysService.GetPayWayById(paywayId);

            if (payway == null)
            {
                throw new EntityNotFoundException(new PayWay {
                    Id = paywayId
                });
            }


            if (existingBill.Payed)
            {
                throw new BadRequestException(new RequestErrorViewModel {
                    Key = "payed", Message = "此訂單已經支付過了"
                });
            }

            if (existingBill.Expired)
            {
                throw new BadRequestException(new RequestErrorViewModel {
                    Key = "expired", Message = "訂單已過繳款期限"
                });
            }


            var pay = Pay.Create(existingBill, payway, ThirdPartyPayment.EcPay);

            var amount          = Convert.ToInt32(existingBill.NeedPayMoney);
            var ecPayTradeModel = _thirdPartyPayService.CreateEcPayTrade(pay, amount);

            if (!ecPayTradeModel.HasToken)
            {
                throw new BadRequestException(new RequestErrorViewModel {
                    Key = "", Message = "開啟支付程序失敗,請稍候再試."
                });
            }


            await _paysService.CreateAsync(pay);

            if (existingBill.PayWayId != paywayId)
            {
                existingBill.PayWayId = paywayId;
                await _billsService.UpdateAsync(existingBill);
            }

            ecPayTradeModel.PaymentType = payway.Code;

            return(ecPayTradeModel);
        }
Example #29
0
 private void SetBillInSession(BillViewModel bill)
 {
     Session["bill"] = bill;
 }
Example #30
0
        public ActionResult DeleteConfirmed(int id, BillViewModel billViewModel)
        {
            this.billService.DeleteById(id);

            return(RedirectToAction("Index", "Bills"));
        }
Example #31
0
 public BillTemplate()
 {
     InitializeComponent();
     DataContext = new BillViewModel();
 }
Example #32
0
        public ActionResult CheckBill()
        {
            var currentOrder = new BillViewModel();

            return(View(currentOrder));
        }