Example #1
0
        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters != null && navigationContext.Parameters.Any())
            {
                var dishes = navigationContext.Parameters["Dishes"] as List<DishViewModel>;

                if (dishes != null)
                    ViewModel = new OrderViewModel(dishes)
                    {
                        Repository = Repository,
                        NavigationService = navigationContext.NavigationService
                    };
                else
                    ViewModel = new OrderViewModel
                    {
                        Repository = Repository,
                        NavigationService = navigationContext.NavigationService
                    };

            }
            else
                ViewModel = new OrderViewModel
                {
                    Repository = Repository,
                    NavigationService = navigationContext.NavigationService
                };
        }
        public ActionResult Order()
        {
            var viewModel = new OrderViewModel();
            if (this.Request.Cookies[UserIdCart] != null)
            {
                var cart = this.shoppingService.GetByUserId(Request.Cookies[UserIdCart].Value);
                if (cart.ProductsCount > 0)
                {
                    var productsIds = cart.ProductIds.Split(new string[] { "," } ,StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    var productsAsQuerable = this.ProductsService.GetByIds(productsIds).ToList();
                    var products = this.Mapper.Map<List<ProductViewModel>>(productsAsQuerable);

                    var sizes = cart.Sizes.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList();
                    for (int i = 0; i < products.Count; i++)
                    {
                        products[i].Sizes.Clear();
                    }

                    for (int i = 0; i < sizes.Count; i++)
                    {
                        var product = products.FirstOrDefault(p => p.Id == productsIds[i]);
                        product.Sizes.Add(new SizeViewModel { Value = (short)sizes[i] });
                    }

                    viewModel = new OrderViewModel
                    {
                        Products = products,
                        TotalPrice = products.Sum(p => p.Price)
                    };
                }
            }

            return View(viewModel);
        }
Example #3
0
        public ActionResult Index()
        {
            var shipToId = SodaSession.ShipToId;
            var order = _productService.GetOrder(shipToId.Value, true);
            OrderViewModel vm = new OrderViewModel();

            foreach (var item in order)
            {
                if (item.OrderQty != null) item.ExtAmt = item.Price * item.OrderQty.Value;
                item.SalesTaxAmt = item.TaxRate * item.Taxable * item.ExtAmt;
                if (item.OrderQty != null) item.CRVAmt = item.OrderQty.Value * item.CRVperUnit;

                vm.TaxTotal += item.SalesTaxAmt;
                vm.CSVTotal += item.CRVAmt;
                vm.GrandTotal += item.ExtAmt + item.SalesTaxAmt + item.CRVAmt;
                vm.SubTotal += item.ExtAmt;
            }

            var shippingInfo = _shippingService.GetShippingInfo(shipToId.Value);

            vm.Items = order;
            vm.ShippingInfo = shippingInfo;

            return View(vm);
        }
Example #4
0
        public ActionResult Create(OrderViewModel vmChanged, string redirectButton)
        {
            var vm = GetViewModelFromTempData<OrderViewModel>() ?? new OrderViewModel(new OrderDTO(), null, true);
            vm.DisplayName = Strings.OrderViewModel_DisplayName;
            vm.ApplyFormAttributes(vmChanged.Model);

            return StoreEntity(vm, redirectButton);
        }
Example #5
0
        public ActionResult Edit(OrderViewModel vmChanged, string redirectButton)
        {
            var vm = GetViewModelFromTempData<OrderViewModel>();

            vm.ApplyFormAttributes(vmChanged.Model);

            return StoreEntity(vm, redirectButton);
        }
Example #6
0
        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            OrderViewModel = new OrderViewModel();
            LayoutRoot.DataContext = OrderViewModel;

            // 用于本地化 ApplicationBar 的示例代码
            //BuildLocalizedApplicationBar();
        }
        public OrderViewModel GetOrderDetailsx(int orderID)
        {
            OrderDataAccessService orderDataAccessService = new OrderDataAccessService();
               OrderViewModel orderViewModel = new OrderViewModel();
               List<OrderDetailProductResult> orderDetailProductResult = new List<OrderDetailProductResult>();
               orderViewModel = orderDataAccessService.GetOrderDetails(orderID);
            OrderCustomer orderCustomer = orderDataAccessService.GetOrder(orderID);
               orderViewModel.OrderDetailProductResults = orderDetailProductResult;
               orderViewModel.Order = orderCustomer.Order;
               orderViewModel.Customer = orderCustomer.Customer;

               return orderViewModel;
        }
 public virtual ActionResult Search()
 {
     var model = new SearchViewModel(ViewData.Model as BaseViewModel);
     var order = new OrderViewModel
                     {Id = 100, Deadline = DateTime.Now, Title = "Karrbros Official", Group = "Best Group Evar"};
     var order2 = new OrderViewModel {Id = 101, Deadline = DateTime.Now.AddDays(15), Title = "Clinton Wrestling", Group = "Time To Get Live" };
     model.Orders.Add(order);
     model.Orders.Add(order2);
     var crumb = new BreadCrumbViewModel
                     {Display = "Order Search", Title = "order search", Url = "/Order/Search"};
     model.BreadCrumbs.Add(crumb);
     return View("Search", model);
 }
        public void TestOrderViewModel()
        {
            OrderViewModel orderViewModel = new OrderViewModel();
            orderViewModel.Service = serviceFacade;
            OrderListDTO order = new OrderListDTO() {Id = 1};
            IList<OrderListDTO> orders = new List<OrderListDTO>() {order};
            Expect.Once.On(serviceFacade).Method("GetAllOrders").Will(Return.Value(orders));
            orderViewModel.LoadCommand.Command.Execute(null);

            Assert.AreEqual<int>(1, orderViewModel.Items.Count);
            Assert.AreEqual(order, orderViewModel.SelectedItem);
            Assert.AreEqual(Strings.OrderViewModel_DisplayName, orderViewModel.DisplayName);
        }
Example #10
0
 public ActionResult PlaceOrder(OrderViewModel vm)
 {
     var shipToId = SodaSession.ShipToId;
     if (vm.CreditCardExpDate != null)
     {
         var orderNumber = _productService.PlaceOrder(SodaSession.ShipToId.Value, vm.CreditCardNumber, vm.CreditCardExpDate.Value);
         if (orderNumber != null)
         {
             vm.OrderNumber = orderNumber.Value;
             return View(vm);
         }
     }
     return View();
 }
        public ActionResult GetOrder(int orderId)
        {
            var orderVm = new OrderViewModel()
            {
                //Address = "88 Coleman Parkway",
                ClientName = "Katherine Perkins",
                IsPaid = false,
                ItemName = "Exametazime",
                Quantity = 38,
                Subtotal = 297.72
            };

            return Json(orderVm, JsonRequestBehavior.AllowGet);
        }
        public OrderViewModel BeginOrderEdit(int orderID)
        {
            OrderDataAccessService orderDataAccessService = new OrderDataAccessService();
               OrderViewModel orderViewModel = new OrderViewModel();
               OrderCustomer orderCustomer = orderDataAccessService.GetOrder(orderID);
               orderCustomer.Order.OrderTotal = orderDataAccessService.GetOrderTotal(orderID);
               orderCustomer.Order.OrderTotalFormatted = orderCustomer.Order.OrderTotal.ToString("C");

               orderViewModel.Customer = orderCustomer.Customer;
               orderViewModel.Order = orderCustomer.Order;
               orderViewModel.Shippers = orderDataAccessService.GetShippers();
               orderViewModel.Order.ShipperName = orderCustomer.Shipper.CompanyName;

               return orderViewModel;
        }
        public override ActionResult Index(RenderModel model)
        {
            int orderIndex = 1;
            if (CurrentPage.GetProperty("orderIndex") != null)
                Int32.TryParse(CurrentPage.GetProperty("orderIndex").Value.ToString(), out orderIndex);

            OrderOperationStatus operationStatus = _ecommerceService.GetOrder(orderIndex);
            if (operationStatus.Status)
            {
                var viewOrder = new OrderViewModel(model);
                viewOrder.InjectFrom(operationStatus.Order);
                viewOrder.Status = operationStatus.Status;
                viewOrder.Message = operationStatus.Message;
                return CurrentTemplate(viewOrder);
            }
            return ReturnErrorView(operationStatus, model);
        }
        public OrderViewModel BeginOrderEntry(OrderViewModel orderViewModel)
        {
            // OrderViewModel orderViewModel = new OrderViewModel();

            CustomerDataAccessService customerDataAccessService = new CustomerDataAccessService();
               // Customer customer = customerDataAccessService.GetCustomerInformation(orderViewModel.Customer.CustomerID);

            orderViewModel.Customer = customerDataAccessService.GetCustomerInformation(orderViewModel.Customer.CustomerID);

            OrderDataAccessService orderDataAccessService = new OrderDataAccessService();
            orderViewModel.Shippers = orderDataAccessService.GetShippers();

               // OrderBusinessService orderBusinessService = new OrderBusinessService();
            //orderViewModel.Order = orderBusinessService.InitializeOrderHeader(customer);

            return orderViewModel;
        }
