Пример #1
0
        private BaseResponse <bool> CheckGeneralPromotionRule(Promotion promotion, OrderAPIViewModel order)
        {
            if (order.BrandId != promotion.BrandId)
            {
                throw ApiException.Get(false, "Khuyến mãi không dành cho hãng này", ResultEnum.PromotionNotApplyToBrand, HttpStatusCode.BadRequest);
            }
            var now = DateTime.Now;

            if ((promotion.FromDate != null && now < promotion.FromDate) &&
                (promotion.ToDate != null && now > promotion.ToDate))
            {
                throw ApiException.Get(false, "Ngày áp dụng không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
            }
            if ((promotion.ApplyFromTime != null && now.Hour < promotion.ApplyFromTime) &&
                (promotion.ApplyToTime != null && now.Hour > promotion.ApplyToTime))
            {
                throw ApiException.Get(false, "Thời gian áp dụng không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
            }
            var sMappingService = Service <IPromotionStoreMappingService>();

            if (order.StoreID == null)
            {
                throw ApiException.Get(false, "Thiếu thông tin cửa hàng", ResultEnum.LackOfInformation, HttpStatusCode.BadRequest);
            }
            var mappings = sMappingService.GetActive(m => m.PromotionId == promotion.PromotionID)
                           .Select(m => m.StoreId).AsEnumerable();

            if (!mappings.Contains(order.StoreID.Value))
            {
                throw ApiException.Get(false, "Khuyến mãi không áp dụng cho cửa hàng này", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
            }

            return(BaseResponse <bool> .Get(true, "Hợp lệ", true, ResultEnum.Success, null));
        }
        public HttpResponseMessage UpdateTableCode(OrderAPIViewModel order)
        {
            var customerDomain = new CustomerDomain();
            BaseResponse <OrderHistoryAPIViewModel> response = new BaseResponse <OrderHistoryAPIViewModel>();
            HttpResponseMessage httpResponseMessage          = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            };
            var customerId = customerDomain.getCustomerIdFromToken(RequestContext);

            if (customerId != null)
            {
                order.CustomerID = customerId;
            }
            var domain = new OrderDomain();

            try
            {
                response = domain.UpdateTableCode(order, customerId.Value);
            }
            catch (ApiException e)
            {
                httpResponseMessage.StatusCode = e.StatusCode;
                response = BaseResponse <OrderHistoryAPIViewModel> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);
            }
            catch (Exception e)
            {
                httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                response = BaseResponse <OrderHistoryAPIViewModel> .Get(false, e.ToString(), null, ResultEnum.InternalError);
            }
            httpResponseMessage.Content = new JsonContent(response);
            return(httpResponseMessage);
        }
Пример #3
0
        public BaseResponse <Promotion> IsPromotionValidFor(Promotion promotion, OrderAPIViewModel order, Membership membership = null)
        {
            var gCheck = CheckGeneralPromotionRule(promotion, order);

            var pDetails = GetPromotionDetailsByPromotion(promotion.PromotionCode);

            var mCheck = CheckMembership(promotion, pDetails, membership);

            if (promotion.ApplyLevel == (int)PromotionApplyLevelEnum.Order)
            {
                foreach (var pD in pDetails)
                {
                    var pDetailCheck = IsPromotionDetailValidFor(pD, order, membership);
                }
            }
            else
            {
                foreach (var pD in pDetails)
                {
                    var pDetailCheck = IsPromotionDetailValidFor(pD, order.OrderDetails, membership);
                }
            }

            return(BaseResponse <Promotion> .Get(true, "Promotion can be applied", promotion, ResultEnum.Success, null));
        }
Пример #4
0
        public BaseResponse <Voucher> IsVoucherValidFor(string voucherCode, OrderAPIViewModel order, string cardCode = null)
        {
            var        voucher    = GetVoucher(voucherCode);
            Membership membership = null;

            if (cardCode != null)
            {
                membership = this.Service <IMembershipService>().GetMembershipByCode(cardCode);
            }
            return(IsVoucherValidFor(voucher, order, membership));
        }
Пример #5
0
        public BaseResponse <Promotion> IsPromotionValidFor(string promotionCode, OrderAPIViewModel order, string cardCode = null)
        {
            var        promotion  = GetPromotion(promotionCode);
            Membership membership = null;

            if (cardCode != null)
            {
                membership = this.Service <IMembershipService>().GetMembershipByCode(cardCode);
            }
            return(IsPromotionValidFor(promotion, order, membership));
        }
        public OrderAPIViewModel AddOrderFromPOS(OrderAPIViewModel model)
        {
            try
            {
                var status             = 0;
                var orderService       = DependencyUtils.Resolve <IOrderService>();
                var productService     = DependencyUtils.Resolve <IProductService>();
                var paymentService     = DependencyUtils.Resolve <IPaymentService>();
                var orderDetailService = DependencyUtils.Resolve <IOrderDetailService>();
                var orderDetailDomain  = new OrderDetailDomain();

                //Cập nhật status đơn hàng
                status = UpdateOrderStatus(model.OrderStatus, model.DeliveryStatus.Value);


                //API return success case
                var result = new OrderAPIViewModel()
                {
                    OrderStatus    = status,
                    InvoiceID      = model.OrderCode,
                    DeliveryStatus = model.DeliveryStatus,
                    CheckInPerson  = model.CheckInPerson,
                };

                //Check if order is existed in server
                var checkRent = orderService.GetOrderByInvoiceId(model.OrderCode);

                //Nếu chưa có sẽ add đơn hàng vào db server
                if (checkRent == null)
                {
                    result = AddOrder(status, model, result);
                }
                //Nếu đơn hàng đã có trên server sẽ update payment hoặc order detail
                else
                {
                    result = UpdateOrder(status, checkRent, model, result);
                }

                return(result);
            }
            catch (Exception ex)
            {
                return(new OrderAPIViewModel
                {
                    OrderStatus = model.OrderStatus,
                    InvoiceID = model.OrderCode,
                    DeliveryStatus = model.DeliveryStatus,
                    CheckInPerson = model.CheckInPerson,
                    //Something wrong, return old status
                });
            }
        }
Пример #7
0
        //[Route("use")]
        //[HttpPut]
        //public HttpResponseMessage UseVoucher(PromotionRequestViewModel model)
        //{
        //    //Logger.Log("Store " + model.terminalId + " - " + (model.Order == null ? "null order" : model.Order.OrderCode + "-" + model.Order.OrderId));
        //    //Logger.Log("|UseVoucherCode| begin method");
        //    try
        //    {
        //        var pDomain = new PromotionDomain();
        //        var voucher = pDomain.GetVoucher(model.VoucherCode);
        //        var available = pDomain.IsVoucherAvailable(voucher);
        //        if (available.Success)
        //        {
        //            var useResult = pDomain.UseVoucher(voucher, model);
        //            //Logger.Log("|UserVoucherCode| result: " + useResult.Message + "-" + useResult.Error, true);
        //            return new HttpResponseMessage()
        //            {
        //                Content = new JsonContent(useResult),
        //                StatusCode = HttpStatusCode.OK
        //            };
        //        }
        //        else
        //        {
        //            return new HttpResponseMessage()
        //            {
        //                Content = new JsonContent(available),
        //                StatusCode = HttpStatusCode.OK
        //            };
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        //Logger.Log("|UserVoucherCode| error:\r\n" + JsonConvert.SerializeObject(e), true);
        //        var res = new BaseResponse<string>
        //        {
        //            Success = false,
        //            Message = "Có lỗi xảy ra",
        //            Error = "",
        //            ResultCode = (int)DataService.Models.ResultEnum.InternalError
        //        };
        //        return new HttpResponseMessage()
        //        {
        //            Content = new JsonContent(res),
        //            StatusCode = HttpStatusCode.InternalServerError
        //        };
        //    }
        //}
        #endregion

        #region Mapping models
        private void AddInfo(OrderAPIViewModel src, VoucherQueryRequest <List <OrderDetailAPIViewModel> > request)
        {
            if (!request.BrandId.HasValue)
            {
                throw ApiException.Get(false, "Thiếu thông tin hãng", ResultEnum.BrandIdNotFound, HttpStatusCode.BadRequest);
            }
            var prdDomain = new ProductDomain();

            src.BrandId = request.BrandId.Value;
            foreach (var oD in request.Data)
            {
                oD.ProductCode = prdDomain.GetProductById(oD.ProductID).Code;
            }
        }
Пример #8
0
        public HttpResponseMessage CheckVoucher(CheckVoucherViewModel request)
        {
            //Logger.Log("Store " + model.terminalId);
            //Logger.Log("|CheckVoucherCode| begin method");
            var response       = new BaseResponse <dynamic>();
            var claimPrincipal = (ClaimsPrincipal)RequestContext.Principal;
            var customerId     = claimPrincipal.Claims.Where(c => c.Type == "CustomerId").Select(c => c.Value).SingleOrDefault();
            var cDomain        = new CustomerDomain();
            var id             = Int32.Parse(customerId);
            var customer       = cDomain.GetCustomerById(id);
            var oDomain        = new OrderDomain();

            var resp = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK
            };

            try
            {
                DateTime time    = DataService.Models.Utils.GetCurrentDateTime();
                var      pDomain = new PromotionDomain();
                var      orderVM = new OrderAPIViewModel();
                var      voucher = pDomain.GetVoucher(request.VoucherCode);
                var      mbs     = customer.MembershipVM;

                orderVM.OrderDetails = request.Data;
                orderVM.StoreID      = request.StoreId;
                AddInfo(orderVM, request);
                oDomain.CalculateOrderPrice(orderVM, time);

                //temp: each voucher has only 1 detail now
                var applyResult = pDomain.IsVoucherValidFor(voucher, orderVM, mbs);
                orderVM = pDomain.ApplyPromotionToOrder(orderVM, applyResult, mbs);

                response = BaseResponse <dynamic> .Get(true, "Thành công", orderVM, ResultEnum.Success);
            }
            catch (ApiException e)
            {
                resp.StatusCode = e.StatusCode;
                response        = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);
            }
            catch (Exception e)
            {
                resp.StatusCode = HttpStatusCode.InternalServerError;
                response        = BaseResponse <dynamic> .Get(false, e.ToString(), null, ResultEnum.InternalError);
            }

            resp.Content = new JsonContent(response);
            return(resp);
        }
