Exemple #1
0
 public JsonResult RemoveDetail(PromotionDetail model)
 {
     _promotionDetailRepository.Delete(o => o.id_ == model.id_);
     _promotionRepository.ClearBannerCache();
     _unitOfWork.Commit();
     return(Json(new {}, JsonRequestBehavior.AllowGet));
 }
Exemple #2
0
        private void AddProgressToPromotion(Guid accoundId, PromotionDetail promotionDetail, ActivePromotion activePromotion)
        {
            var progressDetail = _promotionDao.GetProgress(accoundId, promotionDetail.Id);

            activePromotion.Progress   = GetProgress(promotionDetail, progressDetail);
            activePromotion.UnlockGoal = GetUnlockGoal(promotionDetail);
        }
        public ActionResult GiaSalePage()
        {
            string     barcode    = Request.QueryString.Get("barcode");
            int        Idmenu     = 0;
            decimal    gia        = 0;
            decimal    giakm      = 0;
            MenuOption menuOption = _menuOptionRepository.Get(o => o.Barcode == barcode);
            // kiem tra barcode đó có khuyến mãi hay không
            PromotionDetail  HasSalePage = _promotionDetailRepository.CheckKhuyenMaiSalePage(barcode);
            GiaSalePageModel model       = new GiaSalePageModel();

            if (menuOption != null)
            {
                Idmenu = menuOption.IdMenu;
                Menu menu = _menuRepository.Get(o => o.id_ == Idmenu);
                if (HasSalePage != null)
                {
                    // co khuyen mai
                    giakm = HasSalePage.PriceDiscount;
                }
                gia   = Convert.ToInt32(menu.PricePro);
                model = new GiaSalePageModel()
                {
                    GiaKM       = giakm,
                    HasSalePage = HasSalePage,
                    Gia         = gia
                };
            }
            return(View("GiaSalepage", model));
        }
Exemple #4
0
        public void Handle(PromotionCreated @event)
        {
            using (var context = _contextFactory.Invoke())
            {
                var promotionDetail = new PromotionDetail
                {
                    Id                      = @event.SourceId,
                    Name                    = @event.Name,
                    Description             = @event.Description,
                    StartDate               = @event.StartDate,
                    EndDate                 = @event.EndDate,
                    StartTime               = @event.StartTime,
                    EndTime                 = @event.EndTime,
                    DaysOfWeek              = @event.DaysOfWeek.ToJson(),
                    AppliesToCurrentBooking = @event.AppliesToCurrentBooking,
                    AppliesToFutureBooking  = @event.AppliesToFutureBooking,
                    DiscountValue           = @event.DiscountValue,
                    DiscountType            = @event.DiscountType,
                    MaxUsagePerUser         = @event.MaxUsagePerUser,
                    MaxUsage                = @event.MaxUsage,
                    Code                    = @event.Code,
                    PublishedStartDate      = @event.PublishedStartDate,
                    PublishedEndDate        = @event.PublishedEndDate,
                    TriggerSettings         = @event.TriggerSettings,
                    Active                  = true,
                    Deleted                 = false
                };

                context.Save(promotionDetail);
            }
        }
        public void DeletePromotionDetail(int Id)
        {
            PromotionDetail deletedPromotion = GetPromotionDetailById(Id);

            Context.PromotionDetail.Remove(deletedPromotion);
            Context.Entry(deletedPromotion).State = EntityState.Deleted;
            Context.SaveChanges();
        }
 //PromotionDetail
 #region
 public static PromotionDetailDto MappingDto(this PromotionDetail promotionDetail)
 {
     return(new PromotionDetailDto
     {
         Id = promotionDetail.Id,
         Content = promotionDetail.Content,
         Discount = promotionDetail.Discount,
         PromotionId = promotionDetail.PromotionId
     });
 }
Exemple #7
0
        private bool IsExpired(PromotionDetail promo, DateTime now)
        {
            var endDateTime = promo.GetEndDateTime();

            if (endDateTime.HasValue && endDateTime.Value <= now)
            {
                return(true);
            }

            return(false);
        }
Exemple #8
0
 public ActionResult ThemPromotion(Promotion pro, PromotionDetail detail)
 {
     if (ModelState.IsValid)
     {
         QuanLy ql = new QuanLy();
         ql.AddPromotion(pro, detail);
         return(RedirectToAction("Promotion"));
     }
     ViewBag.IDPromo = new SelectList(__db.Promotions, "ID", "Name", pro.ID);
     return(View(pro));
 }
