public BaseResponse <List <RatingAPIViewModel> > GetRatingByOrderId(int orderId)
 {
     try
     {
         var service = this.Service <IRatingService>();
         var list    = service.GetRatingByOrderId(orderId);
         if (list == null)
         {
             throw ApiException.Get(true, ConstantManager.MES_RATINGPRODUCT_NOTFOUNT, ResultEnum.RatingProductNotFound, HttpStatusCode.OK);
         }
         return(BaseResponse <List <RatingAPIViewModel> > .Get(true, ConstantManager.MES_RATINGPRODUCT_OK, list, ResultEnum.Success));
     }
     catch (Exception ex)
     {
         if (ex is ApiException)
         {
             throw ex;
         }
         else
         {
             throw ApiException.Get(false, ex.ToString(), ResultEnum.InternalError, HttpStatusCode.InternalServerError);
         }
     }
     throw new NotImplementedException();
 }
Exemple #2
0
        public ActionResult Register(UserBasic request)
        {
            try
            {
                #region check model
                if (!ModelState.IsValid)
                {
                    var modelState = ModelState.FirstOrDefault();
                    var error      = modelState.Value.Errors.FirstOrDefault().ErrorMessage;
                    throw ApiException.Get(false, error, ResultEnum.ModelError, HttpStatusCode.BadRequest);
                }
                #endregion
                var task = userService.Register(brandToken, request);
                task.Wait();

                response = BaseResponse <dynamic> .Get(true, ConstantManager.Success("Register"), null, ResultEnum.Success);
            }
            catch (ApiException e)
            {
                result.StatusCode = e.StatusCode;
                response          = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);

                result = new JsonResult(response);
            }
            catch (Exception e)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                response          = BaseResponse <dynamic> .Get(false, ConstantManager.Fail("Register : ") + e.ToString(), null, ResultEnum.InternalError);
            }
            result = new JsonResult(response);
            return(result);

            // create asp user , employee , membership , account
        }
Exemple #3
0
        public ActionResult <List <PayrollPeriodResponse> > Get([FromQuery] int?empId)
        {
            try
            {
                #region check model
                if (!ModelState.IsValid)
                {
                    var modelState = ModelState.FirstOrDefault();
                    var error      = modelState.Value.Errors.FirstOrDefault().ErrorMessage;
                    throw ApiException.Get(false, error, ResultEnum.ModelError, HttpStatusCode.BadRequest);
                }
                #endregion

                var data = payrollperiodService.Get(empId);
                if (data.Count <= 0)
                {
                    throw ApiException.Get(true, ConstantManager.NotFound(" Payroll Period "), ResultEnum.PeriodNotFound, HttpStatusCode.NotFound);
                }
                response = BaseResponse <dynamic> .Get(true, ConstantManager.SUCCESS, data, ResultEnum.Success);
            }
            catch (ApiException e)
            {
                result.StatusCode = e.StatusCode;
                response          = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);

                result = new JsonResult(response);
            }
            catch (Exception e)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                response          = BaseResponse <dynamic> .Get(false, ConstantManager.Fail(e.ToString()), null, ResultEnum.InternalError);
            }
            result = new JsonResult(response);
            return(result);
        }
Exemple #4
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));
        }
Exemple #5
0
        public ActionResult Add(List <ShiftRegisterBasic> request)
        {
            try
            {
                #region check model
                if (!ModelState.IsValid)
                {
                    var modelState = ModelState.FirstOrDefault();
                    var error      = modelState.Value.Errors.FirstOrDefault().ErrorMessage;
                    throw ApiException.Get(false, error, ResultEnum.ModelError, HttpStatusCode.BadRequest);
                }
                #endregion

                shiftRegisterService.RegistShift(request);
                response = BaseResponse <dynamic> .Get(false, ConstantManager.CreateSuccess("Shift Register :"), null, ResultEnum.Success);
            }
            catch (ApiException e)
            {
                result.StatusCode = e.StatusCode;
                response          = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);

                result = new JsonResult(response);
            }
            catch (Exception e)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                response          = BaseResponse <dynamic> .Get(false, ConstantManager.Fail("Shift Register : ") + e.ToString(), null, ResultEnum.InternalError);
            }
            result = new JsonResult(response);
            return(result);
        }