Пример #9
0
        private Order MapOrder(OrderAPIViewModel src)
        {
            var order = src.ToEntity();

            order.OrderDetails = src.OrderDetails.Select(oD => new OrderDetail()
            {
                ProductID        = oD.ProductID,
                Quantity         = oD.Quantity,
                TmpDetailId      = oD.TmpDetailId,
                ParentId         = oD.ParentId,
                ProductOrderType = oD.ProductOrderType
            }).ToList();
            return(order);
        }
        //[trungtran]
        public OrderAPIViewModel ApplyPromotionToOrder(OrderAPIViewModel order, Promotion promotion, PromotionDetail pDetail)
        {
            //temp: apply only for discount promotion
            if (promotion.ApplyLevel == (int)PromotionApplyLevelEnum.Order)
            {
                if (pDetail.DiscountAmount != null)
                {
                    order.Discount    = (double)pDetail.DiscountAmount.Value;
                    order.FinalAmount = order.TotalAmount - order.Discount;
                }
                else if (pDetail.DiscountRate != null)
                {
                    order.Discount     = order.TotalAmount * pDetail.DiscountRate.Value / 100;
                    order.FinalAmount  = order.TotalAmount - order.Discount;
                    order.DiscountRate = pDetail.DiscountRate.Value;
                }
            }
            else if (promotion.ApplyLevel == (int)PromotionApplyLevelEnum.OrderDetail)
            {
                if (pDetail.DiscountAmount != null)
                {
                    var discount = 0.0;
                    foreach (var oD in order.OrderDetails)
                    {
                        oD.Discount    = (double)pDetail.DiscountAmount.Value;
                        oD.FinalAmount = oD.TotalAmount - oD.Discount;
                        discount      += oD.Discount;
                    }
                    order.Discount    = order.TotalAmount - discount;
                    order.FinalAmount = order.TotalAmount - order.Discount;
                }
                else if (pDetail.DiscountRate != null)
                {
                    var rate     = pDetail.DiscountRate.Value;
                    var discount = 0.0;
                    foreach (var oD in order.OrderDetails)
                    {
                        oD.Discount    = oD.TotalAmount * rate / 100;
                        oD.FinalAmount = oD.TotalAmount - oD.Discount;
                        discount      += oD.Discount;
                    }
                    order.Discount    = order.TotalAmount - discount;
                    order.FinalAmount = order.TotalAmount - order.Discount;
                }
            }

            return(order);
        }