Exemple #9
0
        private double?GetUnlockGoal(PromotionDetail promotionDetail)
        {
            if (promotionDetail.TriggerSettings.Type == PromotionTriggerTypes.RideCount)
            {
                return(promotionDetail.TriggerSettings.RideCount);
            }
            else if (promotionDetail.TriggerSettings.Type == PromotionTriggerTypes.AmountSpent)
            {
                return(promotionDetail.TriggerSettings.AmountSpent);
            }

            return(null);
        }
Exemple #10
0
        // Xuất danh sách Promotions
        public List <PromotionDetail> LoadPromotions(string productid)
        {
            List <PromotionDetail> promotionsList = new List <PromotionDetail>();

            DataTable data = DataProvider.Instance.ExecuteQuery("SELECT * FROM PromotionDetail WHERE PRODUCTID = N'" + productid + "'");

            foreach (DataRow item in data.Rows)
            {
                PromotionDetail promotions = new PromotionDetail(item);
                promotionsList.Add(promotions);
            }

            return(promotionsList);
        }
Exemple #11
0
 public ActionResult SuaPromotion(Promotion pro, PromotionDetail detail)
 {
     if (ModelState.IsValid)
     {
         QuanLy ql = new QuanLy();
         ql.UpdatePromotion(pro, detail);
         __db.Entry(pro).State = EntityState.Modified;
         __db.SaveChanges();
         __db.Entry(detail).State = EntityState.Modified;
         __db.SaveChanges();
         ViewBag.IDPromotion = new SelectList(__db.Brands, "ID", "Name", pro.ID);
         return(RedirectToAction("Promotion"));
     }
     return(View(pro));
 }
        private PromotionDetailViewModel MapToPromotionDetailViewModel(PromotionDetail entity)
        {
            if (entity == null)
            {
                return(null);
            }
            var pDetailVM        = entity.To <PromotionDetailViewModel>();
            var listGiftDetailVM = new List <GiftDetailViewModel>();

            foreach (var gD in entity.GiftDetails)
            {
                var gDetailVM = gD.To <GiftDetailViewModel>();
                GiftDetailViewModel tmpGDVM = gD.GiftDetail1 != null?gD.GiftDetail1.To <GiftDetailViewModel>() : null;

                gDetailVM.AndDetailVM = tmpGDVM;
                var tmpGD = gD.GiftDetail1;
                while (tmpGD.GiftDetail1 != null)
                {
                    tmpGDVM.AndDetailVM = tmpGD.GiftDetail1.To <GiftDetailViewModel>();
                    tmpGDVM             = tmpGDVM.AndDetailVM;
                    tmpGD = tmpGD.GiftDetail1;
                }
                listGiftDetailVM.Add(gDetailVM);
            }
            pDetailVM.GiftDetailsVM = listGiftDetailVM;

            var situationList = new List <int>();

            foreach (var s in entity.PromotionApplySituations)
            {
                situationList.Add(s.ApplySituation);
            }
            pDetailVM.ApplySituations = situationList;

            var typeList = new List <int>();

            foreach (var t in entity.PromotionTypes)
            {
                typeList.Add(t.Type);
            }
            pDetailVM.PromotionTypes = typeList;

            pDetailVM.CustomerCashbackDetailsVM  = entity.CustomerCashbackDetails.ToListVM <CustomerCashbackDetail, CustomerCashbackDetailViewModel>();
            pDetailVM.AffliatorCashbackDetailsVM = entity.AffliatorCashbackDetails.ToListVM <AffliatorCashbackDetail, AffliatorCashbackDetailViewModel>();

            return(pDetailVM);
        }
Exemple #13
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 #14
0
        private double?GetProgress(PromotionDetail promotionDetail, PromotionProgressDetail progressDetail)
        {
            if (promotionDetail.TriggerSettings.Type == PromotionTriggerTypes.RideCount)
            {
                return((progressDetail == null || progressDetail.RideCount == null)
                        ? 0
                        : progressDetail.RideCount);
            }
            else if (promotionDetail.TriggerSettings.Type == PromotionTriggerTypes.AmountSpent)
            {
                return((progressDetail == null || progressDetail.AmountSpent == null)
                        ? 0.0
                        : progressDetail.AmountSpent);
            }

            return(null);
        }