Exemple #6
0
        public ActionResult Create([FromBody] PayrollPeriodBasic request)
        {
            try
            {
                #region check model
                if (!ModelState.IsValid)
                {
                    var modelState = ModelState.FirstOrDefault();
                    var error      = modelState.Value.Errors.FirstOrDefault().ErrorMessage;
                    throw ApiException.Get(false, error, ResultEnum.ModelError, HttpStatusCode.BadRequest);
                }
                #endregion

                payrollperiodService.CreatePeriod(request);
                response = BaseResponse <dynamic> .Get(true, ConstantManager.SUCCESS, null, ResultEnum.Success);
            }
            catch (ApiException e)
            {
                result.StatusCode = e.StatusCode;
                response          = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);

                result = new JsonResult(response);
            }
            catch (Exception e)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                response          = BaseResponse <dynamic> .Get(false, ConstantManager.Fail(e.ToString()), null, ResultEnum.InternalError);
            }
            result = new JsonResult(response);
            return(result);

            //var a = ResponseMessage(httpResponseMessage);
            //return result;
        }
Exemple #7
0
        public BaseResponse <Voucher> IsVoucherAvailable(Voucher voucher)
        {
            //Logger.Log("|CheckVoucherCode| voucherCode: " + model.voucherCode);
            BaseResponse <Voucher> res;

            if (voucher != null)
            {
                if ((voucher.isUsed != null && voucher.isUsed == false && voucher.Quantity > voucher.UsedQuantity) ||
                    (voucher.isUsed == null && voucher.Active && voucher.Quantity > voucher.UsedQuantity))
                {
                    //Logger.Log("|CheckVoucherCode| Có thể sử dụng voucher", true);
                    res = new BaseResponse <Voucher>
                    {
                        Success    = true,
                        Message    = "Voucher có thể áp dụng",
                        ResultCode = (int)ResultEnum.Success,
                        Data       = voucher
                    };
                    return(res);
                }
                else
                {
                    //Logger.Log("|CheckVoucherCode| Voucher đã được sử dụng", true);
                    throw ApiException.Get(false, "Voucher đã được sử dụng", ResultEnum.VoucherUsed, HttpStatusCode.BadRequest);
                }
            }

            throw ApiException.Get(false, "Mã Voucher không tồn tại", ResultEnum.VoucherNotFound, HttpStatusCode.NotFound);
        }
Exemple #8
0
        public BaseResponse <List <ProductCategoryAPIViewModel> > GetProductCategoriesByRequest(CategoryRequest <string> request)
        {
            var categoryService = this.Service <IProductCategoryService>();

            try
            {
                if (request.StoreId == null)
                {
                    throw ApiException.Get(false, "StoreId is required!", ResultEnum.StoreIdNotFound, HttpStatusCode.BadRequest);
                }
                var cateVM = categoryService.GetProductCategoriesByRequest(request);
                if (cateVM == null)
                {
                    throw ApiException.Get(true, ConstantManager.MES_PRODUCTCATEGORY_NOT_FOUND, ResultEnum.ProductCategoryNotFound, HttpStatusCode.OK);
                }
                return(BaseResponse <List <ProductCategoryAPIViewModel> > .Get(true, ConstantManager.MES_SUCCESS, cateVM, ResultEnum.Success));
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    throw ex;
                }
                throw ApiException.Get(false, ex.ToString(), ResultEnum.InternalError, HttpStatusCode.InternalServerError);
            }
        }
Exemple #9
0
        public BaseResponse <List <ProductBrandAPIViewModel> > GetProductBrand(ProductBrandRequest <string> request)
        {
            var service = this.Service <IProductBrandService>();
            var list    = service.GetProductBrand(request);

            if (list == null)
            {
                throw ApiException.Get(false, ConstantManager.MES_PRODUCTBRAND_NOTFOUND, ResultEnum.ProductBrandNotFound, HttpStatusCode.BadRequest);
            }
            return(BaseResponse <List <ProductBrandAPIViewModel> > .Get(true, ConstantManager.MES_PRODUCTBRAND_OK, list, ResultEnum.Success));
        }