Пример #11
0
        public BaseResponse <Voucher> IsVoucherValidFor(Voucher voucher, OrderAPIViewModel order, Membership membership = null)
        {
            var available = IsVoucherAvailable(voucher);

            if (voucher.MembershipCardId != null)
            {
                if (voucher.MembershipCardId != membership.Id)
                {
                    throw ApiException.Get(false, "Voucher không dành cho thành viên này", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }

            var pValid = IsPromotionValidFor(voucher.Promotion, order, membership);

            return(BaseResponse <Voucher> .Get(true, "Voucher có thể sử dụng", voucher, ResultEnum.Success, null));
        }
        public HttpResponseMessage CreateOrder(OrderAPIViewModel order)
        {
            var customerDomain = new CustomerDomain();
            BaseResponse <OrderHistoryAPIViewModel> response = new BaseResponse <OrderHistoryAPIViewModel>();
            HttpResponseMessage httpResponseMessage          = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            };

            #region get CustomerId and EmployeeId from Token
            var customerId = customerDomain.getCustomerIdFromToken(RequestContext);
            if (customerId != null)
            {
                order.CustomerID = customerId;
            }
            var   claimPrincipal = (ClaimsPrincipal)RequestContext.Principal;
            var   employeeId     = claimPrincipal.Claims.Where(c => c.Type == "EmployeeId").Select(c => c.Value).SingleOrDefault();
            var   userName       = claimPrincipal.Claims.Where(c => c.Type == "UserName").Select(c => c.Value).SingleOrDefault();
            Int32 employeeID     = 0;
            Int32.TryParse(employeeId, out employeeID);
            if (employeeID != 0)
            {
                order.EmployeeId    = employeeID;
                order.CheckInPerson = userName;
            }
            #endregion

            IOrderDomain domain = new OrderDomain();
            try
            {
                response = domain.AddOrderFromMobile(order);
            }
            catch (DataService.Utilities.ApiException e)
            {
                httpResponseMessage.StatusCode = e.StatusCode;
                response = BaseResponse <OrderHistoryAPIViewModel> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);
            }
            catch (Exception e)
            {
                httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                response = BaseResponse <OrderHistoryAPIViewModel> .Get(false, e.ToString(), null, ResultEnum.InternalError);
            }
            httpResponseMessage.Content = new JsonContent(response);
            return(httpResponseMessage);
        }
        public HttpResponseMessage CalculateFeeDelivery(OrderAPIViewModel order)
        {
            var customerDomain = new CustomerDomain();
            BaseResponse <OrderAPIViewModel> response = new BaseResponse <OrderAPIViewModel>();
            HttpResponseMessage httpResponseMessage   = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK
            };
            //var customerId = customerDomain.getCustomerIdFromToken(RequestContext);
            //if (customerId != 0)
            //{
            //    order.CustomerID = customerId;
            //}
            IOrderDomain domain = new OrderDomain();

            try
            {
                var customerID = customerDomain.getCustomerIdFromToken(RequestContext);
                if (customerID != null)
                {
                    order.CustomerID = customerID;
                }
                response.Data       = domain.GetDeliveryFee(order);
                response.Message    = ConstantManager.MES_SUCCESS;
                response.ResultCode = (int)ResultEnum.Success;
                response.Success    = true;
            }
            catch (DataService.Utilities.ApiException e)
            {
                httpResponseMessage.StatusCode = e.StatusCode;
                response = BaseResponse <OrderAPIViewModel> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);
            }
            catch (Exception e)
            {
                httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                response = BaseResponse <OrderAPIViewModel> .Get(false, e.ToString(), null, ResultEnum.InternalError);
            }
            httpResponseMessage.Content = new JsonContent(response);
            return(httpResponseMessage);
        }