Exemple #15
0
        public ActionResult View(Int32 pid)
        {
            var mainInfo = new PromotionDetail();

            try
            {
                mainInfo.PromotionInfo = promotionBLL.GetPromotionInfoModel(pid);
                if (mainInfo.PromotionInfo == null)
                {
                    return(new TransferResult("/Error/404.html"));
                }
                mainInfo.SkuList = promotionBLL.GetPromotionSkuList(pid);
            }
            catch (Exception ext)
            {
                LogHelper.Error(ext);
            }

            return(View(mainInfo));
        }
Exemple #16
0
 public PromoCodeModel(PromotionDetail promoDetail) : this()
 {
     Id                      = promoDetail.Id;
     Name                    = promoDetail.Name;
     Description             = promoDetail.Description;
     StartDate               = promoDetail.StartDate;
     EndDate                 = promoDetail.EndDate;
     StartTime               = promoDetail.StartTime;
     EndTime                 = promoDetail.EndTime;
     DaysOfWeek              = promoDetail.DaysOfWeek.FromJson <DayOfWeek[]>();
     AppliesToCurrentBooking = promoDetail.AppliesToCurrentBooking;
     AppliesToFutureBooking  = promoDetail.AppliesToFutureBooking;
     DiscountValue           = promoDetail.DiscountValue;
     DiscountType            = promoDetail.DiscountType;
     MaxUsagePerUser         = promoDetail.MaxUsagePerUser;
     MaxUsage                = promoDetail.MaxUsage;
     Code                    = promoDetail.Code;
     Active                  = promoDetail.Active;
     PublishedStartDate      = promoDetail.PublishedStartDate;
     PublishedEndDate        = promoDetail.PublishedEndDate;
     TriggerSettings         = promoDetail.TriggerSettings ?? new PromotionTriggerSettings();
 }
Exemple #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));
        }
        public async Task <ApiResult <string> > AddProductToPromotion(string promotionId, PromotionDetailForCreationDto creationDto)
        {
            var checkPromotion = await _context.Promotions.Where(x => x.Id == promotionId).SingleOrDefaultAsync();

            if (checkPromotion == null)
            {
                return(new ApiResult <string>(HttpStatusCode.NotFound, $"Không tìm thấy chương trình khuyến mãi có mã: {promotionId}"));
            }
            if (checkPromotion.ToDate <= DateTime.Now)
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Không thể thêm sản phẩm vào chương trình khuyến mãi đã hết hạn"));
            }
            var checkProduct = await(from pd in _context.PromotionDetails
                                     join p in _context.Promotions on pd.PromotionId equals p.Id
                                     where p.Id == promotionId && pd.ProductId == creationDto.ProductId select pd).SingleOrDefaultAsync();

            if (checkProduct != null)
            {
                return(new ApiResult <string>(HttpStatusCode.BadRequest, $"Chương trình khuyến mãi đã có sản phẩm này"));
            }
            var promotionDetails = new PromotionDetail()
            {
                Id            = Guid.NewGuid().ToString("D"),
                DiscountType  = creationDto.DiscountType,
                DiscountValue = creationDto.DiscountValue,
                ProductId     = creationDto.ProductId,
                PromotionId   = checkPromotion.Id
            };
            await _context.PromotionDetails.AddAsync(promotionDetails);

            await _context.SaveChangesAsync();

            return(new ApiResult <string>(HttpStatusCode.OK)
            {
                ResultObj = promotionDetails.Id
            });
        }
Exemple #19
0
 public static void MappingPromotionDetail(this PromotionDetailDto promotionDetailDto, PromotionDetail promotionDetail)
 {
     promotionDetail.Id          = promotionDetailDto.Id;
     promotionDetail.Content     = promotionDetailDto.Content;
     promotionDetail.Discount    = promotionDetailDto.Discount;
     promotionDetail.PromotionId = promotionDetailDto.PromotionId;
 }