Exemple #10
0
        public BaseResponse <ProductBrandAPIViewModel> UpdateProductBrand(ProductBrandAPIViewModel productBrand)
        {
            var service = this.Service <IProductBrandService>();
            var productBrandViewModel = service.UpdateProductBrand(productBrand);

            if (productBrandViewModel == null)
            {
                throw ApiException.Get(false, ConstantManager.PRODUCT_BRAND_UPDATE_FAIL, ResultEnum.ProductBrandUpdateFail, HttpStatusCode.BadRequest);
            }
            return(BaseResponse <ProductBrandAPIViewModel> .Get(true, ConstantManager.MES_UPDATE_PRODUCT_BRAND_SUCCESS, productBrandViewModel, ResultEnum.Success));
        }
        public void Add(List<AttentdenceRequest> requests)
        {
            var trans = UnitOfWork.CreateTransac();
            try
            {

                foreach (var item in requests)
                {
                    var emp = employeeService.FindById(item.EmployeeId);
                    if (emp == null)
                    {
                        throw ApiException.Get(false, ConstantManager.NotFound("Employee "), ResultEnum.EmpNotFound, HttpStatusCode.NotFound);
                    }
                    var entity = Mapper.Map<AttentdenceRequest, Attendance>(item);
                    //item.ToEntity();
                    for (int i = 0; i < item.Dates.Count; i++)
                    {
                        entity.ShiftMax = item.Dates[i].GetStartOfDate().Add(item.ShiftMaxTime[i]);
                        entity.ShiftMin = item.Dates[i].GetStartOfDate().Add(item.ShiftMaxTime[i]);
                        entity.ExpandTime = new TimeSpan();
                        entity.CheckInExpandTime = new TimeSpan(1, 0, 0);
                        entity.CheckOutExpandTime = new TimeSpan(1, 0, 0);
                        entity.ComeLateExpandTime = new TimeSpan(1, 0, 0);
                        entity.LeaveEarlyExpandTime = new TimeSpan(1, 0, 0);
                        entity.ProcessingStatus = (int)ProcessingStatusAttendenceEnum.Assign;
                        var timeFrameId = item.TimeFramId[i];
                        var tf = timeFrameService.FindById(timeFrameId);
                        if (tf == null)
                        {
                            throw ApiException.Get(false, ConstantManager.NotFound("Time Frame "), ResultEnum.TimeFrameNotFound, HttpStatusCode.NotFound);
                        }
                        entity.TimeFramId = tf.Id;
                        entity.Active = true;
                        entity.Status = (int)StatusAttendanceEnum.Processing;
                        Create(entity);
                    }
                }
                trans.Commit();
            }
            catch (Exception e)
            {
                trans.Dispose();

                if (e is ApiException)
                {
                    throw e;
                }
                else
                {
                    ApiException.Get(false, ConstantManager.FAIL, ResultEnum.InternalError, HttpStatusCode.InternalServerError);
                }
            }

        }
        //public int CountTotalOrdersOneDay(DateTime dateTime)
        //{
        //    IOrderService orderService = DependencyUtils.Resolve<IOrderService>();
        //    int count =  orderService.CountTotalOrderInOneDay(dateTime);
        //    return count;
        //}

        public BaseResponse <List <OrderHistoryAPIViewModel> > GetOrderHistoryByRequest(OrderRequest <string> request)
        {
            var ser = this.Service <IOrderService>();

            var list = ser.GetOrderHistoryByRequest(request);

            if (list.Count <= 0)
            {
                throw ApiException.Get(true, ConstantManager.MES_ORDER_HISTORY_NOTFOUND, ResultEnum.OrderHistoryNotFound, HttpStatusCode.OK);
            }
            return(BaseResponse <List <OrderHistoryAPIViewModel> > .Get(true, ConstantManager.MES_SUCCESS, list, ResultEnum.Success));
        }
Exemple #13
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;
            }
        }
Exemple #14
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));
        }
