Ejemplo n.º 1
0
        public ServiceResult <string> Create(OrderCreateModel model)
        {
            var result = new ServiceResult <string>();

            if (!ModelState.IsValid)
            {
                result.Code = ReasonCode.MISSING_REQUIRED_FIELDS;
                foreach (string error in ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)))
                {
                    result.Message += error + Environment.NewLine;
                }

                return(result);
            }

            var orderComponent = new OrderComponent();

            var merchantAccountId = this.GetMerchantAccountId();

            //兼容之前版本,没传入法币,则取商家设置的法币
            if (string.IsNullOrEmpty(model.FiatCurrency))
            {
                var merchant = new MerchantAccountComponent().GetById(merchantAccountId);
                model.FiatCurrency = merchant.FiatCurrency;
            }

            var orderNo = orderComponent.CreateOrder(merchantAccountId, model.FiatCurrency, model.CryptoId, model.Amount, model.PaymentType, model.UserToken, this.GetClientIPAddress());

            result.Data = orderNo;

            return(result);
        }
        public async Task <IActionResult> Post([FromBody] OrderCreateModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var newOrder = _mapper.Map <OrderCreateModel, Order>(model);

                    newOrder.UserId = CurrentUserId;

                    _repository.AddOrder(newOrder);
                    if (await _repository.SaveAllAsync())
                    {
                        newOrder = _repository.GetOrderByUserId(CurrentUserId, newOrder.Id);

                        await _trackOrderService.ProcessNewOder(newOrder);

                        var orderVm = _mapper.Map <Order, OrderViewModel>(newOrder);
                        return(Created($"/api/orders/{orderVm.OrderId}", orderVm));
                    }
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed to save a new order: {ex}");
            }

            return(BadRequest("Failed to save new order"));
        }
        /// <summary>
        /// Create a new order
        /// </summary>
        /// <param name="orderCreateModel"></param>
        /// <returns></returns>
        public async Task <Guid> Create(OrderCreateModel orderCreateModel)
        {
            var customer = await _customerAppService.GetById(orderCreateModel.CustomerId);

            var company = await _companyAppService.GetById(orderCreateModel.CompanyId);

            var paymentType = await _paymentTypeAppService.GetById(orderCreateModel.PaymentMethodId);

            var address = await _addressAppService.GetById(orderCreateModel.AddressId);

            if (paymentType == null || customer == null || company == null || address == null)
            {
                throw new Exception("An error has occurred please try again.");
            }

            //Generate the order
            OrderDto model = new OrderDto(orderCreateModel, customer, company, address, paymentType);

            try
            {
                await _smtpEmailSender.SendAsync(
                    to : "*****@*****.**",
                    subject : "You have a new task!",
                    body : $"A new task is assigned for you: <b>test</b>",
                    isBodyHtml : true);
            }
            catch (Exception exception)
            {
                throw exception;
            }

            //We return the id so we can redirect to the orderitem page.
            return(await _repository.InsertAndGetIdAsync(ObjectMapper.Map <Models.Order>(model)));
        }