Пример #14
0
        private void AddInfo(OrderAPIViewModel src, CheckVoucherViewModel request)
        {
            if (!request.BrandId.HasValue && !request.StoreId.HasValue)
            {
                throw ApiException.Get(false, "Thiếu thông tin brand", ResultEnum.BrandIdNotFound, HttpStatusCode.BadRequest);
            }
            var prdDomain = new ProductDomain();

            src.BrandId = request.BrandId.Value;
            if (request.BrandId == -1 && request.StoreId > 0)
            {
                var storeApi = new DataService.Domain.StoreDomain();
                var store    = storeApi.GetStoreByStoreId(request.StoreId.Value);
                src.BrandId = store.BrandId;
            }
            else
            {
                throw ApiException.Get(false, "Thiếu thông tin brand", ResultEnum.BrandIdNotFound, HttpStatusCode.BadRequest);
            }
            foreach (var oD in request.Data)
            {
                oD.ProductCode = prdDomain.GetProductById(oD.ProductID).Code;
            }
        }
        private OrderAPIViewModel UpdateOrder(int status, Models.Entities.Order order, OrderAPIViewModel model, OrderAPIViewModel result)
        {
            var orderService       = DependencyUtils.Resolve <IOrderService>();
            var productService     = DependencyUtils.Resolve <IProductService>();
            var paymentService     = DependencyUtils.Resolve <IPaymentService>();
            var orderDetailService = DependencyUtils.Resolve <IOrderDetailService>();
            var orderDetailDomain  = new OrderDetailDomain();

            #region Đơn hàng mới sẽ cập nhật order detail và payment
            if (model.DeliveryStatus == (int)DeliveryStatus.New)
            {
                //Không được edit đơn hàng finish trên server !!!
                if (order.OrderStatus == (int)OrderStatusEnum.Finish)
                {
                    result.OrderStatus = model.OrderStatus;
                    //Return old status
                }
                #region Start to edit if this order != finished
                //Chỉ edit khi đơn hàng chưa finish trên server
                else if (order.OrderStatus != (int)OrderStatusEnum.Finish)
                {
                    var modifiedPayment     = false;
                    var modifiedOrderDetail = false;

                    #region Nếu chưa từng có orderdetail hoặc có sự thay đổi orderdetail thì sẽ xóa hết order detail
                    if (!order.OrderDetails.Any() ||
                        order.LastModifiedOrderDetail == null ||
                        (order.LastModifiedOrderDetail != null &&
                         order.LastModifiedOrderDetail != model.LastModifiedOrderDetail))
                    {
                        //Delete all orderdetail
                        var lastOdList = order.OrderDetails.ToList();
                        foreach (var od in lastOdList)
                        {
                            order.OrderDetails.Remove(od);
                            var orderDetailCurrent = orderDetailService.Get(od.OrderDetailID);
                            orderDetailService.Delete(orderDetailCurrent);
                        }
                        modifiedOrderDetail = true;
                    }
                    #endregion

                    #region Đơn hàng đang xử lý hoặc đã thành công mới cập nhật payment bằng cách củ chuối xóa hết rồi insert lại
                    if (status == (int)OrderStatusEnum.Finish ||
                        status == (int)OrderStatusEnum.Processing)
                    {
                        //Chưa từng có payment hoặc có sự thay đổi payment
                        if (!order.Payments.Any() ||
                            order.Payments.Sum(p => p.Amount) == 0 ||
                            order.LastModifiedPayment == null ||
                            (order.LastModifiedPayment != null &&
                             order.LastModifiedPayment != model.LastModifiedPayment))
                        {
                            //Delete all payment
                            var lastPList = order.Payments.ToList();
                            foreach (var p in lastPList)
                            {
                                order.Payments.Remove(p);
                                var currentpayment = paymentService.Get(p.PaymentID);
                                paymentService.Delete(currentpayment);
                            }
                            modifiedPayment = true;
                        }
                    }
                    #endregion

                    #region redload order db nếu có bất kì sự thay đổi
                    if (modifiedPayment || modifiedOrderDetail)
                    {
                        order = null;
                        order = orderService.GetOrderByInvoiceId(model.OrderCode);
                    }
                    #endregion

                    #region update if modify Payment or OrderDetail
                    if (modifiedOrderDetail)
                    {
                        //Vì có sự thay đổi orderdetail -> order có thay đổi -> update order
                        //Order
                        order = model.ToEntity();

                        //Orderdetail
                        foreach (var odm in model.OrderDetails.ToList())
                        {
                            var productId   = productService.GetProductByCode(odm.ProductCode).ProductID;
                            var orderdetail = odm.ToEntity();
                            orderdetail.ProductID = productId;
                            orderdetail.StoreId   = model.StoreID;

                            //Orderdetail Promotion Mapping
                            //Đối với đơn hàng từ POS thì phải finish mới có promotion (đơn hàng khác chưa biết..)
                            if (status == (int)OrderStatusEnum.Finish)
                            {
                                foreach (var odpm in odm.OrderDetailPromotionMappings.ToList())
                                {
                                    var mapping = odpm.ToEntity();
                                    mapping.PromotionId = (new PromotionService())
                                                          .GetByPromoCode(odpm.PromotionCode).PromotionID;
                                    mapping.PromotionDetailId = (new PromotionDetailService())
                                                                .GetDetailByPromotionDetailCode(odpm.PromotionDetailCode).PromotionDetailID;

                                    orderdetail.OrderDetailPromotionMappings.Add(mapping);
                                }
                            }

                            order.OrderDetails.Add(orderdetail);
                        }

                        //Order Promotion Mapping
                        //Đối với đơn hàng từ POS thì phải finish mới có promotion (đơn hàng khác chưa biết..)
                        if (status == (int)OrderStatusEnum.Finish)
                        {
                            foreach (var opm in model.OrderPromotionMappings.ToList())
                            {
                                var mapping = opm.ToEntity();
                                mapping.PromotionId = (new PromotionService())
                                                      .GetByPromoCode(opm.PromotionCode).PromotionID;
                                mapping.PromotionDetailId = (new PromotionDetailService())
                                                            .GetDetailByPromotionDetailCode(opm.PromotionDetailCode).PromotionDetailID;

                                order.OrderPromotionMappings.Add(mapping);
                            }
                        }
                    }

                    if (modifiedPayment)
                    {
                        //Payment
                        foreach (var p in model.Payments.ToList())
                        {
                            var payment = p.ToEntity();
                            order.Payments.Add(payment);
                        }
                    }

                    //Save
                    order.OrderStatus    = status;
                    order.DeliveryStatus = model.DeliveryStatus;
                    order.CheckInPerson  = model.CheckInPerson;
                    orderService.EditOrder(order);

                    if (modifiedOrderDetail)
                    {
                        //Update tmpId
                        orderDetailDomain.UpdateOrderDetailId(order);
                        orderService.EditOrder(order);
                    }
                    //Success
                    #endregion
                }
                #endregion
            }
            #endregion
            #region Đơn hàng cũ thì sẽ tiến hành cập nhật lại payment
            //Đơn hàng delivery
            else
            {
                //Không có sự thay đổi ở orderdetail
                #region Nếu đã hoàn thành hoặc đang xử lí sẽ cập nhật payment
                if (status == (int)OrderStatusEnum.Finish ||
                    status == (int)OrderStatusEnum.Processing)
                {
                    var modifiedPayment = false;

                    #region delete all payment in order
                    var pList = order.Payments.ToList();
                    foreach (var p in pList)
                    {
                        modifiedPayment = true;
                        order.Payments.Remove(p);
                        var paymentcurrent = paymentService.Get(p.PaymentID);
                        paymentService.Delete(paymentcurrent);
                    }
                    #endregion

                    #region redload order db if any payment is deleted
                    if (modifiedPayment)
                    {
                        order = null;
                        order = orderService.GetOrderByInvoiceId(model.OrderCode);
                    }
                    #endregion
                    var checkStatusMomo = false;

                    #region add payment from Order view model to order again. Check if there is any Momo payment
                    foreach (var p in model.Payments.ToList())
                    {
                        var payment = p.ToEntity();
                        if (payment.Type == (int)PaymentTypeEnum.MoMo)
                        {
                            checkStatusMomo = true;
                        }
                        order.Payments.Add(payment);
                    }
                    #endregion

                    //for Order payed by Momo
                    if (checkStatusMomo && status == (int)OrderStatusEnum.Finish)
                    {
                        new PaymentDomain().SendMomoPaymentNotification(order);
                        ////update
                        //Fix Order sent Don't Have Payment when finish
                        if (model.FinalAmount > 0)
                        {
                            if (model.FinalAmount != (model.TotalAmount - model.Discount - model.DiscountOrderDetail))
                            {
                                return(new OrderAPIViewModel
                                {
                                    OrderStatus = model.OrderStatus,
                                    InvoiceID = model.OrderCode,
                                    DeliveryStatus = model.DeliveryStatus,
                                    CheckInPerson = model.CheckInPerson,
                                    //Something wrong, return old status
                                });
                            }
                            //TODO: Fix bug Miss Payment
                            if (model.Payments.Count() == 0)
                            {
                                var payment = new Payment();
                                payment.Amount   = model.FinalAmount;
                                payment.Status   = (int)OrderPaymentStatusEnum.Finish;
                                payment.Type     = model.Att1 != null ? (int)PaymentTypeEnum.MemberPayment : (int)PaymentTypeEnum.Cash;
                                payment.PayTime  = model.CheckInDate.Value;
                                payment.FCAmount = 0;
                                order.Payments.Add(payment);
                            }
                        }
                    }

                    order.OrderStatus    = status;
                    order.DeliveryStatus = model.DeliveryStatus;
                    order.CheckInPerson  = model.CheckInPerson;
                    orderService.EditOrder(order);
                    //Success
                }
                #endregion
                #region if status = pre cancel
                else if (status == (int)OrderStatusEnum.PreCancel)
                {
                    order.OrderStatus    = status;
                    order.DeliveryStatus = model.DeliveryStatus;
                    order.CheckInPerson  = model.CheckInPerson;
                    orderService.EditOrder(order);
                }
                #endregion
                else
                //Không có gì cập nhật
                {
                    result.OrderStatus = model.OrderStatus;
                    //Return old status
                }
            }
            #endregion
            return(result);
        }
        private OrderAPIViewModel AddOrder(int status, OrderAPIViewModel model, OrderAPIViewModel result)
        {
            var orderService       = DependencyUtils.Resolve <IOrderService>();
            var productService     = DependencyUtils.Resolve <IProductService>();
            var orderDetailService = DependencyUtils.Resolve <IOrderDetailService>();
            var orderDetailDomain  = new OrderDetailDomain();
            //Order
            var order = model.ToEntity();

            order.OrderStatus    = status;
            order.DeliveryStatus = model.DeliveryStatus;
            order.CheckInPerson  = model.CheckInPerson;

            #region cập nhật order detail
            foreach (var odm in model.OrderDetails.ToList())
            {
                var productId   = productService.GetProductByCode(odm.ProductCode).ProductID;
                var orderdetail = odm.ToEntity();
                orderdetail.ProductID = productId;
                orderdetail.StoreId   = model.StoreID;

                //Orderdetail Promotion Mapping
                //Đối với đơn hàng từ POS thì phải finish mới có promotion (đơn hàng khác chưa biết..)
                if (model.DeliveryStatus == (int)DeliveryStatus.New &&
                    status == (int)OrderStatusEnum.Finish)
                {
                    foreach (var odpm in odm.OrderDetailPromotionMappings.ToList())
                    {
                        var mapping = odpm.ToEntity();
                        mapping.PromotionId = (new PromotionService())
                                              .GetByPromoCode(odpm.PromotionCode).PromotionID;
                        mapping.PromotionDetailId = (new PromotionDetailService())
                                                    .GetDetailByPromotionDetailCode(odpm.PromotionDetailCode).PromotionDetailID;
                        orderdetail.OrderDetailPromotionMappings.Add(mapping);
                    }
                }

                order.OrderDetails.Add(orderdetail);
            }
            #endregion

            #region map Order với Promotion
            //Đối với đơn hàng từ POS thì phải finish mới có promotion (đơn hàng khác chưa biết..)
            if (model.DeliveryStatus == (int)DeliveryStatus.New &&
                status == (int)OrderStatusEnum.Finish)
            {
                foreach (var opm in model.OrderPromotionMappings.ToList())
                {
                    var mapping = opm.ToEntity();
                    mapping.PromotionId = (new PromotionService())
                                          .GetByPromoCode(opm.PromotionCode).PromotionID;
                    mapping.PromotionDetailId = (new PromotionDetailService())
                                                .GetDetailByPromotionDetailCode(opm.PromotionDetailCode).PromotionDetailID;
                    order.OrderPromotionMappings.Add(mapping);
                }
            }
            #endregion

            #region cập nhật payment
            //Finished || Processing Order -> Save Payment
            if (status == (int)OrderStatusEnum.Finish ||
                status == (int)OrderStatusEnum.Processing)
            {
                var checkStatusMomo = false;
                //if
                foreach (var p in model.Payments.ToList())
                {
                    var payment = p.ToEntity();
                    if (payment.Type == (int)PaymentTypeEnum.MoMo)
                    {
                        checkStatusMomo = true;
                    }
                    order.Payments.Add(payment);
                }

                if (checkStatusMomo == true && (int)OrderStatusEnum.Finish == status)
                {
                    new PaymentDomain().SendMomoPaymentNotification(order);
                }

                if (status == (int)OrderStatusEnum.Finish)
                {
                    //Fix Order sent Don't Have Payment when finish
                    if (model.FinalAmount > 0)
                    {
                        if (model.FinalAmount != (model.TotalAmount - model.Discount - model.DiscountOrderDetail))
                        {
                            return(new OrderAPIViewModel
                            {
                                OrderStatus = model.OrderStatus,
                                InvoiceID = model.OrderCode,
                                DeliveryStatus = model.DeliveryStatus,
                                CheckInPerson = model.CheckInPerson,
                                //Something wrong, return old status
                            });
                        }
                        //TODO: Fix bug Miss Payment
                        if (model.Payments.Count() == 0)
                        {
                            var payment = new Payment();
                            payment.Amount   = model.FinalAmount;
                            payment.Status   = (int)OrderPaymentStatusEnum.Finish;
                            payment.Type     = model.Att1 != null ? (int)PaymentTypeEnum.MemberPayment : (int)PaymentTypeEnum.Cash;
                            payment.PayTime  = model.CheckInDate.Value;
                            payment.FCAmount = 0;
                            order.Payments.Add(payment);
                        }
                    }
                }
            }
            else
            {
                //Không lưu payment
            }
            #endregion

            #region Save Order
            var created = orderService.CreateOrder(order);

            if (created)
            {
                //Update tmpId
                orderDetailDomain.UpdateOrderDetailId(order);
                orderService.EditOrder(order);
                //Success
            }
            else
            {
                result.OrderStatus = model.OrderStatus;
                //Fail - Return old status
            }
            #endregion
            return(result);
        }