Exemple #15
0
        public BaseResponse <PromotionDetail> IsPromotionDetailValidFor(PromotionDetail pDetail, IEnumerable <OrderDetailAPIViewModel> OrderDetailAPIViewModels, Membership membership = null)
        {
            foreach (var oD in OrderDetailAPIViewModels)
            {
                if (pDetail.BuyProductCode != null && pDetail.BuyProductCode != oD.ProductCode)
                {
                    throw ApiException.Get(false, "Có sản phẩm không hợp lệ", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }

                if (pDetail.MinBuyQuantity != null)
                {
                    if (oD.Quantity < pDetail.MinBuyQuantity)
                    {
                        throw ApiException.Get(false, "Số lượng sản phẩm không phù hợp", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                    }
                }
                if (pDetail.MaxBuyQuantity != null)
                {
                    if (oD.Quantity > pDetail.MaxBuyQuantity)
                    {
                        throw ApiException.Get(false, "Số lượng sản phẩm không phù hợp", 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));
        }
Exemple #16
0
        public List <VoucherAPIViewModel> GetVoucher(VoucherQueryRequest <dynamic> request)
        {
            var voucher = GetVoucher().Where(v => (1 == 1 || v.Promotion.BrandId == request.BrandId) &&
                                             (request.VoucherId == null || v.VoucherID == request.VoucherId) &&
                                             (request.VoucherCode == null || v.VoucherCode == request.VoucherCode) &&
                                             (request.PromotionId == null || v.PromotionID == request.PromotionId) &&
                                             (request.PromotionCode == null || v.Promotion.PromotionCode == request.PromotionCode));

            //if (request.VoucherId != null)
            //    voucher = voucher.Where(v => v.VoucherID == request.VoucherId);
            //if (request.VoucherCode != null)
            //    voucher = voucher.Where(v => v.VoucherCode == request.VoucherCode);
            //if (request.PromotionId != null)
            //    voucher = voucher.Where(v => v.PromotionID == request.PromotionId);
            //if (request.PromotionCode != null)
            //    voucher = voucher.Where(v => v.Promotion.PromotionCode == request.PromotionCode);
            if (request.AvailableOnly)
            {
                if (request.MembershipVM == null)
                {
                    throw ApiException.Get(false, "Thiếu thông tin thành viên", ResultEnum.MembershipNotFound, HttpStatusCode.BadRequest);
                }
                voucher = voucher.Where(v => !v.isUsed.Value &&
                                        v.UsedQuantity < v.Quantity && v.MembershipCardId == request.MembershipVM.Id);
            }
            if (request.UsedOnly)
            {
                if (request.MembershipVM == null)
                {
                    throw ApiException.Get(false, "Thiếu thông tin thành viên", ResultEnum.MembershipNotFound, HttpStatusCode.BadRequest);
                }
                voucher = voucher.Where(v => v.isUsed.Value &&
                                        v.UsedQuantity >= v.Quantity && v.MembershipCardId == request.MembershipVM.Id);
            }
            var voucherVM = voucher.AsQueryable().ProjectTo <VoucherAPIViewModel>(this.AutoMapperConfig).ToList();

            if (voucherVM.Count < 0)
            {
                throw ApiException.Get(false, "Không tìm thấy voucher nào", ResultEnum.VoucherNotFound, HttpStatusCode.NotFound);
            }
            return(voucherVM);
        }
        public BaseResponse <string> DeleteDelivery(int deliveryId, int customerId)
        {
            if (customerId == 0)
            {
                throw ApiException.Get(false, ConstantManager.MES_DELETE_DELIVERY_FAIL, ResultEnum.CustomerIdInTokenWrong, HttpStatusCode.NotFound);
            }
            var deliService     = this.Service <IDeliveryInfoService>();
            var deliveryInfoOld = deliService.GetDeliveriesByCustomerId(customerId);
            var deli            = deliveryInfoOld.Where(p => p.Id == deliveryId).FirstOrDefault();

            if (deli == null)
            {
                throw ApiException.Get(false, ConstantManager.MES_DELIVERYID_WRONG, ResultEnum.DeleteFail, HttpStatusCode.NotFound);
            }
            else
            {
                deliService.DeleteDelivery(deli);
                return(BaseResponse <string> .Get(true, ConstantManager.MES_DELETE_DELIVERY_SUCCESS, null, ResultEnum.Success));
            }
        }
        public BaseResponse <RatingAPIViewModel> UpdateRatingProduct(RatingAPIViewModel rating)
        {
            var service = this.Service <IRatingService>();
            var list    = service.GetRatingByProductId(rating.Id);

            if (list == null)
            {
                throw ApiException.Get(false, ConstantManager.MES_RATINGPRODUCT_NOTEXIST, ResultEnum.RatingProductNotExist, HttpStatusCode.BadRequest);
            }
            var service2 = this.Service <IProductService>();
            var list2    = service2.GetProductById(rating.ProductId.Value);

            if (list2 == null)
            {
                throw ApiException.Get(false, ConstantManager.MES_PRODUCT_NOTEXIST, ResultEnum.ProductNotExist, HttpStatusCode.BadRequest);
            }
            var rt = service.UpdateRatingProduct(rating);

            return(BaseResponse <RatingAPIViewModel> .Get(true, ConstantManager.MES_RATINGPRODUCT_UPDATE_SUCCESS, rt, ResultEnum.Success));
        }
        public BaseResponse <DeliveryAPIViewModel> CreateDelivery(DeliveryAPIViewModel deli)
        {
            var deliService = this.Service <IDeliveryInfoService>();

            if (deli.CustomerId == 0)
            {
                throw ApiException.Get(false, ConstantManager.MES_CREATE_DELIVERY_FAIL, ResultEnum.CustomerIdInTokenWrong, HttpStatusCode.NotFound);
            }
            var deliveryInfoOld = deliService.GetDeliveriesByCustomerId(deli.CustomerId.Value);

            if (deliveryInfoOld.Count == (int)ConstantManager.MAX_DELIVERYINFO)
            {
                throw ApiException.Get(false, ConstantManager.MES_DELIVERY_MAX, ResultEnum.DeliveryMax, HttpStatusCode.BadRequest);
            }
            if (deliveryInfoOld.Count() == 0)
            {
                deli.isDefaultDeliveryInfo = true;
            }
            if (deli.isDefaultDeliveryInfo == true)
            {
                foreach (var item in deliveryInfoOld)
                {
                    if (item.isDefaultDeliveryInfo == true)
                    {
                        item.isDefaultDeliveryInfo = false;
                        UpdateDelivery(item);
                    }
                }
            }
            var deliVM = deliService.CreateDelivery(deli);

            if (deliVM != null)
            {
                return(BaseResponse <DeliveryAPIViewModel> .Get(true, ConstantManager.MES_CREATE_DELIVERY_SUCCESS, deliVM, (int)ResultEnum.Success));
            }
            else
            {
                throw ApiException.Get(false, ConstantManager.MES_CREATE_DELIVERY_FAIL, ResultEnum.CreateFail, HttpStatusCode.NotFound);
            }
        }
        public BaseResponse <DeliveryAPIViewModel> UpdateDelivery(DeliveryAPIViewModel deliVM)
        {
            var deliService = this.Service <IDeliveryInfoService>();

            if (deliVM.CustomerId == 0)
            {
                throw ApiException.Get(false, ConstantManager.MES_DELETE_DELIVERY_FAIL, ResultEnum.CustomerIdInTokenWrong, HttpStatusCode.NotFound);
            }
            var deliveryInfoOld = deliService.GetDeliveriesByCustomerId(deliVM.CustomerId.Value);
            var deli            = deliveryInfoOld.Where(p => p.Id == deliVM.Id).FirstOrDefault();

            if (deli == null)
            {
                throw ApiException.Get(false, ConstantManager.MES_DELIVERYID_WRONG, ResultEnum.UpdateFail, HttpStatusCode.NotFound);
            }
            else
            {
                if (deliVM.isDefaultDeliveryInfo == true)
                {
                    foreach (var item in deliveryInfoOld)
                    {
                        if (item.isDefaultDeliveryInfo == true)
                        {
                            item.isDefaultDeliveryInfo = false;
                            deliService.UpdateDelivery(item);
                        }
                    }
                }

                deliVM = deliService.UpdateDelivery(deliVM);
                if (deliVM == null)
                {
                    throw ApiException.Get(false, ConstantManager.MES_UPDATE_FAIL, ResultEnum.UpdateFail, HttpStatusCode.NotFound);
                }
                else
                {
                    return(BaseResponse <DeliveryAPIViewModel> .Get(true, ConstantManager.MES_UPDATE_SUCCESS, deliVM, (int)ResultEnum.Success));
                }
            }
        }
Exemple #21
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));
        }
 public BaseResponse<CustomerAPIViewModel> UpdateCustomer(CustomerAPIViewModel customer)
 {
     var customerService = this.Service<ICustomerService>();
     try
     {
         var customerVM = customerService.UpdateCustomer(customer);
         if (customerVM == null)
         {
             throw ApiException.Get(false, ConstantManager.MES_UPDATE_FAIL, ResultEnum.UpdateFail, HttpStatusCode.InternalServerError);
         }
         var account = customerVM.MembershipVM.AccountVMs;
         foreach (var item in account)
         {
             if (item.Type == (int)AccountTypeEnum.CreditAccount)
             {
                 customerVM.Balance = item.Balance == null ? 0 : item.Balance.Value;
             }
             if (item.Type == (int)AccountTypeEnum.PointAccount)
             {
                 customerVM.Point = item.Balance == null ? 0 : item.Balance.Value;
             }
         }
         return BaseResponse<CustomerAPIViewModel>.Get(true, ConstantManager.MES_UPDATE_SUCCESS, customerVM, ResultEnum.Success);
     }
     catch (Exception e)
     {
         if(e is ApiException)
         {
             throw e;
         }
         else
         {
             throw ApiException.Get(false, e.ToString(), ResultEnum.InternalError, HttpStatusCode.InternalServerError);
         }
         
     }
     
 }
Exemple #23
0
 public BaseResponse <ProductCategoryAPIViewModel> GetCategoryByExtraId(int extraID)
 {
     try
     {
         var categoryService = this.Service <IProductCategoryService>();
         var cate            = categoryService.GetCategoryById(extraID);
         if (cate == null)
         {
             throw ApiException.Get(true, ConstantManager.MES_PRODUCTCATEGORY_NOT_FOUND, ResultEnum.RatingProductNotFound, HttpStatusCode.OK);
         }
         return(BaseResponse <ProductCategoryAPIViewModel> .Get(true, ConstantManager.MES_SUCCESS, cate, ResultEnum.Success));
     }
     catch (Exception ex)
     {
         if (ex is ApiException)
         {
             throw ex;
         }
         else
         {
             throw ApiException.Get(false, ex.ToString(), ResultEnum.InternalError, HttpStatusCode.InternalServerError);
         }
     }
 }
Exemple #24
0
        //public BaseResponse<Promotion> IsPromotionValidFor(int promotionId, IEnumerable<OrderDetailAPIViewModel> OrderDetailAPIViewModels, OrderAPIViewModel order, string cardCode = null)
        //{
        //    var promotion = GetPromotion(promotionId);
        //    Membership membership = null;
        //    if (cardCode != null)
        //        membership = this.Service<IMembershipService>().GetMembershipByCode(cardCode);
        //    return IsPromotionValidFor(promotion, OrderDetailAPIViewModels, order, membership);
        //}

        //public BaseResponse<Promotion> IsPromotionValidFor(string promotionCode, IEnumerable<OrderDetailAPIViewModel> OrderDetailAPIViewModels, OrderAPIViewModel order, string cardCode = null)
        //{
        //    var promotion = GetPromotion(promotionCode);
        //    Membership membership = null;
        //    if (cardCode != null)
        //        membership = this.Service<IMembershipService>().GetMembershipByCode(cardCode);
        //    return IsPromotionValidFor(promotion, OrderDetailAPIViewModels, order, membership);
        //}

        //public BaseResponse<Promotion> IsPromotionValidFor(Promotion promotion, IEnumerable<OrderDetailAPIViewModel> OrderDetailAPIViewModels, OrderAPIViewModel order, Membership membership = null)
        //{
        //    var gCheck = CheckGeneralPromotionRule(promotion, order);
        //    if (!gCheck.Success)
        //        return BaseResponse<Promotion>.Get(false, gCheck.Message, null, ResultEnum.Success, gCheck.Error);

        //    var pDetails = GetPromotionDetailsByPromotion(promotion.PromotionCode);

        //    var mCheck = CheckMembership(promotion, pDetails, membership);
        //    if (!mCheck.Success)
        //        return BaseResponse<Promotion>.Get(false, mCheck.Message, null, ResultEnum.Success, mCheck.Error);

        //    if (promotion.ApplyLevel == (int)PromotionApplyLevelEnum.OrderDetailAPIViewModel)
        //    {
        //        foreach (var pD in pDetails)
        //        {
        //            var pDetailCheck = IsPromotionDetailValidFor(pD, OrderDetailAPIViewModels, membership);
        //            if (!pDetailCheck.Success)
        //                return BaseResponse<Promotion>.Get(false, pDetailCheck.Message, null, ResultEnum.Success, pDetailCheck.Error);
        //        }
        //    }
        //    else return BaseResponse<Promotion>.Get(
        //        false, "This is an OrderAPIViewModel level promotion", null,
        //        ResultEnum.Success, "This is an OrderAPIViewModel level promotion");

        //    return BaseResponse<Promotion>.Get(true, "Promotion can be applied", promotion, ResultEnum.Success, null);
        //}

        private BaseResponse <bool> CheckMembership(
            Promotion promotion, IEnumerable <PromotionDetail> pDetails, Membership membership = null)
        {
            if ((promotion.GiftType == (int)PromotionGiftTypeEnum.CashbackDiscountAmount ||
                 promotion.GiftType == (int)PromotionGiftTypeEnum.CashbackDiscountAmount ||
                 promotion.IsForMember))
            {
                if (membership == null)
                {
                    throw ApiException.Get(false, "Khuyến mãi không áp dụng cho thành viên này", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }

                var code = membership.MembershipType.AppendCode + "_" + membership.MembershipCode;

                if (!pDetails.AsEnumerable().Any(pD => Regex.IsMatch(code, pD.RegExCode)))
                {
                    throw ApiException.Get(false, "Khuyến mãi không áp dụng cho thành viên này", ResultEnum.VoucherNotAvailable, HttpStatusCode.BadRequest);
                }
            }

            return(BaseResponse <bool> .Get(
                       true, "OK",
                       true, ResultEnum.Success, "OK"));
        }
Exemple #25
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;
            }
        }