Exemple #20
0
 public void UpdatePromotionDetail(PromotionDetail PromotionDetail)
 {
     Context.Entry(PromotionDetail).State = EntityState.Modified;
     Context.SaveChanges();
 }
        public ActionResult Submit(FormOrderSalePage model)
        {
            // lấy giá và tên sản phẩm từ barcode
            if (string.IsNullOrEmpty(model.Barcode))
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                int  idsanpham = _menuOptionRepository.Get(o => o.Barcode.Equals(model.Barcode)).IdMenu;
                Menu sanpham   = _menuRepository.Get(o => o.id_ == idsanpham);

                #region Insert DetailMenuComment

                DetailMenuComment order = new DetailMenuComment()
                {
                    id_Menu        = 9999,
                    idBrand        = 48611, // đẩy hết về Phú Nhuận
                    Name           = model.Name,
                    Link           = model.Phone.Trim().TrimEnd().TrimStart(),
                    Code           = "Đặt hàng từ Website",
                    Content        = model.Note,
                    HuongDanSuDung = "",
                    GiaoHang       = model.Adress,
                    sDate          = DateTime.Now,
                    sDateOk        = DateTime.Now
                };
                _detailMenuCommentRepository.Add(order);

                #endregion

                IList <string>        str          = new List <string>();
                IList <KHLHProduct>   khlhProducts = new List <KHLHProduct>();
                DetailMenuCommentItem detail       = new DetailMenuCommentItem();
                //kiem tra khuyen mai
                string          giakm       = "";
                PromotionDetail HasSalePage = _promotionDetailRepository.CheckKhuyenMaiSalePage(model.Barcode);
                if (HasSalePage != null)
                {
                    // co khuyen mai
                    giakm = HasSalePage.PriceDiscount.ToString();
                    #region Insert DetailMenuCommentItem
                    // co khuyen mai
                    detail = new DetailMenuCommentItem()
                    {
                        id_Menu = order.id_,
                        Name    = sanpham.NameProduct,
                        Link    = idsanpham + "",
                        Price   = sanpham.PricePro + "",
                        PriceOf = giakm,
                        Content = string.Format("Mã đơn hàng<#{0}#>", order.id_),
                        Number  = 1,
                        BarCode = model.Barcode,
                        sDate   = DateTime.Now,
                        sDateOk = DateTime.Now,
                        Img     = sanpham.Img
                    };
                    khlhProducts.Add(new KHLHProduct()
                    {
                        Code      = detail.BarCode,
                        GiaWeb    = int.Parse(detail.PriceOf),
                        NgayTao   = detail.sDate,
                        SL        = 1, //1 là số lượng sản phẩm đặt hàng
                        LinkImage = "https://beautygarden.vn/Upload/Files/" + sanpham.Img
                    });
                }
                else
                {
                    // không co khuyen mai
                    detail = new DetailMenuCommentItem()
                    {
                        id_Menu = order.id_,
                        Name    = sanpham.NameProduct,
                        Link    = idsanpham + "",
                        Price   = sanpham.PricePro + "",
                        PriceOf = sanpham.PricePro + "",
                        Content = string.Format("Mã đơn hàng<#{0}#>", order.id_),
                        Number  = 1,
                        BarCode = model.Barcode,
                        sDate   = DateTime.Now,
                        sDateOk = DateTime.Now,
                        Img     = sanpham.Img
                    };
                    khlhProducts.Add(new KHLHProduct()
                    {
                        Code      = detail.BarCode,
                        GiaWeb    = int.Parse(detail.PriceOf),
                        NgayTao   = detail.sDate,
                        SL        = 1, //1 là số lượng sản phẩm đặt hàng
                        LinkImage = "https://beautygarden.vn/Upload/Files/" + sanpham.Img
                    });
                }
                _detailMenuCommentItemRepository.Add(detail);
                str.Add(string.Format("{0}({1})", model.Barcode, 1)); //1 là số lượng sản phẩm đặt hàng
                #endregion

                #region insert KH_LH
                string dh = string.Format("{0}#,{1}", order.id_, string.Join(",", str));

                string sql =
                    string.Format(
                        "INSERT INTO [bg.hvnet.vn].dbo.KH_LH (NguoiNhap,Nguon,Ten,Phone,DiaChi,GhiChu,idTinh,TrangThai,DonHang,idShop) values (" +
                        " '{0}',{1},N'{2}','{3}',N'{4}',N'{5}',{6},{7},'{8}',{9} " +
                        ")", "system", 1,
                        order.Name,
                        order.Link,
                        order.GiaoHang,
                        order.Content,
                        1,
                        0,
                        dh,
                        order.idBrand
                        );

                int id = _detailMenuCommentRepository.InsertIntoKHLH(sql, order.Link);

                #endregion

                #region Insert KH_LH_product
                if (khlhProducts.Any() && id != 0)
                {
                    foreach (var khlhProduct in khlhProducts)
                    {
                        khlhProduct.IdKH = id;
                    }
                    _detailMenuCommentRepository.InsertKHLHProduct(khlhProducts);
                }

                #endregion

                _unitOfWork.Commit();
                return(RedirectToAction("DatHangThanhCong", new { barcode = model.Barcode }));
            }
        }