Пример #17
0
        public BaseResponse <PromotionDetail> IsPromotionDetailValidFor(PromotionDetail pDetail, OrderAPIViewModel order, Membership membership = null)
        {
            if (pDetail.MinOrderAmount != null)
            {
                if (order.TotalAmount < pDetail.MinOrderAmount)
                {
                    throw ApiException.Get(false, "Tổng thanh toán không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }
            if (pDetail.MaxOrderAmount != null)
            {
                if (order.TotalAmount > pDetail.MaxOrderAmount)
                {
                    throw ApiException.Get(false, "Tỏng thanh toán không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }
            var cashbackAcc = membership.Accounts.FirstOrDefault(a => a.Type == (int)AccountTypeEnum.PointAccount);

            if (cashbackAcc == null)
            {
                throw ApiException.Get(false, "Không thể tìm thấy tài khoản tích điểm", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
            }
            if (pDetail.MinPoint != null)
            {
                if (cashbackAcc.Balance < pDetail.MinPoint)
                {
                    throw ApiException.Get(false, "Điểm thành viên không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }
            if (pDetail.MaxPoint != null)
            {
                if (cashbackAcc.Balance > pDetail.MaxPoint)
                {
                    throw ApiException.Get(false, "Điểm thành viên không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }

            return(BaseResponse <PromotionDetail> .Get(true, "PromotionDetail can be applied", pDetail, ResultEnum.Success, null));
        }
Пример #18
0
        public BaseResponse <PromotionDetail> IsPromotionDetailValidFor(string pDetailCode, OrderAPIViewModel order, string cardCode = null)
        {
            Membership membership = null;

            if (cardCode != null)
            {
                membership = this.Service <IMembershipService>().GetMembershipByCode(cardCode);
            }
            var pDetail = GetPromotionDetail(pDetailCode);

            return(IsPromotionDetailValidFor(pDetail, order, membership));
        }
        public void CalculateOrderPrice(OrderAPIViewModel order, DateTime time)
        {
            #region OrderDetail

            #region Service and variable
            IProductService productService         = DependencyUtils.Resolve <IProductService>();
            double          orderDetailTotalAmount = 0;
            double          orderDetailFinalAmount = 0;
            //double discountOrderDetail = 0;
            //biến giảm giá trên mỗi sản phẩm
            double discountEachProduct = 0;
            //biến giảm giá trên toàn hóa đơn
            double discount         = 0;
            bool   checkDeliveryFee = false;
            double finalAmount      = 0;
            double totalAmount      = 0;
            double deliveryFee      = 0;
            //add order detail have product is a delivery fee
            //giảm giá trên từng sản phẩm, hóa đơn tùy theo rule ở hàm checkPromotionRUle
            int quantity = 0;//check quantity trong order gửi 1 đơn hàng và có quantity trong đó
            #endregion

            foreach (var item in order.OrderDetails)
            {
                if (item.ParentId == 0)
                {
                    item.ParentId = null;
                }

                if (item.Quantity <= 0)
                {
                    throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_NEGATIVE_QUANTITY, ResultEnum.OrderDetailQuantity, HttpStatusCode.BadRequest);
                }
                var product = productService.GetProductById(item.ProductID);
                if (product == null)
                {
                    throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_NOT_FOUND_PRODUCT, ResultEnum.ProductNotFound, HttpStatusCode.NotFound);
                }
                item.ProductType = product.ProductType;
                item.TotalAmount = product.Price * item.Quantity;

                orderDetailTotalAmount += item.TotalAmount;
                item.UnitPrice          = product.Price;
                //lấy giảm giá theo rule
                PromotionRule rule = new PromotionRule();
                rule = PromotionRuleUtility.checkPromotionRule(order, quantity, item);
                //check rule 1, 2 dc định nghĩ ở ConstantManager
                if (rule.rule == ConstantManager.PROMOTION_RULE_2 || rule.countProduct)
                {
                    item.Discount = rule.discountAmount;
                }
                else if (rule.rule == ConstantManager.PROMOTION_RULE_1)
                {
                    discount = rule.discountAmount;
                }

                quantity                = rule.quantity;
                item.FinalAmount        = item.TotalAmount - item.Discount;
                orderDetailFinalAmount += item.FinalAmount;
                discountEachProduct    += item.Discount;
                //discountOrderDetail += item.Discount;
                item.OrderDate = time;
            }
            foreach (var item in order.OrderDetails)
            {
                if (item.ProductType != (int)ProductTypeEnum.ServiceFee)
                {
                    totalAmount  = productService.GetProductById(item.ProductID).Price *item.Quantity;
                    finalAmount += totalAmount - item.Discount;
                    if (finalAmount >= ConstantManager.DELIVERY_FREE || order.OrderType != (int)OrderTypeEnum.MobileDelivery)
                    {
                        checkDeliveryFee = true;
                    }
                }
            }

            if (!checkDeliveryFee)
            {
                var tmpOrderDetail  = order.OrderDetails.ToList();
                var productDelivery = productService.GetProductDeliveryFee();
                OrderDetailAPIViewModel deliveryOrderDt = new OrderDetailAPIViewModel();
                deliveryOrderDt.ProductID   = productDelivery.ProductID;
                deliveryOrderDt.Quantity    = 1;
                deliveryOrderDt.TotalAmount = productDelivery.Price;
                deliveryOrderDt.FinalAmount = productDelivery.Price;
                deliveryOrderDt.UnitPrice   = productDelivery.Price;
                deliveryFee = productDelivery.Price;

                deliveryOrderDt.ProductOrderType = (int)Models.ProductOrderType.Single;
                deliveryOrderDt.OrderDate        = time;
                deliveryOrderDt.ProductType      = (int)ProductTypeEnum.ServiceFee;
                tmpOrderDetail.Add(deliveryOrderDt);
                order.OrderDetails = tmpOrderDetail;
            }
            #endregion
            #region Order
            order.CheckInDate = time;
            var vatAmount = 0; //VAT 10%
            #region edit promotion

            #endregion

            order.TotalAmount         = orderDetailTotalAmount;
            order.Discount            = discount;
            order.DiscountOrderDetail = discountEachProduct;
            order.FinalAmount         = orderDetailTotalAmount + deliveryFee - vatAmount - discount - discountEachProduct;//l?y order detail sum l?i => ra du?c order thi?t c?a passio
            //order.DiscountOrderDetail = discountOrderDetail;
            //gán giản giá trên từng sản phẩm cho order
            #endregion
        }
        public static PromotionRule checkPromotionRule(OrderAPIViewModel order, int quantity, OrderDetailAPIViewModel od)
        {
            #region call service
            IVoucherService         voucherService         = DependencyUtils.Resolve <IVoucherService>();
            IPromotionService       promotionService       = DependencyUtils.Resolve <IPromotionService>();
            IPromotionDetailService promotionDetailService = DependencyUtils.Resolve <IPromotionDetailService>();
            IProductService         productService         = DependencyUtils.Resolve <IProductService>();
            #endregion

            PromotionRule result = new PromotionRule
            {
                rule           = 0,
                discountAmount = 0
            };
            #region Voucher
            var voucher = voucherService.GetVoucherIsNotUsedAndCode(order.VoucherCode);
            if (voucher == null)
            {
                return(result);
            }
            #endregion


            //var voucher = voucherApi
            //TODO after have voucher
            int checkCountProduct = 0;//dùng check trường hợp gửi 2 đơn hàng giống nhau nhưng mỗi cái có 1 quantity

            //get date to get promotion is experied ??
            #region Promotion
            var      promotion = promotionService.GetPromotionByDateAndId(voucher.PromotionID);
            DateTime now       = DateTime.Now;

            if (promotion == null)
            {
                return(result);
            }
            else if (!(promotion.ApplyFromTime <= now.Hour && now.Hour <= promotion.ApplyToTime))
            {
                return(result);
            }

            #endregion
            #region PromtionDetail rule 1 min , max order???
            // loop to get total amount, final amount to get check in promotiondetail
            double finalAmount = 0;

            foreach (var item in order.OrderDetails)
            {
                finalAmount += (productService.GetProductById(item.ProductID).Price *item.Quantity);
            }

            var promotionDetail = promotionDetailService.GetDetailByCode(promotion.PromotionCode).FirstOrDefault();
            if (promotionDetail == null)
            {
                return(result);
            }
            //check promotion detail is have min, max order != null ???
            if (promotionDetail.MinOrderAmount != null || promotionDetail.MaxOrderAmount != null)
            {
                if (promotionDetail.MinOrderAmount != null && finalAmount < promotionDetail.MinOrderAmount)
                {
                    throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_EXCEED_VOUCHER_MIN_MAX, ResultEnum.VoucherMin, HttpStatusCode.BadRequest);
                }
                else if (promotionDetail.MaxOrderAmount != null && finalAmount > promotionDetail.MaxOrderAmount)
                {
                    throw  ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_EXCEED_VOUCHER_MIN_MAX, ResultEnum.VoucherMax, HttpStatusCode.BadRequest);
                }
                else
                {
                    try
                    {
                        double discountAmount = 0;//amount return
                        if (promotionDetail.DiscountRate != null && promotionDetail.DiscountRate > 0)
                        {
                            //nhân với phần trăm giảm giá và trả về số tiền lun
                            discountAmount = (productService.GetProductById(od.ProductID).Price *promotionDetail.DiscountRate.Value) / 100;
                        }
                        else if (promotionDetail.DiscountAmount != null && promotionDetail.DiscountAmount > 0)
                        {
                            //nếu giảm giá theo tiền mặt
                            discountAmount = Convert.ToDouble(promotionDetail.DiscountAmount.Value);
                        }
                        result.rule           = Models.ConstantManager.PROMOTION_RULE_1;
                        result.discountAmount = discountAmount;
                        return(result);
                    }
                    catch
                    {
                        result.rule           = 0;
                        result.discountAmount = 0;
                        return(result);
                    }
                }
            }
            #endregion

            #region rule 2 buy min, max quantity of each product
            else if (promotionDetail.BuyProductCode != null)
            {
                double discountAmount = 0;
                //check product code is in order ????
                bool checkProductCode = false;
                //list product discount
                List <ProductDiscount> listProductDiscount = new List <ProductDiscount>();
                // var pmDetail = promotionDetailApi.GetDetailByCode(promotion.PromotionCode);
                int     pDetailId         = voucher.PromotionDetailID == null ? 0 : voucher.PromotionDetailID.Value;
                var     pmDetail          = promotionDetailService.GetDetailById(pDetailId);
                decimal tmpDiscountAmount = 0;
                double  tmpDiscountRate   = 0;
                string  mesMinBuyProduct  = "";
                bool    checkCount        = true;//check quanitty min order buy
                var     tmpProductOrder   = productService.GetProductById(od.ProductID);

                bool checkCountProductQuantity = true; //false => đơn hàng gửi lên giống nhau nhưng ko đủ quantity min order,
                                                       //true => đơn hàng gửi lên giống nhau nhưng đủ quantity
                foreach (var item in order.OrderDetails)
                {
                    if (tmpProductOrder.Code == pmDetail.BuyProductCode)
                    {
                        checkCountProduct += item.Quantity;//cộng đồn quantity trong order
                        if (checkCountProduct < pmDetail.MinBuyQuantity)
                        {
                            checkCountProductQuantity = false;//false => đơn hàng gửi lên giống nhau nhưng ko đủ quantity min order,
                        }
                        else
                        {
                            checkCountProductQuantity = true;
                        }
                    }
                }
                if (pmDetail != null)
                {
                    if (tmpProductOrder.Code == pmDetail.BuyProductCode)
                    {
                        quantity         += od.Quantity;
                        tmpDiscountAmount = pmDetail.DiscountAmount == null ? 0 : pmDetail.DiscountAmount.Value * od.Quantity;
                        tmpDiscountRate   = pmDetail.DiscountRate == null ? 0 : pmDetail.DiscountRate.Value;
                        checkProductCode  = true;
                        if (quantity < pmDetail.MinBuyQuantity)
                        {
                            mesMinBuyProduct = pmDetail.MinBuyQuantity + " " + tmpProductOrder.ProductName;
                            checkCount       = false;
                        }
                    }
                    else
                    {
                        // checkCount = true;
                    }
                }

                try
                {
                    //if true => get list product discount
                    if (checkProductCode)
                    {
                        //check amount discount and rate, return value
                        if (tmpDiscountAmount > 0)
                        {
                            discountAmount = System.Convert.ToDouble(tmpDiscountAmount);
                        }
                        else if (tmpDiscountRate > 0)
                        {
                            discountAmount = (tmpProductOrder.Price * tmpDiscountRate * od.Quantity) / 100;
                        }
                    }
                    checkProductCode = false;
                    //return list product with discount amount, rate
                }
                catch
                {
                    result.rule           = 0;
                    result.discountAmount = 0;
                    result.quantity       = 0;
                    result.countProduct   = false;
                    return(result);
                }


                if (!checkCount && !checkCountProductQuantity)
                {
                    result.rule           = 0;
                    result.discountAmount = 0;
                    result.quantity       = quantity;
                    result.countProduct   = checkCountProductQuantity;
                    return(result);
                }
                result.rule           = ConstantManager.PROMOTION_RULE_2;
                result.discountAmount = discountAmount;
                result.quantity       = quantity;
                result.countProduct   = checkCountProductQuantity;
                return(result);
            }
            result.rule           = 0;
            result.discountAmount = 0;
            result.quantity       = 0;
            return(result);

            #endregion
        }
        public BaseResponse <OrderHistoryAPIViewModel> AddOrderFromMobile(OrderAPIViewModel order)
        {
            using (TransactionScope scope =
                       new TransactionScope(TransactionScopeOption.Required,
                                            new TransactionOptions {
                IsolationLevel = IsolationLevel.RepeatableRead
            }))
            {
                try
                {
                    #region call service
                    DateTime             time                = DataService.Models.Utils.GetCurrentDateTime();
                    IStoreService        storeService        = DependencyUtils.Resolve <IStoreService>();
                    IDeliveryInfoService deliveryInfoService = DependencyUtils.Resolve <IDeliveryInfoService>();
                    IVoucherService      voucherService      = DependencyUtils.Resolve <IVoucherService>();
                    var orderService   = DependencyUtils.Resolve <IOrderService>();
                    var productService = DependencyUtils.Resolve <IProductService>();
                    #endregion

                    #region set default order
                    order.DeliveryStatus = (int)DeliveryStatus.New;
                    //order.OrderType = (int)OrderTypeEnum.Delivery;
                    order.OrderStatus = (int)OrderStatusEnum.New;
                    order.InvoiceID   = ConstantManager.PREFIX_MOBILE + "-" + order.StoreID + "-" + InvoiceCodeGenerator.GenerateInvoiceCode(); // truyền mã hóa don
                    order.SourceType  = (int)SourceTypeEnum.Mobile;
                    order.IsSync      = false;
                    int paymentType = order.PaymentType;
                    #endregion

                    #region check customer existed
                    var customer = new CustomerDomain().GetCustomerById(order.CustomerID.Value);
                    if (customer == null)
                    {
                        throw ApiException.Get(false, ConstantManager.MES_CHECK_CUSTOMERID_FAIL, ResultEnum.CustomerNotFound, HttpStatusCode.NotFound);
                    }
                    #endregion
                    #region check parent and child OrderDetail
                    foreach (var item in order.OrderDetails)
                    {
                        if (item.ParentId == 0)
                        {
                            item.ParentId = null;
                        }
                        if (item.ParentId != null && item.ParentId > -1)
                        {
                            var parentOrderDetail = order.OrderDetails.FirstOrDefault(od => od.TmpDetailId == item.ParentId);
                            if (parentOrderDetail != null)
                            {
                                var listExtra = productService.getProductExtraById(parentOrderDetail.ProductID);
                                var check     = listExtra.FirstOrDefault(e => e.ProductID == item.ProductID);
                                if (check == null)
                                {
                                    throw ApiException.Get(false, ConstantManager.MES_CHILD_ORDERDETAIL_WRONG, ResultEnum.ChildOrderDetailWrong, HttpStatusCode.BadRequest);
                                }
                            }
                            else
                            {
                                throw ApiException.Get(false, ConstantManager.MES_PARENT_ORDERDETAIL_NOTFOUND, ResultEnum.ParentOrderDetailNotFound, HttpStatusCode.BadRequest);
                            }
                        }
                    }
                    #endregion

                    #region calculate price of order detail and order
                    #region check voucher existed
                    if (!string.IsNullOrEmpty(order.VoucherCode))
                    {
                        var voucher = voucherService.GetVoucherIsNotUsedAndCode(order.VoucherCode);
                        if (voucher == null)
                        {
                            throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_NOT_FOUND_VOUCHER, ResultEnum.VoucherNotFound, HttpStatusCode.NotFound);
                        }
                    }
                    #endregion
                    CalculateOrderPrice(order, time);
                    #endregion

                    #region Update Order Type info
                    switch (order.OrderType)
                    {
                    case (int)OrderTypeEnum.MobileDelivery:
                        var deliveryInfo = deliveryInfoService.GetDeliveryById(order.DeliveryInfoId);
                        if (deliveryInfo != null && deliveryInfo.CustomerId == customer.CustomerID)
                        {
                            order.Receiver        = deliveryInfo.CustomerName;
                            order.DeliveryAddress = deliveryInfo.Address;
                            order.DeliveryPhone   = deliveryInfo.Phone;
                        }
                        else
                        {
                            throw ApiException.Get(true, ConstantManager.MES_DELIVERYID_WRONG, ResultEnum.DeliveryNotFound, HttpStatusCode.OK);
                        }
                        break;

                    case (int)OrderTypeEnum.AtStore:
                        order.DeliveryAddress = OrderTypeEnum.AtStore.DisplayName();
                        order.Receiver        = customer.Name;
                        order.DeliveryPhone   = customer.Phone;
                        break;

                    case (int)OrderTypeEnum.MobileTakeAway:
                        order.DeliveryAddress = OrderTypeEnum.MobileTakeAway.DisplayName();
                        order.Receiver        = customer.Name;
                        order.DeliveryPhone   = customer.Phone;
                        break;

                    default:
                        if (string.IsNullOrEmpty(order.DeliveryAddress))
                        {
                            throw ApiException.Get(true, ConstantManager.MES_ORDERTYPE_NOTSUPPORT, ResultEnum.OrderTypeNotSupport, HttpStatusCode.OK);
                        }
                        break;
                    }

                    #endregion

                    //get CallCenter storeid
                    //var mobileStore = storeService.GetStoresByBrandIdAndType(order.BrandId, (int)StoreTypeEnum.MobileApp).FirstOrDefault();
                    //if (mobileStore != null)
                    //{
                    //    order.StoreID = mobileStore.ID;
                    //}

                    order.GroupPaymentStatus = 0; //Tam thoi chua xài
                    order.PaymentStatus      = (int)OrderPaymentStatusEnum.Finish;
                    customer.BrandId         = order.BrandId;


                    #region Update payment
                    new PaymentDomain().UpdatePayment(order, customer, time);
                    #endregion
                    if (order.Payments.Count <= 0)
                    {
                        throw ApiException.Get(true, ConstantManager.MES_PAYMENTTYPE_NOTSUPPORT, ResultEnum.PaymenTypeNotSupport, HttpStatusCode.OK);
                    }
                    var orderTest = order.ToEntity();
                    var rs        = orderService.CreateOrder(orderTest);



                    if (rs == false)
                    {
                        throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_FAIL, ResultEnum.CreateFail, HttpStatusCode.InternalServerError);
                    }

                    #region Update voucher after used
                    CheckVoucherUsed(order.VoucherCode);
                    #endregion
                    scope.Complete();
                    scope.Dispose();
                    var orderFinal = orderService.GetOrderByRenId(orderTest.RentID);
                    orderFinal.PaymentType = paymentType;
                    return(BaseResponse <OrderHistoryAPIViewModel> .Get(true, ConstantManager.MES_CREATE_ORDER_SUCCESS, orderFinal, ResultEnum.Success));
                }
                catch (Exception e)
                {
                    scope.Dispose();
                    if (e is ApiException)
                    {
                        throw e;
                    }
                    else
                    {
                        throw ApiException.Get(false, ConstantManager.MES_CREATE_ORDER_FAIL, ResultEnum.CreateFail, HttpStatusCode.InternalServerError);
                    }
                }
            }
        }