Exemple #26
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                employeeService = context.HttpContext.RequestServices.GetService <IEmployeeService>();
                var blockList  = new List <string>();
                var exceptList = new List <string>();
                if (!string.IsNullOrEmpty(Block))
                {
                    blockList = Block.Trim().Split(',').ToList();
                }
                if (!string.IsNullOrEmpty(Except))
                {
                    exceptList = Except.Trim().Split(',').ToList();
                }
                _request = context.HttpContext.Request;
                var query = _request.Query;

                _authorization = _request.Headers.FirstOrDefault(p => p.Key.Equals("Authorization")).Value.ToString();
                if (_authorization == null || string.IsNullOrEmpty(_authorization))
                {
                    throw ApiException.Get(false, ConstantManager.MES_AUTHORIZATION_NOT_FOUND, ResultEnum.AuthorizationNotFound, HttpStatusCode.BadRequest);
                }
                else
                {
                    var tokenJWT = Utils.DecodeJwtToken(_authorization);
                    // get List role
                    var role   = tokenJWT.Claims.Where(c => c.Type == "role").Select(c => c.Value).ToList();
                    var unique = tokenJWT.Claims.Where(c => c.Type == "unique_name").FirstOrDefault().Value.ToString();
                    var email  = unique.Split('-')[0];
                    var emp    = employeeService.Get(email).FirstOrDefault();
                    if (!role.Contains(RoleTypeEnum.ActiveUser.ToString()))
                    {
                        throw ApiException.Get(false, ConstantManager.MES_NOT_ACTIVE, ResultEnum.NotActive, HttpStatusCode.NotAcceptable);
                    }
                    if (!role.Contains(RoleTypeEnum.Administrator.ToString()))
                    {
                        if (query.Count() == 0)
                        {
                            throw ApiException.Get(false, ConstantManager.MES_REQUEST_DENY, ResultEnum.NotAcceptable, HttpStatusCode.NotAcceptable);
                        }
                        else
                        {
                            var id = query.FirstOrDefault(p => p.Key.Equals("id")).Value;
                            if (id != emp.Id)
                            {
                                throw ApiException.Get(false, ConstantManager.MES_REQUEST_DENY, ResultEnum.NotAcceptable, HttpStatusCode.NotAcceptable);
                            }
                        }
                    }
                    //foreach (var e in exceptList)
                    //{
                    //    if (role.Contains(e.ToString()))
                    //    {
                    //        return;
                    //    }
                    //}

                    //foreach (var item in blockList)
                    //{
                    //    var a = (RoleTypeEnum[])Enum.GetValues(typeof(RoleTypeEnum));
                    //    var check = a.FirstOrDefault(e => e.ToString().Contains(item)).ToString();
                    //    if (check == null)
                    //    {
                    //        throw ApiException.Get(false, ConstantManager.MES_ROLE_WRONG, ResultEnum.AttributeWrong, HttpStatusCode.BadRequest);

                    //    }
                    //    if (role.Contains(item))
                    //    {
                    //        throw ApiException.Get(false, ConstantManager.MES_REQUEST_DENY, ResultEnum.RoleNotSupport, HttpStatusCode.NotAcceptable);
                    //    }
                    //}
                    return;
                }
            }
            catch (ApiException e)
            {
                result.StatusCode = e.StatusCode;
                result.Value      = BaseResponse <dynamic> .Get(e.Success, e.ErrorMessage, null, e.ErrorStatus);
            }
            catch (Exception e)
            {
                result.StatusCode = (int)HttpStatusCode.InternalServerError;
                result.Value      = BaseResponse <dynamic> .Get(false, ConstantManager.Fail(" Authentication   : ") + e.ToString(), null, ResultEnum.InternalError);
            }
            context.Result = result;
        }
        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 BaseResponse <RatingAPIViewModel> CreateRatingProduct(RatingAPIViewModel rating)
        {
            var service         = this.Service <IRatingService>();
            var productService  = this.Service <IProductService>();
            var customerService = this.Service <ICustomerService>();
            var orderService    = this.Service <IOrderService>();

            try
            {
                if (rating.CustomerId == 0)
                {
                    throw ApiException.Get(false, ConstantManager.MES_CUSTOMER_NOTFOUND, ResultEnum.CustomerIdInTokenWrong, HttpStatusCode.BadRequest);
                }
                var customer = customerService.GetCustomerById(rating.CustomerId.Value);
                if (customer == null)
                {
                    throw ApiException.Get(false, ConstantManager.MES_CUSTOMER_NOTFOUND, ResultEnum.CustomerNotFound, HttpStatusCode.BadRequest);
                }
                else
                {
                    if (rating.ProductId != null && rating.OrderId != null)
                    {
                        throw ApiException.Get(false, ConstantManager.MES_RATE_VALID, ResultEnum.RateValid, HttpStatusCode.BadRequest);
                    }
                    else
                    {
                        rating.ReviewEmail = customer.Email;
                        rating.ReviewName  = customer.Name;
                        rating.Verified    = false;
                        if (rating.ProductId != null)
                        {
                            var check = productService.GetProductById(rating.ProductId.Value);
                            if (check == null)
                            {
                                throw ApiException.Get(false, ConstantManager.MES_PRODUCT_NOTEXIST, ResultEnum.ProductNotExist, HttpStatusCode.BadRequest);
                            }
                        }
                        if (rating.OrderId != null)
                        {
                            var check = orderService.GetOrderById(rating.OrderId.Value);
                            if (check == null)
                            {
                                throw ApiException.Get(false, ConstantManager.MES_ORDER_NOT_FOUND, ResultEnum.OrderNotFound, HttpStatusCode.BadRequest);
                            }
                            if (check.CustomerID != rating.CustomerId)
                            {
                                throw ApiException.Get(false, ConstantManager.MES_REQUEST_DENY, ResultEnum.CustomerIdNotMatch, HttpStatusCode.BadRequest);
                            }
                        }
                        var rt = service.CreateRatingProduct(rating);
                        return(BaseResponse <RatingAPIViewModel> .Get(true, ConstantManager.MES_RATING_CREATE_SUCCESS, rt, ResultEnum.Success));
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    throw ex;
                }
                else
                {
                    throw ApiException.Get(false, ConstantManager.MES_RATING_CREATE_FAIL, ResultEnum.CreateFail, HttpStatusCode.InternalServerError);
                }
            }
        }
        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);
                    }
                }
            }
        }