Ejemplo n.º 4
0
        public async Task AddOrderAsync(OrderCreateModel model)
        {
            List <BookDTO> booksOrder = new List <BookDTO>();

            foreach (var bookId in model.BookOrderIds)
            {
                booksOrder.Add(new BookDTO()
                {
                    Id = bookId
                });
            }

            await _orderService.AddOrderAsync(new OrderDTO()
            {
                OrderBooks     = booksOrder,
                AppUserId      = (await _currentUser.GetCurrentUser(_httpContextAccessor.HttpContext)).Id,
                TimeOfDelivery = DateTime.Now.AddDays(3)
            });

            var basketId = (await _currentUser.GetCurrentUser(_httpContextAccessor.HttpContext)).BasketId;

            foreach (var bookId in model.BookOrderIds)
            {
                await _basketService.RemoveBasketBookAsync(basketId, bookId);
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> OrderCreate(OrderCreateModel order)
        {
            User user = await _userManager.GetUserAsync(User);

            _orderService.CreateOrder(order, user);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 6
0
        private Guid InnerCreateOrder(Guid customerId, OrderCreateModel order)
        {
            var rnd   = new Random(10000);
            var model = new OrderReadModel()
            {
                Goods    = order.Goods,
                ArriveAt = DateTime.UtcNow.AddDays(2),
                OrderId  = Guid.NewGuid(),
                Cost     = (decimal)rnd.NextDouble(),
                Currency = order.Currency
            };

            if (!Orders.ContainsKey(customerId))
            {
                Orders.Add(customerId, new List <OrderReadModel>()
                {
                    model
                });
            }
            else
            {
                Orders[customerId].Add(model);
            }

            return(model.OrderId);
        }
Ejemplo n.º 7
0
        public ActionResult CreateOrder([FromBody] OrderCreateModel gg)
        {
            // var userId = int.Parse(User.FindFirst("id").Value);
            // var order = _orderService.GetOrder(id);
            // List<OrderItem> items = null;
            var items = gg.Items.Select(item => new OrderItem {
                BookId = item.BookId, Quantity = item.Quantity
            })
                        .ToList();

            for (int i = 0; i < gg.Items.Count; i++)
            {
                _bookService.ChangeBookQuantity(gg.Items[i].BookId);
            }



            var f = _orderService.CreateOrder(new Order
            {
                UserId     = gg.UserId,
                OrderItems = items
            });

            return(Ok(f));
        }
Ejemplo n.º 8
0
        public void Create__ValidEditModel__Success()
        {
            const string noteText = "created note";

            var customerId = this.order.Customer.Id;

            var createModel = new OrderCreateModel
            {
                Note      = noteText,
                Type      = OrderType.NonStandard,
                OrderDate = DateTime.Now.AddMonths(1),
                PaymentInfoOrderedDate = DateTime.Now,
                Duration   = 123,
                CustomerId = customerId,
            };

            var crudResult = this.GetService().Create(createModel);
            int orderId    = crudResult.Data;

            var orderFromDb = this.nhSessionHelper.GetInNewSession <Order>(orderId);

            orderFromDb.ShouldNot(Be.Null);
            orderFromDb.Id.ShouldEqual(orderId);
            orderFromDb.Version.ShouldNot(Be.Empty);
            orderFromDb.Note.ShouldEqual(noteText);
        }
Ejemplo n.º 9
0
        public TResult PayOrder(OrderCreateModel order)
        {
            var result = new TResult();

            if (order.TicketItem.Count <= 0)
            {
                return(result.ErrorResult("请选择您要购买的产品"));
            }

            var userInfo  = _enterpriseUserService.LoginForSession();
            var orderInfo = new OrderInfoCreateModel
            {
                PayType        = order.PayType,
                UserId         = userInfo.UserId,
                ValidityDate   = order.ValidityDate,
                Mobile         = "",
                Linkman        = "",
                TicketCategory = (int)TicketCategoryStatus.QrCodePrintTicket,
                TicketSource   = (int)TicketSourceStatus.ScenicSpot,
                TicketItem     = order.TicketItem
            };

            List <int> productIds       = orderInfo.TicketItem.Select(a => a.TicketId).ToList();
            var        tbl_Tickets      = _ticketService.GetTickets(productIds);
            var        tbl_Order        = _orderService.AddOrder(orderInfo);
            var        tbl_OrderDetails = _orderDetailService.AddOrderDetails(orderInfo, tbl_Order);

            _orderService.UpdateOrder(tbl_Order, tbl_OrderDetails);
            var tbl_Ticket_Testings = _ticketTestingService.addTicketTestings(tbl_Order, tbl_OrderDetails);

            _ticketService.UpdateTicketBySellCount(tbl_Tickets, tbl_OrderDetails);
            try
            {
                _orderService.BeginTran();
                _orderService.Add(tbl_Order);
                _orderDetailService.Add(tbl_OrderDetails);
                _ticketTestingService.Add(tbl_Ticket_Testings);
                _saleLogService.Add(tbl_Order);
                _ticketService.Update(tbl_Tickets);
                //提交事物
                _orderService.CommitTran();
            }
            catch
            {
                _orderService.RollbackTran();
                return(result.ErrorResult());
            }

            //打印机打印
            if (order.IsPrint && !string.IsNullOrEmpty(order.PrintKey))
            {
                var isPrint = _printService.Print(tbl_Order.OrderNo, order.PrintKey);
                if (!isPrint.Success)
                {
                    return(result.ErrorResult("门票创建成功," + isPrint.Message));
                }
            }

            return(result.SuccessResult());
        }
        public CreatedOrderResult OrderCreateV2(OrderCreateModel obj)
        {
            ReasonStatusBal    _rsbal             = new ReasonStatusBal();
            CreatedOrderResult objCreateOrderData = new CreatedOrderResult();
            int flag = 0;
            Dictionary <string, int> returndata = new Dictionary <string, int>();

            returndata.Add("status", 0);

            try
            {
                System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
                string x_StateName    = string.Empty;
                string x_DistrictName = string.Empty;
                if (headers.Contains("state"))
                {
                    x_StateName = headers.GetValues("state").First().ToLower();
                }
                if (headers.Contains("district"))
                {
                    x_DistrictName = headers.GetValues("district").First().ToLower();
                }
                objCreateOrderData = _rsbal.OrderCreateV2(obj, x_StateName, x_DistrictName);
            }
            catch (Exception ex)
            {
                LogDal.ErrorLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name, ex.Message, obj.userid);
            }

            // string json = JsonConvert.SerializeObject(returndata);
            //HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
            //HttpContext.Current.Response.Write(json);
            return(objCreateOrderData);
        }
Ejemplo n.º 11
0
 public async Task PostToDatabaseAsync(OrderCreateModel order)
 {
     await _dbContext.Orders.AddAsync(new Order
     {
         Name    = order.Name,
         Address = order.Address
     });
 }
        public HttpResponseMessage Insert(OrderCreateModel orderCreateModel)
        {
            OrderDto orderDto = this.mapper.Map <OrderDto>(orderCreateModel);

            this.orderAppService.CreateNewOrder(orderDto);

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Post(OrderCreateModel orderCreateModel)
        {
            orderCreateModel.WebsiteId = this.WebsiteId;
            orderCreateModel.UserId    = this.UserId;
            await orderService.CreateAsync(orderCreateModel);

            return(Ok(new ApiResponse <OrderCreateModel>()));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Create new order
        /// </summary>
        /// <param name="orderCreateModel"></param>
        /// <returns></returns>
        public async Task CreateAsync(OrderCreateModel orderCreateModel)
        {
            var orderRepository   = unitOfWork.GetRepository <Order>();
            var cartRepository    = unitOfWork.GetRepository <Cart>();
            var productRepository = unitOfWork.GetRepository <Product>();
            var order             = mapper.Map <Order>(orderCreateModel);
            var carts             = (await cartRepository.GetAllAsync(x => x.UserId == orderCreateModel.UserId &&
                                                                      x.WebsiteId == orderCreateModel.WebsiteId &&
                                                                      !x.DeletedDate.HasValue)).ToList();

            //Prevent create order with empty cart
            if (!carts.Any())
            {
                throw new ValidationException(Constants.MessageResponse.CheckOutWithEmptyCartError);
            }

            foreach (var cart in carts)
            {
                var product = await productRepository.FindByAsync(
                    x => x.Id == cart.ProductId &&
                    x.Status == (int)Status.ACTIVE && x.WebsiteId == orderCreateModel.WebsiteId);

                if (product == null)
                {
                    throw new NotFoundException(string.Format(
                                                    Constants.MessageResponse.NotFoundError, nameof(Product), cart.ProductId));
                }

                if (product.Quantity < cart.Quantity)
                {
                    throw new ValidationException(string.Format(
                                                      Constants.MessageResponse.MissingInventoryData, nameof(Product), product.Name));
                }
                //create new order detail
                order.OrderDetail.Add(new OrderDetail
                {
                    ProductId = cart.ProductId,
                    Quantity  = cart.Quantity,
                    Price     = product.Price,
                    Discount  = product.Discount
                });

                //update quantity of product in inventory
                product.Quantity   -= cart.Quantity;
                product.UpdatedDate = DateTime.UtcNow;
                productRepository.Update(product);

                //remove cart
                cart.DeletedDate = DateTime.UtcNow;
                cartRepository.Update(cart);
            }

            order.Total       = order.OrderDetail.Sum(od => (od.Price * od.Quantity) * (1 - (od.Discount / 100)));
            order.Status      = (int)Status.ACTIVE;
            order.CreatedDate = DateTime.UtcNow;
            orderRepository.Add(order);
            await unitOfWork.CommitAsync();
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Post([FromBody] OrderCreateModel model)
        {
            var mapping = new Func <Order, Task <Order> >(async(entity) =>
            {
                entity.Name            = model.Name;
                entity.Description     = model.Description;
                entity.OrganizationId  = CurrentAccountOrganizationId;
                entity.CustomerName    = model.CustomerName;
                entity.CustomerPhone   = model.CustomerPhone;
                entity.CustomerAddress = model.CustomerAddress;
                entity.SolutionId      = model.SolutionId;
                entity.Data            = model.Data;

                var details = new List <OrderDetail>();
                if (model.Content != null && model.Content.Count > 0)
                {
                    model.Content.ForEach(item =>
                    {
                        var detail           = new OrderDetail();
                        detail.Id            = GuidGen.NewGUID();
                        detail.ProductSpecId = item.ProductSpecId;
                        detail.Num           = item.Num;
                        //detail.UnitPrice = item.UnitPrice;
                        detail.UnitPrice      = Math.Round(item.UnitPrice, 2, MidpointRounding.AwayFromZero);
                        detail.Remark         = item.Remark;
                        detail.Room           = item.Room;
                        detail.Owner          = item.Owner;
                        detail.CreatedTime    = DateTime.Now;
                        detail.ModifiedTime   = detail.CreatedTime;
                        detail.Creator        = CurrentAccountId;
                        detail.Modifier       = CurrentAccountId;
                        detail.OrganizationId = CurrentAccountOrganizationId;
                        details.Add(detail);
                    });
                }
                entity.OrderDetails = details;

                var customizedProducts = new List <OrderDetailCustomizedProduct>();
                if (model.CustomizedProduct != null && model.CustomizedProduct.Count > 0)
                {
                    model.CustomizedProduct.ForEach(item =>
                    {
                        var customiedProd  = new OrderDetailCustomizedProduct();
                        customiedProd.Id   = GuidGen.NewGUID();
                        customiedProd.Name = item.Name;
                        customiedProd.Icon = item.Icon;
                        customizedProducts.Add(customiedProd);
                    });
                }
                entity.CustomizedProducts = customizedProducts;


                return(await Task.FromResult(entity));
            });

            return(await _PostRequest(mapping));
        }
Ejemplo n.º 16
0
        public ActionResult Create(OrderCreateModel model)
        {
            try
            {
                var user = AccountHelper.GetLoginUserInfo(HttpContext.User.Identity);

                var order = new Order();
                if (AccountHelper.IsSuperAdmin(user))
                {
                    order.CustomerCode = Constants.SuperAdminDefaultCustomerCode;
                }
                else
                {
                    order.CustomerCode = AccountHelper.GetCustomerCode(user.CustomerCode);
                }
                order.ModelNo       = model.Shoe;
                order.ContainerType = model.ContainerType;
                order.SendDate      = Convert.ToDateTime(model.ETD).Date;
                order.BanderNo      = model.BundleNo;
                order.ContractNo    = model.ContractNo;
                order.Size1         = model.Size1;
                order.Size2         = model.Size2;
                order.Size3         = model.Size3;
                order.Size4         = model.Size4;
                order.Size5         = model.Size5;
                order.Size6         = model.Size6;
                order.Size7         = model.Size7;
                order.Size8         = model.Size8;
                order.Size9         = model.Size9;
                order.Size10        = model.Size10;
                order.Size11        = model.Size11;
                order.Size12        = model.Size12;
                order.Size13        = model.Size13;
                order.Size14        = model.Size14;
                order.Size15        = model.Size15;
                order.Size16        = model.Size16;
                order.Size17        = model.Size17;
                order.Size18        = model.Size18;
                order.Size19        = model.Size19;
                order.Size20        = model.Size20;

                string           message = OrderManager.Instance.Create(order, user.LoginName);
                OrderCreateModel createModel;
                createModel = TempData["editModel"] as OrderCreateModel;
                if (!String.IsNullOrEmpty(message))
                {
                    createModel.Message = message;
                    return(View(createModel));
                }
                return(RedirectToAction("index"));
            }
            catch (Exception ex)
            {
                TempData["Error"] = ex.ToString();
                return(View("Error"));
            }
        }
Ejemplo n.º 17
0
 public async Task <IActionResult> Post([FromBody] OrderCreateModel model)
 {
     _logger.LogInformation($"Create new videoGame : {HttpContext.Request.Query} ");
     if (await _service.CreateAsync(_mapper.Map <OrderDTO>(model)))
     {
         return(Ok());
     }
     return(BadRequest());
 }
Ejemplo n.º 18
0
        public JsonResult SubmitOrderByCart(string cartItemIds, long recieveAddressId, string couponIds, int integral = 0)
        {
            IEnumerable <long>     nums;
            IEnumerable <string[]> strArrays;
            OrderCreateModel       orderCreateModel = new OrderCreateModel();
            IOrderService          orderService     = ServiceHelper.Create <IOrderService>();

            orderCreateModel.PlatformType     = base.PlatformType;
            orderCreateModel.CurrentUser      = base.CurrentUser;
            orderCreateModel.ReceiveAddressId = recieveAddressId;
            orderCreateModel.Integral         = integral;
            char[]             chrArray = new char[] { ',' };
            IEnumerable <long> nums1    =
                from item in cartItemIds.Split(chrArray)
                select long.Parse(item);

            orderCreateModel.CartItemIds = nums1;
            IEnumerable <string> strs = null;

            if (!string.IsNullOrEmpty(couponIds))
            {
                strs = couponIds.Split(new char[] { ',' });
            }
            OrderCreateModel orderCreateModel1 = orderCreateModel;

            if (strs == null)
            {
                nums = null;
            }
            else
            {
                nums =
                    from p in strs
                    select long.Parse(p.Split(new char[] { '\u005F' })[0]);
            }
            orderCreateModel1.CouponIds = nums;
            OrderCreateModel orderCreateModel2 = orderCreateModel;

            if (strs == null)
            {
                strArrays = null;
            }
            else
            {
                strArrays =
                    from p in strs
                    select p.Split(new char[] { '\u005F' });
            }
            orderCreateModel2.CouponIdsStr = strArrays;
            List <OrderInfo>   orderInfos = orderService.CreateOrder(orderCreateModel);
            IEnumerable <long> array      = (
                from item in orderInfos
                select item.Id).ToArray();
            decimal num = orderInfos.Sum <OrderInfo>((OrderInfo item) => item.OrderTotalAmount);

            return(Json(new { success = true, orderIds = array, realTotalIsZero = num == new decimal(0) }));
        }
        public async Task <IActionResult> Post(OrderCreateModel model)
        {
            var createdOrder = await _orderService.CreateAsync(User.GetId(), model);

            var response  = new Response(createdOrder);
            var getParams = new { createdOrder.Id };

            return(CreatedAtAction(nameof(Get), getParams, response));
        }
Ejemplo n.º 20
0
 public JsonResult Create(OrderCreateModel data)
 {
     try {
         orderService.CreateOrder(data);
         return(Json(true));
     } catch {
         return(Json(false));
     }
 }
Ejemplo n.º 21
0
        /// <summary>
        /// 购物车方式提交的订单
        /// </summary>
        /// <param name="value">数据</param>
        private object SubmitOrderByCart(OrderSubmitOrderByCartModel value)
        {
            string cartItemIds      = value.cartItemIds;
            long   recieveAddressId = value.recieveAddressId;
            string couponIds        = value.couponIds;
            int    integral         = value.integral;

            bool   isCashOnDelivery = value.isCashOnDelivery;
            int    invoiceType      = value.invoiceType;
            string invoiceTitle     = value.invoiceTitle;
            string invoiceContext   = value.invoiceContext;
            //end
            string           orderRemarks = "";//value.orderRemarks;//订单备注
            OrderCreateModel model        = new OrderCreateModel();
            List <OrderInfo> infos        = new List <OrderInfo>();

            var orderService = ServiceProvider.Instance <IOrderService> .Create;
            IEnumerable <long> orderIds;

            model.PlatformType     = PlatformType.WeiXinSmallProg;
            model.CurrentUser      = CurrentUser;
            model.ReceiveAddressId = recieveAddressId;
            model.Integral         = integral;

            model.formId = value.formId;

            model.IsCashOnDelivery = isCashOnDelivery;
            model.Invoice          = (InvoiceType)invoiceType;
            model.InvoiceContext   = invoiceContext;
            model.InvoiceTitle     = invoiceTitle;
            //end
            CommonModel.OrderShop[] OrderShops = Newtonsoft.Json.JsonConvert.DeserializeObject <OrderShop[]>(value.jsonOrderShops);
            model.OrderShops   = OrderShops;//用户APP选择门店自提时用到,2.5版本未支持门店自提
            model.OrderRemarks = OrderShops.Select(p => p.Remark).ToArray();
            try
            {
                var cartItemIdsArr = cartItemIds.Split(',').Select(item => long.Parse(item)).ToArray();
                //根据购物车项补充sku数据
                var cartItems = CartApplication.GetCartItems(cartItemIdsArr);
                model.SkuIds = cartItems.Select(e => e.SkuId).ToList();
                model.Counts = cartItems.Select(e => e.Quantity).ToList();

                model.CartItemIds  = cartItemIdsArr;
                model.CouponIdsStr = OrderHelper.ConvertUsedCoupon(couponIds);

                var orders = orderService.CreateOrder(model);
                orderIds = orders.Select(item => item.Id).ToArray();
                decimal orderTotals = orders.Sum(item => item.OrderTotalAmount);

                return(Json(new { Status = "OK", Message = "提交成功", OrderId = string.Join(",", orderIds), OrderTotal = orderTotals }));
            }
            catch (HimallException he)
            {
                return(Json(new { Status = "NO", Message = he.Message }));
            }
        }
Ejemplo n.º 22
0
        public OrderProfile()
        {
            var t = new OrderCreateModel();

            this.CreateMap <OrderCreateModel, Order>()
            .ForMember(o => o.UserFrom, src => src.MapFrom(i => i.UserFrom))
            .ForMember(o => o.UserTo, src => src.MapFrom(i => i.UserTo))
            .ForMember(o => o.ProductId, src => src.MapFrom(i => i.ProductId))
            .ForMember(o => o.ProductCount, src => src.MapFrom(i => i.ProductCount));
        }
Ejemplo n.º 23
0
        public async Task <OrderResponseModel> CreateAsync(Guid employeeId, OrderCreateModel model)
        {
            var newOrder = _mapper.Map <Order>(model);

            newOrder.Employee = await _employeeService.FindAsync(employeeId);

            var createdOrder = await _orderService.CreateAsync(newOrder);

            return(_mapper.Map <OrderResponseModel>(createdOrder));
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Post([FromBody] OrderCreateModel orderCreateModel)
        {
            var responseModel = await _orderService.CreateOrderAsync(orderCreateModel);

            if (responseModel.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(Ok((OrderViewModel)responseModel.Data));
            }
            return(BadRequest(responseModel.Message));
        }
Ejemplo n.º 25
0
        public int OrderCreate(OrderCreateModel obj)
        {
            //int id = _rsdal.GetFarmerIdByMobile(mobile);
            // DataTable DT = Helper.Helper.ToDataTable(obj.Product);
            int flag = _rsdal.OrderCreate(obj.userid, obj.Farmer.FarmerId, obj.Farmer.FarmerName, obj.Farmer.FatherName, obj.Farmer.Mobile,
                                          obj.Farmer.StateId, obj.Farmer.DistrictId, obj.Farmer.BlockId, obj.Farmer.VillageId, obj.Farmer.OtherVillageName, obj.Farmer.Address,
                                          obj.DeliveryDate, obj.Lat, obj.Long, obj.ModeOfPayment);

            return(flag);
        }
Ejemplo n.º 26
0
        public IActionResult Order(int?productId, int?basketsCount)
        {
            if (!productId.HasValue)
            {
                ViewBag.BadRequestMessage = "Product Id is Null";
                return(View("BadRequest"));
            }
            OrderCreateModel productOrderModel = _orderService.GetOrderCreateModel(productId.Value, basketsCount.Value);

            return(View(productOrderModel));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public JsonResult PayOrder(OrderCreateModel order)
        {
            if (!ModelState.IsValid)
            {
                var message = ModelState.BuildErrorMessage();
                throw new SimpleBadRequestException(message);
            }
            var result = _orderFacadeService.PayOrder(order);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 28
0
        public async Task <IActionResult> PostOrder([FromBody] OrderCreateModel createModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var viewModel = await _orderService.CreateAsync(createModel);

            return(CreatedAtAction("GetOrder", new { id = viewModel?.Id }, viewModel));
        }
Ejemplo n.º 29
0
 public OrderCreateModel GetOrderCreateModel(int id, int basketsCount)
 {
     using (UnitOfWork unitOfWork = _unitOfWorkFactory.Create())
     {
         Product product = unitOfWork.Products.GetAllWithBrandsCategoriesAndOrders()
                           .FirstOrDefault(p => p.Id == id);
         OrderCreateModel orderCreateModel = Mapper.Map <OrderCreateModel>(product);
         orderCreateModel.Count = basketsCount;
         return(orderCreateModel);
     }
 }
Ejemplo n.º 30
0
        public void TestCreateAsync_WithEmptyCart_ShouldThrowValidationException()
        {
            var orderCreateModel = new OrderCreateModel
            {
                UserId      = 2,
                WebsiteId   = 1,
                Phone       = "0906322555",
                ShipAddress = "Ha Noi"
            };
            var ex = Assert.ThrowsAsync <ValidationException>(() => orderService.CreateAsync(orderCreateModel));

            Assert.AreEqual(MessageResponse.CheckOutWithEmptyCartError, ex.Message);
        }
        public ActionResult Add(OrderCreateModel model)
        {
            if (!this.ModelState.IsValid)
            {
                model.Categories = this.GetCategories();
                return this.View(model);
            }

            Order orderCreated = null;
            try
            {
                var customer = this.customerService.Create(model.Customer.Name, model.Customer.Phone, model.Customer.Email);
                var unit = this.unitService.Create(model.Unit.Brand, model.Unit.Model, model.Unit.SerialNumber, model.Unit.CategoryId);

                var order = new Order
                {
                    Customer = customer,
                    ProblemDescription = model.ProblemDescription,
                    Status = Status.Pending,
                    Unit = unit,
                    WarrantyStatus = model.WarrantyStatus,
                    WarrantyCard = model.WarrantyCard,
                    WarrantyDate = model.WarrantyDate,
                };

                this.orderService.Create(order);
                string publicCode = this.coder.Encode(order.Id, customer.Name);
                this.orderService.AddPublicId(order.Id, publicCode);
                orderCreated = order;
            }
            catch (Exception)
            {
                this.TempData["Error"] = "Order can not be created";
                this.Response.StatusCode = 400;
                model.Categories = this.GetCategories();
                return this.View(model);
            }

            this.TempData["Success"] = "Order created successfully";
            return this.RedirectToAction("AfterCreation", "ViewOrder", new { id = orderCreated.Id });
        }
        public ActionResult Index()
        {
            var model = new OrderCreateModel
            {
                Categories = this.GetCategories()
            };

            return this.View("Add", model);
        }