Exemple #22
0
        private void UnlockPromotionIfNecessary(double promotionProgress, double promotionThreshold, PromotionTriggerTypes triggerType, Guid accountId, PromotionDetail promotion)
        {
            // Check if promotion needs to be unlocked
            bool isPromotionUnlocked = false;

            if (triggerType == PromotionTriggerTypes.RideCount)
            {
                isPromotionUnlocked = promotionProgress != 0 &&
                                      promotionProgress >= promotionThreshold &&
                                      (promotionProgress % promotionThreshold) == 0;
            }
            else if (triggerType == PromotionTriggerTypes.AmountSpent)
            {
                isPromotionUnlocked = promotionProgress >= promotionThreshold;
            }

            if (isPromotionUnlocked)
            {
                _commandBus.Send(new AddUserToPromotionWhiteList
                {
                    AccountIds          = new[] { accountId },
                    PromoId             = promotion.Id,
                    LastTriggeredAmount = promotionProgress
                });
            }
        }
        //[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);
        }
Exemple #24
0
        private bool IsStarted(PromotionDetail promo, DateTime now)
        {
            var startDateTime = promo.GetStartDateTime().GetValueOrDefault(DateTime.MinValue);

            return(startDateTime <= now);
        }
Exemple #25
0
        /// <summary>
        ///
        /// </summary>
        ///
        /// <param name="model"></param>
        /// <returns>
        ///  <param name="details"></param>
        ///  <param name="message"></param>
        /// </returns>
        public async Task <(PromotionDetail details, string message)> UpgradeDownGrade(AdminPowers model)
        {
            //User user = new User();
            var userContext = _httpContextAccessor.HttpContext.User.Identity.Name;

            if (model == null)
            {
                return(null, $"{userContext}, Pass the right parameter");
            }
            var getTheUsers = await repository.LoadWhere(u => (u.Id == model.UserId || u.Username == model.Username) || u.Username == userContext);

            if (getTheUsers == null)
            {
                return(null, $"No user found.");
            }
            var user  = getTheUsers.FirstOrDefault(t => t.Username == model.Username);
            var admin = getTheUsers.FirstOrDefault(t => t.Username == userContext);

            if (admin.Role == UserRoles.Admin)
            {
                if (model.PromoteOrDemote)
                {
                    if (user.Role == UserRoles.Noob)
                    {
                        user.Role = UserRoles.Elite;

                        var msg = $"Role changed to {user.Role}";

                        user.ActionTaken = msg;
                        user.ModifiedAt  = DateTime.Now;
                        user.ModifiedBy  = admin.Username;
                        await repository.Update(user);

                        var detail = new PromotionDetail();
                        detail.IsRoleChanged = true;
                        detail.Message       = user.ActionTaken;
                        detail.UpdatedRole   = user.Role;


                        return(details : detail, message : msg);
                    }
                    if (user.Role == UserRoles.Elite)
                    {
                        var msge = $"Role unchanged because the user is already an {user.Role} user";

                        var detail = new PromotionDetail
                        {
                            IsRoleChanged = false,
                            Message       = msge,
                            UpdatedRole   = user.Role
                        };


                        return(details : detail, message : msge);
                    }
                }

                // Demote user.
                if (user.Role == UserRoles.Noob)
                {
                    var msg = $"Role unchanged because the user is already a {user.Role} user";

                    var detail = new PromotionDetail();
                    detail.IsRoleChanged = false;
                    detail.Message       = msg;
                    detail.UpdatedRole   = user.Role;


                    return(details : detail, message : msg);
                }
                if (user.Role == UserRoles.Elite)
                {
                    user.Role = UserRoles.Noob;

                    var msge = $"Role changed to {user.Role}";

                    user.ActionTaken = msge;
                    user.ModifiedAt  = DateTime.Now;
                    user.ModifiedBy  = admin.Username;
                    await repository.Update(user);

                    var detail = new PromotionDetail();
                    detail.IsRoleChanged = true;
                    detail.Message       = user.ActionTaken;
                    detail.UpdatedRole   = user.Role;

                    return(details : detail, message : msge);
                }
            }
            return(details : null, message : $"An Error Occured.");
        }