Example #15
0
        public async Task<IHttpActionResult> Get(long id)
        {
            var user = await _authRepository.FindUser(HttpContext.Current.User as ClaimsPrincipal);
            var entity = await _orderRepository.GetAsync(id);
            if (entity == null)
            {
                return NotFound();
            }
            if (entity.UserId != user.Id)
            {
                return StatusCode(HttpStatusCode.Forbidden);
            }

            var viewModel = new OrderViewModel();
            viewModel.Create(entity);

            return Ok(viewModel);
        }
		public RmaRequestViewModel(
			IViewModelsFactory<ICreateRefundViewModel> wizardVmFactory,
			IViewModelsFactory<IOrderViewModel> orderVmFactory,
			IAuthenticationContext authContext,
			RmaRequest rmaRequestItem,
			OrderViewModel parentViewModel, OrderClient client)
		{
			_wizardVmFactory = wizardVmFactory;
			_orderVmFactory = orderVmFactory;
			CurrentRmaRequest = rmaRequestItem;
			_authContext = authContext;
			_parentViewModel = parentViewModel;
			_orderClient = client;

			RmaRequestWizardDialogInteractionRequest = new InteractionRequest<Confirmation>();

			RmaRequestCancelCommand = new DelegateCommand(RaiseRmaRequestCancelInteractionRequest, () => CurrentRmaRequest.IsCancellable(client));
			RmaRequestCompleteCommand = new DelegateCommand(RaiseRmaRequestCompleteInteractionRequest, () => CurrentRmaRequest.IsCompletable(client));
			ExchangeOrderCreateCommand = new DelegateCommand(RaiseExchangeOrderCreateInteractionRequest, () => CurrentRmaRequest.IsAllowCreateExchangeOrder());
			ExchangeOrderViewCommand = new DelegateCommand(RaiseExchangeOrderViewInteractionRequest, () => CurrentRmaRequest.ExchangeOrder != null);
		}