Exemple #30
0
        public async Task <UserResponse> Login(string brandToken, UserLoginRequest model)
        {
            try
            {
                var result = new UserResponse();
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://authorizecore.unicode.edu.vn");
                    var oBject = new
                    {
                        Email      = model.Email,
                        Password   = model.Password,
                        brandToken = brandToken
                    };

                    var response = await client.PostAsJsonAsync("/api/authorize/login", oBject);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseObj = await response.Content.ReadAsAsync <JObject>();

                        var token = responseObj.SelectToken("token").ToString();
                        var role  = responseObj.SelectToken("roles").ToArray();
                        var emp   = employeeService.Get(model.Email).FirstOrDefault();
                        result.Token    = token;
                        result.Employee = emp;
                        result.Role     = role;
                        var loyaltyResponse = RootConfig.LoyaltyClient.MembershipsApi.Get(new ResoLoyalty.Client.Models.Request.MembershipRequest()
                        {
                            of_emp_code = emp.EmpEnrollNumber,
                            includes    = new List <string>()
                            {
                                MembershipRequest.Basic,
                                MembershipRequest.CreditAcc
                            }
                        }).Result;
                        var membership = loyaltyResponse.Content.ReadAsAsync <BaseResponse <IEnumerable <Membership> > >().Result.Data.FirstOrDefault();
                        result.Membership = membership;
                        //var tokenJWT = Utils.DecodeJwtToken(token);
                        //tokenJWT.Claims.Where(p => p.Type )
                        //var email = data.SelectToken("email").ToString();
                        //employeeService.Add(model);
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw ApiException.Get(false, ConstantManager.UNAUTHORIZED, ResultEnum.Unauthorization, HttpStatusCode.Unauthorized);
                        }
                        else
                        {
                            throw ApiException.Get(false, ConstantManager.FAIL, ResultEnum.InternalError, HttpStatusCode.InternalServerError);
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    throw ex;
                }
                else
                {
                    throw  ApiException.Get(false, ConstantManager.FAIL, ResultEnum.InternalError, HttpStatusCode.InternalServerError);
                }
            }
        }