Exemple #26
0
    public void Read(TProtocol iprot)
    {
        iprot.IncrementRecursionDepth();
        try
        {
            TField field;
            iprot.ReadStructBegin();
            while (true)
            {
                field = iprot.ReadFieldBegin();
                if (field.Type == TType.Stop)
                {
                    break;
                }
                switch (field.ID)
                {
                case 1:
                    if (field.Type == TType.I32)
                    {
                        PromotionType = (PromotionType)iprot.ReadI32();
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                case 51:
                    if (field.Type == TType.Struct)
                    {
                        BuddyInfo = new PromotionBuddyInfo();
                        BuddyInfo.Read(iprot);
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                case 2:
                    if (field.Type == TType.Struct)
                    {
                        PromotionDetail = new PromotionDetail();
                        PromotionDetail.Read(iprot);
                    }
                    else
                    {
                        TProtocolUtil.Skip(iprot, field.Type);
                    }
                    break;

                default:
                    TProtocolUtil.Skip(iprot, field.Type);
                    break;
                }
                iprot.ReadFieldEnd();
            }
            iprot.ReadStructEnd();
        }
        finally
        {
            iprot.DecrementRecursionDepth();
        }
    }
Exemple #27
0
        public JsonResult Save(PromotionModel.PromotionSaveModel model)
        {
            Promotion promotion;
            IList <PromotionDetail> promotionDetails = JsonConvert.DeserializeObject <IList <PromotionDetail> >(model.Details);

            DateTime start = DateTimeHelper.ConvertToLongDay(model.StartDay);
            DateTime end   = DateTimeHelper.ConvertToLongDay(model.EndDay);

            if (model.id_ == 0)
            {
                promotion = new Promotion()
                {
                    Active             = model.Active,
                    Discount           = model.Discount,
                    EndDay             = end,
                    StartDay           = start,
                    IdUserOk           = 0,
                    ProductCategoryIds = model.ProductCategoryIds,
                    ProductIds         = model.ProductIds,
                    Region             = model.Region,
                    Title  = model.Title,
                    IdUser = 15
                };

                _promotionRepository.Add(promotion);
                _unitOfWork.Commit();
            }
            else
            {
                promotion                    = _promotionRepository.GetById(model.id_);
                promotion.Active             = model.Active;
                promotion.Discount           = model.Discount;
                promotion.EndDay             = end;
                promotion.StartDay           = start;
                promotion.ProductCategoryIds = model.ProductCategoryIds;
                promotion.ProductIds         = model.ProductIds;
                promotion.Region             = model.Region;
                promotion.Title              = model.Title;

                _promotionRepository.Update(promotion);
            }

            #region

            IList <PromotionDetail> oldDetails = model.id_ != 0
                                                    ? _promotionDetailRepository.GetMany(o => o.PromotionId == model.id_).ToList()
                                                    : new List <PromotionDetail>();

            foreach (var dt in promotionDetails)
            {
                if (dt.id_ == 0)
                {
                    PromotionDetail promotionDetail = new PromotionDetail()
                    {
                        Percent       = dt.Percent,
                        ProductId     = dt.ProductId,
                        PriceDiscount = dt.PriceDiscount,
                        PromotionId   = promotion.id_,
                        Price         = dt.Price
                    };
                    _promotionDetailRepository.Add(promotionDetail);
                }
                else
                {
                    PromotionDetail promotionDetail = oldDetails.FirstOrDefault(o => o.id_ == dt.id_);
                    if (promotionDetail != null)
                    {
                        promotionDetail.Percent       = dt.Percent;
                        promotionDetail.PriceDiscount = dt.PriceDiscount;
                        promotionDetail.Price         = dt.Price;
                        _promotionDetailRepository.Update(promotionDetail);
                    }
                }
            }
            #endregion

            _promotionRepository.ClearBannerCache();
            _unitOfWork.Commit();

            return(Json(new
            {
                PromotionId = promotion.id_
            }, JsonRequestBehavior.AllowGet));
        }
Exemple #28
0
 public void InsertPromotionDetail(PromotionDetail PromotionDetail)
 {
     Context.PromotionDetail.Add(PromotionDetail);
     Context.Entry(PromotionDetail).State = EntityState.Added;
     Context.SaveChanges();
 }