Example #17
0
        public ActionResult Order(int id)
        {
            var model = new OrderViewModel();

            var userId = User.Identity.GetUserId();
            var order = orderService.Find(id);
            if (order.UserId != userId) return RedirectToAction("Index");
            Mapper.Map(order, model);
            foreach (var item in model.Items)
            {
                string optionsDisplay = "";
                var options = JsonConvert.DeserializeObject<OrderItemOption[]>(item.Options);
                foreach (var optionId in options.Select(o => o.Id))
                {
                    var option = optionService.Find(optionId);
                    if (option == null) continue;
                    optionsDisplay += string.Format("<strong>{0}</strong>: {1} ", option.Category.Name, option.Name);
                }
                item.OptionsDisplay = optionsDisplay;
            }

            return View(model);
        }
		public ShipmentViewModel(OrderClient client, IViewModelsFactory<ISplitShipmentViewModel> splitVmFactory, IViewModelsFactory<ILineItemAddViewModel> wizardLineItemVmFactory, IViewModelsFactory<ILineItemViewModel> lineItemVmFactory, OrderViewModel orderViewModel, Shipment shipmentItem, IOrderEntityFactory entityFactory, IRepositoryFactory<IPricelistRepository> repositoryFactory, PriceListClient priceListClient)
		{
			_orderClient = client;
			ParentViewModel = orderViewModel;
			_currentOrder = orderViewModel._innerModel;
			CurrentShipment = shipmentItem;
			_entityFactory = entityFactory;
			_repositoryFactory = repositoryFactory;
			_priceListClient = priceListClient;
			_lineItemVmFactory = lineItemVmFactory;
			_wizardLineItemVmFactory = wizardLineItemVmFactory;
			_splitVmFactory = splitVmFactory;

			CommonShipmentConfirmRequest = orderViewModel.CommonOrderCommandConfirmRequest;

			ReleaseShipmentCommand = new DelegateCommand(RaiseReleaseShipmentInteractionRequest, () => CurrentShipment.IsReleaseable(_currentOrder.InnerItem, client));
			CompleteShipmentCommand = new DelegateCommand(RaiseCompleteShipmentInteractionRequest, () => CurrentShipment.IsCompletable(_currentOrder.InnerItem, client));
			CancelShipmentCommand = new DelegateCommand(RaiseCancelShipmentInteractionRequest, () => CurrentShipment.IsCancellable(_currentOrder.InnerItem, client));
			AddLineItemCommand = new DelegateCommand(RaiseAddLineItemInteractionRequest, () => CurrentShipment.IsModifyable(_currentOrder.InnerItem));
			MoveLineItemCommand = new DelegateCommand<ShipmentItem>(RaiseMoveLineItemInteractionRequest, x => x != null && CurrentShipment.IsModifyable(_currentOrder.InnerItem));
			RemoveLineItemCommand = new DelegateCommand<ShipmentItem>(RaiseRemoveLineItemInteractionRequest, x => x != null && CurrentShipment.IsModifyable(_currentOrder.InnerItem));
			ViewLineItemDetailsCommand = new DelegateCommand<object>(RaiseViewLineItemDetailsInteractionRequest, x => x != null);
		}
        public ActionResult Edit(string id, OrderViewModel c)
        {
            double prices = 0;

            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    var data = iOrderRepositery.GetDetail(id);
                    if (data != null)
                    {
                        prices = data.Products.Sum(x => x.price);
                        if (c.orders == "[]" || c.Products.Count == 0)
                        {
                            ViewBag.Companies  = util.GetAllCompany();
                            ViewBag.Stores     = util.GetAllStores();
                            ViewBag.cities     = util.getCities();
                            ViewBag.TotalPrice = prices;
                            ModelState.AddModelError("", "Products Can't be Null");
                            return(View(c));
                        }
                        if (c.Products.Any(x => x.Quantity <= 0))
                        {
                            ViewBag.Companies  = util.GetAllCompany();
                            ViewBag.Stores     = util.GetAllStores();
                            ViewBag.cities     = util.getCities();
                            ViewBag.TotalPrice = prices;
                            ModelState.AddModelError("", "Products Can't be Negative");
                            return(View(c));
                        }
                        c.order_id = data.order_id;
                        c.Products = JsonConvert.DeserializeObject <List <Products> >(c.orders);
                        List <Tuple <int, bool> > res = iOrderRepositery.Update(c);
                        if (res.Any(x => x.Item2 == false && x.Item1 > 0))
                        {
                            ViewBag.Companies  = util.GetAllCompany();
                            ViewBag.Stores     = util.GetAllStores();
                            ViewBag.cities     = util.getCities();
                            ViewBag.TotalPrice = prices;
                            var    OutOfStock   = res.Where(x => x.Item2 == false);
                            var    listOfModels = c.Products.Where(x => OutOfStock.Select(i => i.Item1).Contains(x.modelId)).Select(x => new { x.model_name, x.com_Name });
                            string str          = "";
                            foreach (var item in listOfModels)
                            {
                                str = str + item.com_Name + " " + item.model_name + "\n";
                            }
                            ModelState.AddModelError("", "Following Product(s) is Out of Stock \n" + String.Join("/n", listOfModels));
                            return(View(c));
                        }
                        if (res.Any(x => x.Item2 == false && x.Item1 == 0))
                        {
                            return(View("Error"));
                        }
                        if (res.Any(x => x.Item2 == false && x.Item1 == -2))
                        {
                            ViewBag.Companies  = util.GetAllCompany();
                            ViewBag.Stores     = util.GetAllStores();
                            ViewBag.cities     = util.getCities();
                            ViewBag.TotalPrice = prices;
                            ModelState.AddModelError("", "Error in Payment Gatway! Sorry for inconvenience");
                            return(View(c));
                        }
                        return(RedirectToAction("Details", new
                        {
                            id = id
                        }));
                    }
                    ViewBag.Name = "Order";
                    return(View("ProductNotFound", id));
                }
                ViewBag.Companies  = util.GetAllCompany();
                ViewBag.Stores     = util.GetAllStores();
                ViewBag.cities     = util.getCities();
                ViewBag.TotalPrice = prices;
                return(View(c));
            }
            catch (Exception e)
            {
                ViewBag.Companies  = util.GetAllCompany();
                ViewBag.Stores     = util.GetAllStores();
                ViewBag.cities     = util.getCities();
                ViewBag.TotalPrice = prices;
                ModelState.AddModelError("", e.Message);
                return(View(c));
            }
        }
        public JsonResult OnPostCreate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            order.OrderID = orders.Count + 2;
            orders.Add(order);

            return(new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
Example #21
0
        public async Task Checkout_Calls_Service_And_Returns_Redirect()
        {
            //Arrange

            Mock <ICartService> mockCartService = new Mock <ICartService>();

            var cartItems = new List <(ProductViewModel product, int quantity)>()
            {
                (new ProductViewModel()
                {
                    Id = 1, Name = "Product_1", Brand = "Brand_1", Price = 11m, ImageUrl = "img1.png"
                }, 1),
                (new ProductViewModel()
                {
                    Id = 2, Name = "Product_2", Brand = "Brand_2", Price = 22m, ImageUrl = "img2.png"
                }, 1),
                (new ProductViewModel()
                {
                    Id = 3, Name = "Product_3", Brand = "Brand_3", Price = 33m, ImageUrl = "img3.png"
                }, 1)
            };

            mockCartService.Setup(x => x.TransformToViewModel()).Returns(() => new CartViewModel()
            {
                Items = cartItems
            });

            Mock <IOrderService> mockOrderService = new Mock <IOrderService>();

            List <OrderItemDTO> orderItemDTOs = new List <OrderItemDTO>()
            {
                new OrderItemDTO(1, new ProductDTO(1, "TestProduct_1", 1, 11m, "img1.url", null, null), 11m, 1),
                new OrderItemDTO(2, new ProductDTO(2, "TestProduct_2", 2, 22m, "img2.url", null, null), 22m, 1)
            };

            int      expectedValue = 36984;
            OrderDTO orderDTO      = new OrderDTO(expectedValue, new User(), "TestAdress", "TestPhone", DateTime.Now, orderItemDTOs);

            mockOrderService.Setup(x => x.CreateOrder(It.IsAny <CreateOrderModel>())).ReturnsAsync(() => orderDTO);

            OrderViewModel orderViewModel = new OrderViewModel()
            {
                Id = 11223344, UserId = "78134", Address = "TestAdress", Date = DateTime.Now, Phone = "TestPhone"
            };

            UserManager <User> mockUserManger = TestUserManager <User>();

            CartController cartController = new CartController(mockCartService.Object, mockUserManger);

            //Act

            IActionResult result = await cartController.Checkout(orderViewModel, mockOrderService.Object);

            //Assert

            RedirectToActionResult ret_RedirectToActionResult = Assert.IsType <RedirectToActionResult>(result); //Not derived type (why view result)

            Assert.Equal(nameof(cartController.OrderConfirmed), ret_RedirectToActionResult.ActionName);
            Assert.Null(ret_RedirectToActionResult.ControllerName);
            Assert.Equal(expectedValue, ret_RedirectToActionResult.RouteValues["id"]);
        }
        public JsonResult OnPostUpdate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Where(x => x.OrderID == order.OrderID).Select(x => order);

            return(new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
 public OrderViewModel CreateOrder(OrderViewModel orderViewModel)
 {
     CartDataAccessService cartDataAccessService = new CartDataAccessService();
        return cartDataAccessService.CreateOrder(orderViewModel);
 }
 public OpenOrderAddWindowCommand(OrderViewModel orderViewModel) : base(orderViewModel)
 {
 }
Example #25
0
 public void OnNavigatedFrom(NavigationContext navigationContext)
 {
     ViewModel = null;
 }
        /// <summary>
        /// 获取售票员订单
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="sellerId"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public TPageResult <OrderViewModel> GetOrderList(int page, int pageSize, int sellerId, string keyword)
        {
            var result = new TPageResult <OrderViewModel>();

            var total = 0;
            List <Tbl_Order> orderList = new List <Tbl_Order>();

            if (!string.IsNullOrEmpty(keyword))
            {
                var orderDetail = _orderDetailRepository.FirstOrDefault(a => a.CertificateNO == keyword);
                if (orderDetail == null)
                {
                    return(result.SuccessResult(null, 0));
                }
                orderList = _orderRepository.GetPageList(pageSize, page, out total,
                                                         a => a.TicketSource == (int)TicketSourceStatus.ScenicSpot && a.SellerId == sellerId && a.OrderNo == orderDetail.OrderNo
                                                         , a => a.CreateTime, false);
            }
            else
            {
                orderList = _orderRepository.GetPageList(pageSize, page, out total,
                                                         a => a.TicketSource == (int)TicketSourceStatus.ScenicSpot && a.SellerId == sellerId
                                                         , a => a.CreateTime, false);
            }

            if (orderList.Count <= 0)
            {
                return(result.SuccessResult(null, 0));
            }
            var orderNos     = orderList.Select(a => a.OrderNo).ToList();
            var orderDetails = _orderDetailRepository.GetAllList(a => orderNos.Contains(a.OrderNo));

            var orderViewList = new List <OrderViewModel>();

            foreach (var row in orderList)
            {
                OrderViewModel relist = new OrderViewModel();
                relist.OrderNo           = row.OrderNo;
                relist.Linkman           = row.Linkman;
                relist.IDCard            = row.IDCard;
                relist.CreateTime        = row.CreateTime;
                relist.Mobile            = row.Mobile;
                relist.ValidityDateStart = row.ValidityDateStart;
                relist.ValidityDateEnd   = row.ValidityDateEnd;
                relist.BookCount         = row.BookCount;
                relist.TotalAmount       = row.TotalAmount;
                relist.PayType           = row.PayType;
                //未过有效期 允许退票
                relist.CanRefund = row.ValidityDateEnd >= DateTime.Now.Date;
                relist.ListDtl   = new List <OdtDtl>();
                var details = orderDetails.Where(a => a.OrderNo == row.OrderNo).ToList();
                foreach (var ent in details)
                {
                    relist.IsPrintT = ent.TicketCategory == 1;
                    relist.IsTwo    = ent.TicketCategory == 2;
                    OdtDtl dtlEnt = new OdtDtl
                    {
                        OrderDetailId  = ent.OrderDetailId,
                        TicketCategory = ent.TicketCategory,
                        TicketName     = ent.TicketName,
                        Quantity       = ent.Quantity,
                        Price          = ent.Price,
                        TotalAmount    = (ent.Price * ent.Quantity),
                        CertificateNO  = ent.CertificateNO,
                        Mobile         = ent.Mobile,
                        IDCard         = ent.IDCard,
                        PrintCount     = ent.PrintCount,
                        OrderStatus    = ent.OrderStatus,
                        CanRefund      = ((ent.OrderStatus == (int)OrderDetailsDataStatus.Activate || ent.OrderStatus == (int)OrderDetailsDataStatus.IsTaken) && row.ValidityDateEnd >= DateTime.Now.Date)
                    };
                    relist.ListDtl.Add(dtlEnt);
                }
                orderViewList.Add(relist);
            }
            return(result.SuccessResult(orderViewList, total));
        }
Example #27
0
        public async Task<IHttpActionResult> Delete(long id, string username)
        {
            var user = await _authRepository.FindUser(username);
            var isAdmin = await _authRepository.IsAdmin(HttpContext.Current.User as ClaimsPrincipal);


            var entity = await _orderRepository.FindAsync(o => o.ProductId == id && o.UserId == user.Id);
            
            if (entity == null)
            {
                return NotFound();
            }

            var order = entity.FirstOrDefault();
            if(order == null)
            {
                return NotFound();
            }

            if (!isAdmin)
            {
                return StatusCode(HttpStatusCode.Forbidden);
            }

            _orderRepository.Remove(order);
            await _unitOfWork.CompleteAsync();
            var viewModel = new OrderViewModel();
            viewModel.Create(order);

            return Ok(viewModel);
        }
        public ActionResult Orders_Update([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            if (order != null && ModelState.IsValid)
            {
                // own create logic or use with sample data to test
                for (int i = 0; i < dbOrders.Count; i++)
                {
                    if (order.OrderID == dbOrders[i].OrderID)
                    {
                        dbOrders[i] = order;
                    }
                }
            }

            //Return any validation errors, if any.
            return(Json(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
        public ActionResult Orders_Create([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            if (order != null && ModelState.IsValid)
            {
                // own update logic or use with sample data to test

                var nextId = dbOrders.Count + 1;
                order.OrderID = nextId;
                dbOrders.Add(order);
            }

            //Return any validation errors, if any.
            return(Json(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
Example #30
0
        public OrderViewModel poGetOrderbyId(int Id)
        {
            tOrder         item  = dbContext.tOrders.FirstOrDefault(p => p.OrderId == Id);
            OrderViewModel Order = new OrderViewModel();

            Order.oAddress   = item.oAddress;
            Order.oCheck     = item.oCheck;
            Order.oCheckDate = item.oCheckDate;

            Order.oDate          = item.oDate.Date;
            Order.oDeliverDate   = item.oDeliverDate;
            Order.oEmployeeId    = item.oEmployeeId;
            Order.OrderId        = item.OrderId;
            Order.sWarehouseName = item.tWarehouseName.WarehouseName;
            Order.seName         = item.tEmployee.eName;
            Order.scName         = item.tCustomer.cName;
            int receivedM(int PayId)
            {
                var cashList = from tp in dbContext.tOrderPays
                               where tp.oPayType == PayId && tp.oOrderId == Id
                               select tp.oPayment;
                int cashTotal = 0;

                foreach (var cashItem in cashList)
                {
                    cashTotal = (int)cashItem + cashTotal;
                }
                return(cashTotal);
            }

            Order.cash    = receivedM(1);
            Order.card    = receivedM(2);
            Order.voucher = receivedM(3);
            int receivedTotal = 0;

            for (int i = 1; i < 4; i++)
            {
                receivedTotal += receivedM(i);
            }
            Order.received = receivedTotal;

            var receivableMoney = from tp in dbContext.tOrderDetails
                                  where tp.oOrderId == item.OrderId
                                  select tp.oProductQty * tp.tProduct.pPrice;
            int receivableTotal = 0;

            foreach (var receivableM in receivableMoney)
            {
                receivableTotal += (int)receivableM;
            }
            Order.originalPrice = receivableTotal;
            if (item.oPromotionId != null)
            {
                Order.receivable    = receivableTotal - Convert.ToInt32(item.tPromotion.pDiscount);
                Order.PromotionName = item.tPromotion.PromotionName;
                Order.pDiscount     = Convert.ToInt32(item.tPromotion.pDiscount);
            }
            else
            {
                Order.receivable    = receivableTotal;
                Order.PromotionName = "無參與折扣活動";
                Order.pDiscount     = 0;
            }
            List <AccountOrderDetailViewModel> orderDetails = new List <AccountOrderDetailViewModel>();
            List <tOrderDetail> orderDetailList             = dbContext.tOrderDetails.Where(od => od.oOrderId == Id).ToList();

            foreach (var detail in orderDetailList)
            {
                AccountOrderDetailViewModel accountOrderdetail = new AccountOrderDetailViewModel();
                tProduct product = dbContext.tProducts.Where(p => p.ProductId == detail.oProductId).FirstOrDefault();
                accountOrderdetail.ProductNum   = product.pNumber;
                accountOrderdetail.ProductName  = product.pName;
                accountOrderdetail.ProductPrice = product.pPrice;
                accountOrderdetail.oProductQty  = detail.oProductQty;
                accountOrderdetail.oNote        = detail.oNote;
                orderDetails.Add(accountOrderdetail);
            }
            Order.orderDetailViews = orderDetails;
            return(Order);
        }
Example #31
0
        public List <OrderViewModel> GetOrderAllByEmp(int EmployeeId)
        {
            List <tOrder>         order     = dbContext.tOrders.OrderByDescending(o => o.oDate).Where(o => o.oEmployeeId == EmployeeId).ToList();
            List <OrderViewModel> orderlist = new List <OrderViewModel>();

            foreach (tOrder item in order)
            {
                OrderViewModel Order = new OrderViewModel();
                Order.oAddress = item.oAddress;
                Order.oCheck   = item.oCheck;
                if (item.oCheckDate != null)
                {
                    Order.oCheckDate = item.oCheckDate.Value.Date;
                }


                Order.oDate = item.oDate.Date;
                //if(item.oDeliverDate)
                //Order.oDeliverDate = item.oDeliverDate.Value.Date;
                Order.OrderId = item.OrderId;

                Order.sWarehouseName = item.tWarehouseName.WarehouseName;
                Order.seName         = item.tEmployee.eName;
                Order.scName         = item.tCustomer.cName;
                var note = item.cNote;
                if (note != null)
                {
                    if (note.Length > 10)
                    {
                        Order.cNote = note.Substring(0, 10) + "...";
                    }
                    else
                    {
                        Order.cNote = note;
                    }
                }
                //變數 - 觀察付了多少錢
                var receivedMoney = from tP in dbContext.tOrderPays
                                    where tP.oOrderId == item.OrderId
                                    select tP.oPayment;
                //已收到
                int receivedTotal = 0;
                foreach (var receivedM in receivedMoney)
                {
                    receivedTotal = (int)receivedM + receivedTotal;
                }

                Order.received = receivedTotal;
                //應收款
                var receivableMoney = from tp in dbContext.tOrderDetails
                                      where tp.oOrderId == item.OrderId
                                      select tp.oProductQty * tp.tProduct.pPrice;
                //全額
                int receivableTotal = 0;

                foreach (var receivableM in receivableMoney)
                {
                    receivableTotal += (int)receivableM;
                }
                //折扣
                if (item.oPromotionId != null)
                {
                    tPromotion promotion = dbContext.tPromotions.Where(p => p.PromotionId == item.oPromotionId).FirstOrDefault();

                    if (promotion.PromotionName.Length > 7)
                    {
                        Order.PromotionName = promotion.PromotionName.Substring(0, 6) + ".";
                    }
                    else
                    {
                        Order.PromotionName = promotion.PromotionName;
                    }

                    //Order.PromotionName = promotion.PromotionName;
                    Order.pDiscount  = Convert.ToInt32(item.tPromotion.pDiscount);
                    receivableTotal -= Convert.ToInt32(item.tPromotion.pDiscount);
                }

                Order.receivable = receivableTotal;
                //應付款額-收款
                var surplus = receivableTotal - receivedTotal;
                Order.surplus = surplus;
                if (item.oCheck != null)
                {
                    Order.htmlName = "tr_hidden1";
                }
                else if (surplus <= 0)
                {
                    Order.htmlName = "tr_hidden2";
                }
                else
                {
                    Order.htmlName = "tr_hidden3";
                }
                List <AccountOrderDetailViewModel> detailViewModels = new List <AccountOrderDetailViewModel>();
                List <tOrderDetail> detailLists = dbContext.tOrderDetails.Where(od => od.oOrderId == item.OrderId).ToList();
                foreach (tOrderDetail itemdetail in detailLists)
                {
                    AccountOrderDetailViewModel detail = new AccountOrderDetailViewModel();
                    tProduct product = dbContext.tProducts.Where(p => p.ProductId == itemdetail.oProductId).FirstOrDefault();
                    detail.ProductNum   = product.pNumber;
                    detail.ProductName  = product.pName;
                    detail.ProductPrice = product.pPrice;
                    detail.oProductQty  = itemdetail.oProductQty;
                    detail.oNote        = itemdetail.oNote;
                    detailViewModels.Add(detail);
                }
                Order.orderDetailViews = detailViewModels;
                orderlist.Add(Order);
            }
            return(orderlist);
        }
        public ActionResult Index(OrderHistoryPage currentPage)
        {
            var purchaseOrders = OrderContext.Current.GetPurchaseOrders(_customerContext.CurrentContactId)
                                 .OrderByDescending(x => x.Created)
                                 .ToList();

            var viewModel = new OrderHistoryViewModel
            {
                CurrentPage     = currentPage,
                Orders          = new List <OrderViewModel>(),
                CurrentCustomer = _customerService.GetCurrentContact()
            };

            foreach (var purchaseOrder in purchaseOrders)
            {
                // Assume there is only one form per purchase.
                var form = purchaseOrder.GetFirstForm();

                var billingAddress = form.Payments.FirstOrDefault() != null?form.Payments.First().BillingAddress : new OrderAddress();

                var orderViewModel = new OrderViewModel
                {
                    PurchaseOrder = purchaseOrder,
                    Items         = form.GetAllLineItems().Select(lineItem => new OrderHistoryItemViewModel
                    {
                        LineItem = lineItem,
                    }).GroupBy(x => x.LineItem.Code).Select(group => group.First()),
                    BillingAddress    = _addressBookService.ConvertToModel(billingAddress),
                    ShippingAddresses = new List <AddressModel>()
                };

                foreach (var orderAddress in form.Shipments.Select(s => s.ShippingAddress))
                {
                    var shippingAddress = _addressBookService.ConvertToModel(orderAddress);
                    orderViewModel.ShippingAddresses.Add(shippingAddress);
                    orderViewModel.OrderGroupId = purchaseOrder.OrderGroupId;
                }

                if (!string.IsNullOrEmpty(purchaseOrder[Constants.Quote.QuoteStatus]?.ToString()) &&
                    (purchaseOrder.Status == OrderStatus.InProgress.ToString() || purchaseOrder.Status == OrderStatus.OnHold.ToString()))
                {
                    orderViewModel.QuoteStatus = purchaseOrder[Constants.Quote.QuoteStatus].ToString();
                    DateTime quoteExpireDate;
                    DateTime.TryParse(purchaseOrder[Constants.Quote.QuoteExpireDate].ToString(), out quoteExpireDate);
                    if (DateTime.Compare(DateTime.Now, quoteExpireDate) > 0)
                    {
                        orderViewModel.QuoteStatus = Constants.Quote.QuoteExpired;
                        try
                        {
                            // Update order quote status to expired
                            purchaseOrder[Constants.Quote.QuoteStatus] = Constants.Quote.QuoteExpired;
                            _orderRepository.Save(purchaseOrder);
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetLogger(GetType()).Error("Failed to update order status to Quote Expired.", ex.StackTrace);
                        }
                    }
                }

                viewModel.Orders.Add(orderViewModel);
            }

            viewModel.OrderDetailsPageUrl =
                UrlResolver.Current.GetUrl(_contentLoader.Get <StartPage>(ContentReference.StartPage).OrderDetailsPage);

            return(View(viewModel));
        }
Example #33
0
        protected ActionResult StoreEntity(OrderViewModel vm, string redirectButton)
        {
            bool persist = string.IsNullOrEmpty(redirectButton);
            try
            {
                if (ModelState.IsValid && persist)
                {
                    Service.StoreOrder(vm.Model);

                    // Finish Action and go back to Index
                    RemoveViewModelFromTempData<OrderViewModel>();
                    RemoveViewModelFromTempData<OrderDetailViewModel>(typeof(OrderDetailController).FullName);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Error", ex);
            }

            // Finish Action without saving
            StoreViewModelToTempData(vm);
            StoreViewModelToTempData(vm.OrderDetails, typeof(OrderDetailController).FullName);

            if (persist)
                return View(vm);
            else
                return Redirect(redirectButton);
        }
Example #34
0
 public Orders()
 {
     InitializeComponent();
     BindingContext = _viewModel = new OrderViewModel();
 }
Example #35
0
        private bool NeedsRefresh(OrderViewModel vm, int id)
        {
            // True when Id changed
            if (vm?.Model?.Id != id) return true;

            // True when coming from other Controller
            if (ReferrerControllerName == "Order" && ReferrerActionName != "Index") return false;
            if (ReferrerControllerName == "OrderDetail") return false;
            return true;
        }
Example #36
0
        public void Update(OrderViewModel OrderViewModel)
        {
            var updateCommand = _mapper.Map <UpdateOrderCommand>(OrderViewModel);

            Bus.SendCommand(updateCommand);
        }
Example #37
0
        public async Task <string> PrepareOrderForAuthenticatedCustomer([FromBody] OrderViewModel orderDetails)
        {
            DateTime startTime = DateTime.Now;

            if (!ModelState.IsValid)
            {
                List <string> errorList = (from item in ModelState.Values
                                           from error in item.Errors
                                           select error.ErrorMessage).ToList();
                string errorMessage = JsonConvert.SerializeObject(errorList);
                throw new PartnerDomainException(ErrorCode.InvalidInput).AddDetail("ErrorMessage", errorMessage);
            }

            orderDetails.CustomerId = Principal.PartnerCenterCustomerId;
            orderDetails.OrderId    = Guid.NewGuid().ToString();
            string operationDescription = string.Empty;

            // Validate & Normalize the order information.
            OrderNormalizer orderNormalizer = new OrderNormalizer(ApplicationDomain.Instance, orderDetails);

            switch (orderDetails.OperationType)
            {
            case CommerceOperationType.AdditionalSeatsPurchase:
                operationDescription = Resources.AddSeatsOperationCaption;
                orderDetails         = await orderNormalizer.NormalizePurchaseAdditionalSeatsOrderAsync().ConfigureAwait(false);

                break;

            case CommerceOperationType.NewPurchase:
                operationDescription = Resources.NewPurchaseOperationCaption;
                orderDetails         = await orderNormalizer.NormalizePurchaseSubscriptionOrderAsync().ConfigureAwait(false);

                break;

            case CommerceOperationType.Renewal:
                operationDescription = Resources.RenewOperationCaption;
                orderDetails         = await orderNormalizer.NormalizeRenewSubscriptionOrderAsync().ConfigureAwait(false);

                break;
            }

            // prepare the redirect url so that client can redirect to payment gateway.
            string redirectUrl = string.Format(CultureInfo.InvariantCulture, "{0}/#ProcessOrder?ret=true", Request.RequestUri.GetLeftPart(UriPartial.Authority));

            // Create the right payment gateway to use for customer oriented payment transactions.
            IPaymentGateway paymentGateway = await CreatePaymentGateway(operationDescription, orderDetails.CustomerId).ConfigureAwait(false);

            // execute and get payment gateway action URI.
            string generatedUri = await paymentGateway.GeneratePaymentUriAsync(redirectUrl, orderDetails).ConfigureAwait(false);

            // Capture the request for the customer summary for analysis.
            Dictionary <string, string> eventProperties = new Dictionary <string, string> {
                { "CustomerId", orderDetails.CustomerId }, { "OperationType", orderDetails.OperationType.ToString() }
            };

            // Track the event measurements for analysis.
            Dictionary <string, double> eventMetrics = new Dictionary <string, double> {
                { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
            };

            ApplicationDomain.Instance.TelemetryService.Provider.TrackEvent("api/order/prepare", eventProperties, eventMetrics);

            return(generatedUri);
        }
        public ActionResult Order(OrderViewModel model)
        {
            for (int i = 0; i < model.Products.Count; i++)
            {
                this.shoppingService.OrderProductBySize(model.Products[i].Id, model.Products[i].Sizes.FirstOrDefault().Value);
            }

            this.HttpContext.Response.Cache.SetNoStore();
            var userId = this.HttpContext.User.Identity.GetUserId();
            this.shoppingService.AddOrder(model.TotalPrice, userId, this.Mapper.Map<List<Product>>(model.Products),
                Request.Cookies[UserIdCart].Value);

            return Redirect("/orders/index");
        }
        public ActionResult Orders_Destroy([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            if (order != null)
            {
                // own destroy logic or use with sample data to test

                for (int i = 0; i < dbOrders.Count; i++)
                {
                    if (order.OrderID == dbOrders[i].OrderID)
                    {
                        dbOrders.Remove(dbOrders[i]);
                        break;
                    }
                }
            }

            //Return any validation errors, if any.
            return(Json(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
        public JsonResult OnPostDestroy([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Remove(orders.First(x => x.OrderID == order.OrderID));

            return(new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState)));
        }
 public void SetOrderWindowReference(OrderViewModel orderViewModel)
 {
     _orderViewModel = orderViewModel;
 }
Example #42
0
        public ActionResult QrOrder()
        {
            var cart         = (List <ShoppingCartViewModel>)Session[CommonConstants.ShoppingCartSession];
            var orderDetails = new List <OrderDetail>();

            if (Session["GoToQROrder"] == null || cart.Count == 0)
            {
                return(RedirectToAction("QrScanner"));
            }
            Session["GoToQROrder"] = null;
            var user = _userManager.GetUserById(User.Identity.GetUserId());

            var orderViewModel = new OrderViewModel
            {
                CustomerAddress = user.Address,
                CustomerEmail   = user.Email,
                CustomerMobile  = user.PhoneNumber,
                CustomerId      = user.Id,
                CustomerMessage = "Thanh toán bằng QR Code",
                PaymentMethod   = "QR",
                CustomerName    = user.FullName,
                CreatedDate     = DateTime.Now,
                CreatedBy       = user.UserName,
                PaymentStatus   = 0
            };

            if (orderViewModel.CustomerAddress == null)
            {
                orderViewModel.CustomerAddress = "Địa chỉ";
            }
            var  order    = new Order();
            bool isEnough = true;

            order.UpdateOrder(orderViewModel);

            foreach (var item in cart)
            {
                var detail = new OrderDetail
                {
                    ProductID = item.ProductId,
                    Quantity  = item.Quantity,
                    Price     = item.Product.Price
                };
                orderDetails.Add(detail);
                isEnough = _productService.SellingProduct(item.ProductId, item.Quantity);
            }
            if (!isEnough)
            {
                return(RedirectToAction("CompleteOrder", new OrderResultViewModel {
                    Result = false, Message = "Sản phẩm đã hết hàng"
                }));
            }

            var totalAmountSession = orderDetails.Sum(x => x.Quantity * x.Price);

            var totalAmountInt = decimal.ToInt32(totalAmountSession);

            var myAccount = _userManager.GetUserById(User.Identity.GetUserId());

            myAccount.Coin -= totalAmountInt;

            _orderService.Add(ref order, orderDetails);
            _orderService.SaveChanges();

            Session["totalAmount"] = orderDetails.Sum(x => x.Quantity * x.Price).ToString();

            ApplySendHtmlOrder();
            DeleteCart();
            return(RedirectToAction("CompleteOrder", new OrderResultViewModel {
                Result = true
            }));
        }
Example #43
0
        public async Task <SubscriptionsSummary> ProcessOrderForUnAuthenticatedCustomer(string customerId, string paymentId, string payerId)
        {
            DateTime startTime = DateTime.Now;

            customerId.AssertNotEmpty(nameof(customerId));
            paymentId.AssertNotEmpty(nameof(paymentId));
            payerId.AssertNotEmpty(nameof(payerId));

            BrandingConfiguration branding = await ApplicationDomain.Instance.PortalBranding.RetrieveAsync().ConfigureAwait(false);

            CustomerViewModel customerRegistrationInfoPersisted = await ApplicationDomain.Instance.CustomerRegistrationRepository.RetrieveAsync(customerId).ConfigureAwait(false);

            Customer newCustomer = new Customer()
            {
                CompanyProfile = new CustomerCompanyProfile()
                {
                    Domain = customerRegistrationInfoPersisted.DomainName,
                },
                BillingProfile = new CustomerBillingProfile()
                {
                    Culture     = customerRegistrationInfoPersisted.BillingCulture,
                    Language    = customerRegistrationInfoPersisted.BillingLanguage,
                    Email       = customerRegistrationInfoPersisted.Email,
                    CompanyName = customerRegistrationInfoPersisted.CompanyName,

                    DefaultAddress = new Address()
                    {
                        FirstName    = customerRegistrationInfoPersisted.FirstName,
                        LastName     = customerRegistrationInfoPersisted.LastName,
                        AddressLine1 = customerRegistrationInfoPersisted.AddressLine1,
                        AddressLine2 = customerRegistrationInfoPersisted.AddressLine2,
                        City         = customerRegistrationInfoPersisted.City,
                        State        = customerRegistrationInfoPersisted.State,
                        Country      = customerRegistrationInfoPersisted.Country,
                        PostalCode   = customerRegistrationInfoPersisted.ZipCode,
                        PhoneNumber  = customerRegistrationInfoPersisted.Phone,
                    }
                }
            };

            // Register customer
            newCustomer = await ApplicationDomain.Instance.PartnerCenterClient.Customers.CreateAsync(newCustomer).ConfigureAwait(false);

            ResourceCollection <AgreementMetaData> agreements = await ApplicationDomain.Instance.PartnerCenterClient.AgreementDetails.GetAsync().ConfigureAwait(false);

            // Obtain reference to the Microsoft Customer Agreement.
            AgreementMetaData microsoftCloudAgreement = agreements.Items.FirstOrDefault(agr => agr.AgreementType.Equals("MicrosoftCustomerAgreement", StringComparison.InvariantCultureIgnoreCase));

            // Attest that the customer has accepted the Microsoft Customer Agreement (MCA).
            await ApplicationDomain.Instance.PartnerCenterClient.Customers[newCustomer.Id].Agreements.CreateAsync(
                new Agreement
            {
                DateAgreed     = DateTime.UtcNow,
                PrimaryContact = new PartnerCenter.Models.Agreements.Contact
                {
                    Email       = customerRegistrationInfoPersisted.Email,
                    FirstName   = customerRegistrationInfoPersisted.FirstName,
                    LastName    = customerRegistrationInfoPersisted.LastName,
                    PhoneNumber = customerRegistrationInfoPersisted.Phone
                },
                TemplateId = microsoftCloudAgreement.TemplateId,
                Type       = "MicrosoftCustomerAgreement",
                UserId     = branding.AgreementUserId
            }).ConfigureAwait(false);

            string newCustomerId = newCustomer.CompanyProfile.TenantId;

            CustomerViewModel customerViewModel = new CustomerViewModel()
            {
                AddressLine1     = newCustomer.BillingProfile.DefaultAddress.AddressLine1,
                AddressLine2     = newCustomer.BillingProfile.DefaultAddress.AddressLine2,
                City             = newCustomer.BillingProfile.DefaultAddress.City,
                State            = newCustomer.BillingProfile.DefaultAddress.State,
                ZipCode          = newCustomer.BillingProfile.DefaultAddress.PostalCode,
                Country          = newCustomer.BillingProfile.DefaultAddress.Country,
                Phone            = newCustomer.BillingProfile.DefaultAddress.PhoneNumber,
                Language         = newCustomer.BillingProfile.Language,
                FirstName        = newCustomer.BillingProfile.DefaultAddress.FirstName,
                LastName         = newCustomer.BillingProfile.DefaultAddress.LastName,
                Email            = newCustomer.BillingProfile.Email,
                CompanyName      = newCustomer.BillingProfile.CompanyName,
                MicrosoftId      = newCustomer.CompanyProfile.TenantId,
                UserName         = newCustomer.BillingProfile.Email,
                Password         = newCustomer.UserCredentials.Password,
                AdminUserAccount = newCustomer.UserCredentials.UserName + "@" + newCustomer.CompanyProfile.Domain
            };

            IPaymentGateway paymentGateway = PaymentGatewayConfig.GetPaymentGatewayInstance(ApplicationDomain.Instance, "ProcessingOrder");
            OrderViewModel  orderToProcess = await paymentGateway.GetOrderDetailsFromPaymentAsync(payerId, paymentId, string.Empty, string.Empty).ConfigureAwait(false);

            // Assign the actual customer Id
            orderToProcess.CustomerId = newCustomerId;

            CommerceOperations commerceOperation = new CommerceOperations(ApplicationDomain.Instance, newCustomerId, paymentGateway);
            await commerceOperation.PurchaseAsync(orderToProcess).ConfigureAwait(false);

            SubscriptionsSummary summaryResult = await GetSubscriptionSummaryAsync(newCustomerId).ConfigureAwait(false);

            // Remove the persisted customer registration info.
            await ApplicationDomain.Instance.CustomerRegistrationRepository.DeleteAsync(customerId).ConfigureAwait(false);

            // Capture the request for the customer summary for analysis.
            Dictionary <string, string> eventProperties = new Dictionary <string, string> {
                { "CustomerId", orderToProcess.CustomerId }
            };

            // Track the event measurements for analysis.
            Dictionary <string, double> eventMetrics = new Dictionary <string, double> {
                { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
            };

            ApplicationDomain.Instance.TelemetryService.Provider.TrackEvent("api/order/NewCustomerProcessOrder", eventProperties, eventMetrics);

            summaryResult.CustomerViewModel = customerViewModel;

            return(summaryResult);
        }
Example #44
0
        /// <summary>
        /// 刷新客显
        /// </summary>
        public void RefreshPM()
        {
            OrderViewModel viewModel = this.DataContext as OrderViewModel;

            viewModel.RefreshPM();
        }
        public ActionResult CheckoutReview()
        {
            int CustomerID = 0;
            string ErrorMessage = "";
            string retMsg = "";
            string token = "";
            string PayerID = "5678912340";
            NVPCodec decoder = new NVPCodec();
            token = Session["token"].ToString();
            OrderViewModel orderViewModel = new OrderViewModel();
            NVPAPICaller payPalCaller = new NVPAPICaller();
            CustomerDataAccessService customerDataAccessService = new CustomerDataAccessService();
            var Cart = ShoppingCartActions.GetCart();

            string CartID = Cart.ShoppingCartId;
            orderViewModel.Order.CartID = CartID;

            bool ret = payPalCaller.GetCheckoutDetails(token, ref PayerID, ref decoder, ref retMsg);
            if (ret)
            {
                Session["payerId"] = PayerID;
                CustomerID = customerDataAccessService.GetCustomerIdNumber(User.Identity.Name);
                orderViewModel.Order.CustomerID = CustomerID;
                orderViewModel.Order.OrderDate = Convert.ToDateTime(decoder["TIMESTAMP"].ToString());
                orderViewModel.Order.UserName = User.Identity.Name;
                orderViewModel.Order.FirstName = decoder["FIRSTNAME"].ToString();
                orderViewModel.Order.LastName = decoder["LASTNAME"].ToString();
                orderViewModel.Order.SheepToStreet = decoder["SHIPTOSTREET"].ToString();
                orderViewModel.Order.ShipCity = decoder["SHIPTOCITY"].ToString();
                orderViewModel.Order.ShipToState = decoder["SHIPTOSTATE"].ToString();
                orderViewModel.Order.ShipPostalCode = decoder["SHIPTOZIP"].ToString();
                orderViewModel.Order.ShipCountry = decoder["SHIPTOCOUNTRYCODE"].ToString();
                orderViewModel.Order.Email = decoder["EMAIL"].ToString();
                orderViewModel.Order.OrderTotal = Convert.ToDouble(decoder["AMT"].ToString());
                orderViewModel.Customer.CustomerID = CustomerID;

                // Verify total payment amount as set on CheckoutStart.aspx.
                try
                {
                    decimal paymentAmountOnCheckout = Convert.ToDecimal(Session["payment_amt"].ToString());
                    decimal paymentAmoutFromPayPal = Convert.ToDecimal(decoder["AMT"].ToString());
                    if (paymentAmountOnCheckout != paymentAmoutFromPayPal)
                    {
                        ErrorMessage = "Amount%20total%20mismatch.";
                        return RedirectToAction("CheckoutError", ErrorMessage);
                    }
                }
                catch (Exception)
                {
                    ErrorMessage = "Amount%20total%20mismatch.";
                    return RedirectToAction("CheckoutError", ErrorMessage);

                }
                //Process the order

                OrderApplicationService orderApplicationService = new OrderApplicationService();
                orderViewModel = orderApplicationService.CreateOrder(orderViewModel);
                orderViewModel = orderApplicationService.BeginOrderEntry(orderViewModel);
                Session["currentOrderId"] = orderViewModel.Order.OrderID;

            }
            else
            {
                RedirectToAction("CheckoutError", retMsg);
            }
            return View("CheckoutReview", orderViewModel);
        }
Example #46
0
 public static IOrder ConvertToOrderModel(this OrderViewModel orderViewModel) => OrderFactory.Create(orderViewModel);
 public void CreateOrder(OrderViewModel order)
 {
     _orderRepo.Insert(
         _mapper.Map <Order>(order)
         );
 }
        public ActionResult 會計審核()
        {
            OrderViewModel CheckOrder = new OrderViewModel();

            return(View(CheckOrder));
        }
        public OrderViewModel LoadOrderDetailProduct(List<HiLToysDataModel.OrderDetailProductResult> OrderDetailProductResult)
        {
            OrderViewModel orderViewModel = new OrderViewModel();

            orderViewModel.Order.OrderID = OrderDetailProductResult[0].OrderID;
            orderViewModel.Order.OrderDate = OrderDetailProductResult[0].OrderDate;

            OrderCustomer orderCustomer = new OrderCustomer();
            orderCustomer.Customer.CustomerID = OrderDetailProductResult[0].CustomerID;
            orderCustomer.Customer.FirstName = OrderDetailProductResult[0].FirstName;
            orderCustomer.Customer.LastName = OrderDetailProductResult[0].LastName;
            orderViewModel.Customer = orderCustomer.Customer;

            for (int i = 0;  i < OrderDetailProductResult.Count; i++)
            {
                orderViewModel.OrderDetailProducts[i].Products.ProductID = OrderDetailProductResult[i].ProductID;
                orderViewModel.OrderDetailProducts[i].Products.ProductName = OrderDetailProductResult[i].ProductName;
                orderViewModel.OrderDetailProducts[i].Products.QuantityPerUnit = OrderDetailProductResult[i].QuantityPerUnit;

                orderViewModel.OrderDetailProducts[i].Products.UnitPrice = OrderDetailProductResult[i].UnitPrice;
                orderViewModel.OrderDetailProducts[i].OrderDetail.Quantity = OrderDetailProductResult[i].Quantity;
                orderViewModel.OrderDetailProducts[i].OrderDetail.OrderDate = OrderDetailProductResult[i].OrderDate;

                orderViewModel.OrderDetailProducts[i].OrderDetail.Discount = OrderDetailProductResult[i].Discount;
            }

            return orderViewModel;
        }
Example #50
0
 public FormViewModel(BaseViewModel model)
 {
     Cart = model.Cart;
     Order = new OrderViewModel();
 }
 public StoreOrders()
 {
     InitializeComponent();
     BindingContext = orderVm = new OrderViewModel();
 }
Example #52
0
        private void RefreshOrderDetailViewModel(OrderViewModel vm, OrderDTO item)
        {
            var vmOrderDetail = GetViewModelFromTempData<OrderDetailViewModel>(typeof(OrderDetailController).FullName);

            if (vmOrderDetail != null && vmOrderDetail.LatestControllerAction != ControllerAction.None)
            {
                vm.OrderDetails = vmOrderDetail;
            }
            else
            {
                vm.OrderDetails = new OrderDetailViewModel(item.Details.ToList());
            }

            vm.OrderDetails.IsReadOnly = CurrentActionName == "Details";
            vm.OrderDetails.ReturnController = CurrentControllerName;
            vm.OrderDetails.ReturnAction = CurrentActionName;
            vm.OrderDetails.ReturnId = CurrentParameterId;
        }
Example #53
0
        public async Task <IEnumerable <OrderViewModel> > GetCancellations(UserProfile user, DateTime from, DateTime to, int shopId)
        {
            IEnumerable <Shop> shops = new List <Shop>();
            var orders    = new List <OrderViewModel>();
            var ordersDal = new List <Order>();

            var avl = shopsChecker.CheckAvailability(user, shopId);

            if (!avl.isCorrectShop)
            {
                return(new List <OrderViewModel>());
            }
            if (!avl.hasShop && avl.isAdmin)
            {
                shops = shopRepo.GetShopsByBusiness(user.business_id.Value);
            }
            else if (!avl.hasShop && !avl.isAdmin)
            {
                return(new List <OrderViewModel>());
            }
            else if (avl.hasShop)
            {
                shops = new List <Shop> {
                    shopRepo.GetById(shopId)
                };
            }

            if (shops == null || !shops.Any())
            {
                return(new List <OrderViewModel>());
            }

            foreach (var shop in shops)
            {
                ordersDal.AddRange(await ordersRepo.GetCancellationsByShopIdInDateRange(shop.id, from, to));
            }

            var orderGroups = ordersDal.OrderByDescending(p => p.report_date);

            foreach (var group in orderGroups)
            {
                var orderVm = new OrderViewModel
                {
                    id         = group.id,
                    reportDate = group.report_date
                };
                foreach (var item in group.OrderDetails)
                {
                    var prodDal = await productRepo.GetByIdAsync(item.prod_id);

                    var cost = costRepo.GetByProdAndShopIds(item.prod_id, shopId);
                    var prod = new OrderRowViewModel
                    {
                        image      = (await imgRepo.GetByIdAsync(item.prod_id))?.img_url_temp,
                        name       = prodDal.name,
                        price      = cost.value,
                        count      = item.count,
                        totalPrice = item.count * cost.value,
                        vendorCode = prodDal.attr1
                    };
                    prod.totalPrice = prod.price * prod.count;
                    orderVm.products.Add(prod);
                }
                orders.Add(orderVm);
            }
            return(orders);
        }
Example #54
0
 private void MarkOrderDetailChanges(OrderViewModel vm)
 {
     switch (vm.OrderDetails.LatestControllerAction)
     {
         case ControllerAction.Create:
             foreach (var ins in vm.OrderDetails.Items.Where(i => i.Id <= 0))
                 vm.Model.MarkChildForInsertion(ins);
             break;
         case ControllerAction.Edit:
             if (!string.IsNullOrEmpty(ReferrerParameterId))
                 vm.Model.MarkChildForUpdate(vm.OrderDetails.SelectedItem);
             break;
         case ControllerAction.Delete:
             foreach (var del in vm.OrderDetails.ItemsToDelete)
                 vm.Model.MarkChildForDeletion(del);
             break;
     }
 }
Example #55
0
 public ActionResult Save(OrderViewModel model)
 {
     db.Orders.Add(model.Order);
     db.SaveChanges();
     return(View("Create"));
 }
        public async Task <ActionResult> Create(OrderViewModel c)
        {
            try
            {
                if (c.orders == "[]" || c.Products.Count == 0)
                {
                    ViewBag.Companies = util.GetAllCompany();
                    ViewBag.Stores    = util.GetAllStores();
                    ViewBag.cities    = util.getCities();
                    ModelState.AddModelError("", "Products Can't be Null");
                    return(View(c));
                }
                if (c.Products.Any(x => x.Quantity <= 0))
                {
                    ViewBag.Companies = util.GetAllCompany();
                    ViewBag.Stores    = util.GetAllStores();
                    ViewBag.cities    = util.getCities();
                    ModelState.AddModelError("", "Products Can't be Negative");
                    return(View(c));
                }
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    var user = await userManager.GetUserAsync(User);

                    if (!(User.IsInRole("Admin") || User.IsInRole("Super Admin") || User.IsInRole("Employee")))
                    {
                        c.cus_name    = user.FullName;
                        c.cus_phone   = user.PhoneNumber;
                        c.orderStatus = Status.Pending;
                        if (user.CusRef != null)
                        {
                            if (c.CustRef != user.CusRef)
                            {
                                c.CustRef = (int)user.CusRef;
                            }
                        }
                        else
                        {
                            c.CustRef = util.GenerateCusRef();
                        }
                        user.CusRef = c.CustRef;
                        await userManager.UpdateAsync(user);
                    }
                    else
                    {
                        c.orderStatus = Status.Completed;
                        c.TakenBy     = user.Id;
                    }

                    List <Tuple <int, bool> > res = await iOrderRepositery.addOrder(c, Url);

                    if (res.Any(x => x.Item2 == false && x.Item1 > 0))
                    {
                        ViewBag.Companies = util.GetAllCompany();
                        ViewBag.Stores    = util.GetAllStores();
                        ViewBag.cities    = util.getCities();
                        var    OutOfStock   = res.Where(x => x.Item2 == false);
                        var    listOfModels = c.Products.Where(x => OutOfStock.Select(i => i.Item1).Contains(x.modelId)).Select(x => new { x.model_name, x.com_Name });
                        string str          = "";
                        foreach (var item in listOfModels)
                        {
                            str = str + item.com_Name + " " + item.model_name + "\n";
                        }
                        ModelState.AddModelError("", "Following Product(s) is Out of Stock /n" + String.Join("/n", listOfModels));
                        return(View(c));
                    }
                    else if (res.Any(x => x.Item2 == false && x.Item1 == -1))
                    {
                        ViewBag.Companies = util.GetAllCompany();
                        ViewBag.Stores    = util.GetAllStores();
                        ViewBag.cities    = util.getCities();
                        ModelState.AddModelError("", "Order Placed! Error in Updating Stock");
                        return(View(c));
                    }
                    else if (res.Any(x => x.Item2 == false && x.Item1 == -2))
                    {
                        ViewBag.Companies = util.GetAllCompany();
                        ViewBag.Stores    = util.GetAllStores();
                        ViewBag.cities    = util.getCities();
                        ModelState.AddModelError("", "Error in Payment Gatway");
                        return(View(c));
                    }

                    var id = res.Select(x => x.Item1).First();
                    if (!(User.IsInRole("Admin") || User.IsInRole("Super Admin") || User.IsInRole("Employee")))
                    {
                        c.order_id = id;
                        string str = await ViewToStringRenderer.RenderViewToStringAsync(HttpContext.RequestServices, $"~/Views/Template/OrderConfirmation.cshtml", c);

                        await _emailSender.SendEmailAsync(user.Email, "Order Confirmation", str);
                    }
                    string ID = protector.Protect(id.ToString());
                    return(RedirectToAction("Details", new { id = ID }));
                }
                ViewBag.Companies = util.GetAllCompany();
                ViewBag.Stores    = util.GetAllStores();
                ViewBag.cities    = util.getCities();
                return(View(c));
            }
            catch (Exception e)
            {
                ViewBag.Companies = util.GetAllCompany();
                ViewBag.Stores    = util.GetAllStores();
                ViewBag.cities    = util.getCities();
                ModelState.AddModelError("", e.Message);
                return(View(c));
            }
        }