Inheritance: IOfferService
        protected void lbApplyTestPromoCode_Click(object sender, EventArgs e)
        {
            var profileId = QueryUserId;
            var promoCode = txtTestPromoCode.Text.Trim();

            UtilityService.SaveAttribute(profileId,
                                         "Profile",
                                         SystemCustomerAttributeNames.DiscountCouponCode,
                                         promoCode);

            int offerRuleId = QueryOfferRuleId;
            var country     = ShippingService.GetCountryById(ShippingSettings.PrimaryStoreCountryId);

            OfferService.ProcessCartOfferByProfileId(profileId, country.ISO3166Code, offerRuleId);

            LoadCart(profileId);

            hfCurrentPanel.Value = "test";

            enbTempCart.Message = "Promo code was applied successfully.";
        }
Beispiel #2
0
            public void ProductIdDoesNotExist_ReturnsNegativeOne()
            {
                // Arrange...
                Offer offer = null;

                dbMock.Setup(m => m.Offer.Add(It.IsAny <Offer>())).Callback((Offer o) => { offer = o; });
                dbMock.Setup(m => m.SaveChanges()).Returns(0);
                var productId = 123;

                productServiceMock.Setup(p => p.Exists(It.Is <int>(i => i == productId))).Returns(false);
                var offerService = new OfferService(dbMock.Object, loggerMock.Object, productServiceMock.Object);

                // Act...
                var result = offerService.CreateOffer(new OfferDTO()
                {
                    ProductId = productId
                });

                // Assert...
                Assert.AreEqual(-1, result);
            }
Beispiel #3
0
 protected void lbDeleteSelected_Click(object sender, EventArgs e)
 {
     if ((_selectionFilter != null) && (_selectionFilter.Values != null))
     {
         if (!_inverseSelection)
         {
             foreach (var id in _selectionFilter.Values)
             {
                 OfferService.DeleteOfferList(Convert.ToInt32(id));
             }
         }
         else
         {
             var itemsIds = _paging.ItemsIds <int>("OfferListID as ID");
             foreach (int id in itemsIds.Where(id => !_selectionFilter.Values.Contains(id.ToString())))
             {
                 OfferService.DeleteOfferList(id);
             }
         }
     }
 }
        public async Task ShouldThrowsArgumentException_WhenInvalidOfferIdIsPassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            int invalidOfferID = 100;

            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var sut = new OfferService(context, dateTimeNowProvider.Object);

                //Act
                //Assert
                await Assert.ThrowsExceptionAsync <ArgumentException>(() => sut.GetAllProductsInOfferAsync(invalidOfferID));
            }
        }
Beispiel #5
0
            public void ProductIdExists_Created()
            {
                // Arrange...
                Offer offer = null;

                dbMock.Setup(m => m.Offer.Add(It.IsAny <Offer>())).Callback((Offer o) => { offer = o; });
                dbMock.Setup(m => m.SaveChanges()).Returns(0);
                var productId = 123;

                productServiceMock.Setup(p => p.Exists(It.Is <int>(i => i == productId))).Returns(true);
                var offerService = new OfferService(dbMock.Object, loggerMock.Object, productServiceMock.Object);

                // Act...
                var result = offerService.CreateOffer(new OfferDTO()
                {
                    ProductId = productId
                });

                // Assert...
                Assert.That(offer.ProductId, Is.EqualTo(productId));
            }
Beispiel #6
0
        public static void SendFailureMessage(int orderByRequestId)
        {
            var orderByRequest = GetOrderByRequest(orderByRequestId);
            var offer          = OfferService.GetOffer(orderByRequest.OfferId);

            IList <EvaluatedCustomOptions> listOptions = null;
            var selectedOptions = orderByRequest.Options.IsNotEmpty() && orderByRequest.Options != "null"
                                                    ? HttpUtility.UrlDecode(orderByRequest.Options)
                                                    : null;

            if (selectedOptions.IsNotEmpty())
            {
                try
                {
                    listOptions = CustomOptionsService.DeserializeFromXml(selectedOptions);
                }
                catch (Exception)
                {
                    listOptions = null;
                }
            }

            string optionsRender = OrderService.RenderSelectedOptions(listOptions);


            var failureByRequestMail = new FailureByRequestMailTemplate(orderByRequest.OrderByRequestId.ToString(),
                                                                        orderByRequest.ArtNo, orderByRequest.ProductName + " " + optionsRender,
                                                                        orderByRequest.Quantity.ToString(),
                                                                        orderByRequest.UserName,
                                                                        offer != null && offer.Color != null
                                                                            ? offer.Color.ColorName
                                                                            : "",
                                                                        offer != null && offer.Size != null
                                                                            ? offer.Size.SizeName
                                                                            : "");

            failureByRequestMail.BuildMail();
            SendMail.SendMailNow(orderByRequest.Email, failureByRequestMail.Subject, failureByRequestMail.Body, true);
        }
        public async Task CreateThrowsArgumentExceptionWithProperMessage_WhenInvalidProductQuantityIsPassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            int    validOfferID;
            var    validProductId1 = 1;
            string validProductName;

            using (var getContext = new StoreSystemDbContext(options))
            {
                validOfferID     = getContext.Offers.Include(x => x.ProductsInOffer).First(x => x.ProductsInOffer.Count == 0).OfferID;
                validProductName = getContext.Products.Find(validProductId1).Name;
            }

            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var validDate           = new DateTime(2019, 4, 1);
                var sut = new OfferService(context, dateTimeNowProvider.Object);
                ProductIdQuantityDto[] products = new[]
                {
                    new ProductIdQuantityDto(validProductId1, 100),
                };
                var errorText = string.Format(
                    Consts.QuantityNotEnough,
                    validProductName,
                    validProductId1);
                //Act
                //Assert
                Assert.AreEqual(
                    errorText,
                    (await Assert.ThrowsExceptionAsync <ArgumentException>(() => sut.AddProductsByIdToOfferAsync(validOfferID, products))).Message);
            }
        }
        public async Task Test_EditOffer_ShouldUpdateOffer()
        {
            var context = await GetContext();

            var offerRepo    = new DbRepository <Offer>(context);
            var offerService = new OfferService(offerRepo);

            var editDto = new EditOfferDTO
            {
                Id    = 72,
                Title = "Edited offer"
            };
            int id = await offerService.EditOffer(editDto);


            var offers           = context.Offers.ToArray();
            var editedOfferTitle = offerService.GetTitleById(id);

            Assert.Equal("Edited offer", context.Offers
                         .SingleOrDefault(p => p.Id == id)
                         .Title);
        }
        public async Task AddProductsToOffer_WhenValidParametersArePassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            int validOfferID;

            var validProductId1 = 1;
            var validProductId2 = 2;

            using (var getContext = new StoreSystemDbContext(options))
            {
                validOfferID = getContext.Offers.Include(x => x.ProductsInOffer).First(x => x.ProductsInOffer.Count == 0).OfferID;
            }

            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var validDate           = new DateTime(2019, 4, 1);
                var sut = new OfferService(context, dateTimeNowProvider.Object);
                ProductIdQuantityDto[] products = new[]
                {
                    new ProductIdQuantityDto(validProductId1, 1),
                    new ProductIdQuantityDto(validProductId2, 1),
                };

                //Act
                var isExecuted = await sut.AddProductsByIdToOfferAsync(validOfferID, products);

                //Assert
                Assert.IsTrue(isExecuted);
                Assert.AreEqual(2, context.Offers.Include(x => x.ProductsInOffer).First(x => x.OfferID == validOfferID).ProductsInOffer.Count);
            }
        }
Beispiel #10
0
        public ActionResult Edit(OfferViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var company      = UserCompany;
            var offer        = new Offer();
            var offerService = new OfferService();

            offer.Title       = model.Title;
            offer.Description = model.Description;
            offer.Url         = model.Url;
            offer.Category    = model.Category;
            offer.CompanyId   = company.Id;
            offer.Id          = model.Id;

            offerService.SaveOffer(offer);

            model.SuccessMessage = "Success - Offer saved.";
            return(RedirectToAction("Index"));
        }
        protected string GetOfferName(int offerRuleId)
        {
            if (offerRuleId == 0)
            {
                return(string.Empty);
            }

            var offer = OfferService.GetOfferRuleOnlyById(offerRuleId);

            if (offer == null)
            {
                return(string.Empty);
            }

            if (offer.IsCart)
            {
                return(string.Format("<a href='/marketing/promo_cart_offer_info.aspx?offerruleid={1}' target='_blank'>Offer '{0}' (ID: {1})</a>", offer.Name, offer.Id));
            }
            else
            {
                return(string.Format("<a href='/marketing/promo_catalog_offer_info.aspx?offerruleid={1}' target='_blank'>Offer '{0}' (ID: {1})</a>", offer.Name, offer.Id));
            }
        }
Beispiel #12
0
            public void DateModifiedNull_Created()
            {
                // Arrange...
                Offer offer = null;

                dbMock.Setup(m => m.Offer.Add(It.IsAny <Offer>()))
                .Callback((Offer o) =>
                {
                    offer         = o;
                    offer.OfferId = 123;
                });
                dbMock.Setup(m => m.SaveChanges()).Returns(1);
                var offerService = new OfferService(dbMock.Object, loggerMock.Object, productServiceMock.Object);

                // Act...
                var result = offerService.CreateOffer(new OfferDTO()
                {
                    Price = 1.99M
                });

                // Assert...
                Assert.That(result, Is.GreaterThan(0));
            }
Beispiel #13
0
        public void WhenCollectionOfOffersProvided_ServiceShouldReturnOfferHasLowestAmount()
        {
            //Arrange
            var offerDtos = new List <IOfferDto>()
            {
                offer1, offer2, offer3
            };
            var httpClientFactoryMock = Substitute.For <IHttpClientFactory>();

            var fakeHttpClient = new HttpClient();

            httpClientFactoryMock.CreateClient().Returns(fakeHttpClient);

            //Act
            var service = new OfferService(httpClientFactoryMock);
            var result  = service.GetOfferWithLowestAmount(offerDtos).Result;

            //Assert
            result
            .Should()
            .BeOfType <OfferDto>()
            .Which.OfferAmount.Equals(30.12);
        }
        public async Task ThrowsArgumentException_WhenInvalidOfferIdIsPassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            int invalidOfferId = 100;
            var client         = 1;
            var address        = 1;
            var city           = 1;
            var country        = 1;
            var deadline       = new DateTime(2019, 5, 10);
            var deliveryDate   = new DateTime(2019, 5, 8);
            var discount       = 0.10m;
            var offerDate      = new DateTime(2019, 5, 1);


            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var sut       = new OfferService(context, dateTimeNowProvider.Object);
                var errorText = string.Format(
                    Consts.ObjectIDNotExist,
                    nameof(Offer),
                    invalidOfferId);
                //Act
                //Assert
                Assert.AreEqual(
                    errorText,
                    (await Assert.ThrowsExceptionAsync <ArgumentException>(() =>
                                                                           sut.UpdateOfferAsync(invalidOfferId, client, discount, offerDate, (deadline - offerDate).TotalDays, deliveryDate, address, city, country))).Message
                    );
            }
        }
Beispiel #15
0
        public async Task <ActionResult> ConfirmEmail(string userId, string offerToken, string code)
        {
            if (userId == null || offerToken == null)
            {
                return(View("Error"));
            }
            OfferService offerService      = new OfferService();
            var          model             = new DealRegisterViewModel();
            var          offer             = offerService.GetOfferByToken(offerToken);
            var          existingOfferCode = CodeForUser(offer.Id, userId);

            if (existingOfferCode == null)//if user does not have code yet, claim next
            {
                var offerCode = offerService.ClaimNextCode(offer.Id, userId);
                model.OfferCode   = offerCode;
                model.Title       = offer.Title;
                model.Description = offer.Description;
                model.Url         = offer.Url;
            }
            else//otherwise use the code that user already has
            {
                model.OfferCode   = existingOfferCode;
                model.Title       = offer.Title;
                model.Description = offer.Description;
                model.Url         = offer.Url;
            }
            var result = await UserManager.ConfirmEmailAsync(userId, code);

            if (result.Succeeded)
            {
                return(View("ConfirmEmail", model));
            }
            else
            {
                return(View("Error"));
            }
        }
        public void CheckIfAddElectricScooterAddsTheScooter()
        {
            var dbContext = new AutomobileDbContext();
            var service   = new OfferService(dbContext);

            IFormFile file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.txt");

            service.AddElectricScooter(new AddElectricScooterViewModel()
            {
                Title              = "Test",
                Make               = "Xiaomi",
                Model              = "365",
                Year               = 2003,
                Price              = 220,
                Condition          = (Condition)Enum.Parse(typeof(Condition), "New"),
                WaterproofLevel    = "test",
                MaxSpeedAchievable = 25,
                MotorPower         = 250,
                ScooterSize        = "2413",
                TiresSize          = 8.5m,
                TravellingDistance = 205,
                Battery            = "test",
                Kilometers         = 15000,
                Description        = "asasrsa",
                ContactNumber      = "03210320232",
                MainImageFile      = file
            }, "e4bf2992-cc46-4ebb-baf2-667f245a3582");

            var scooterOffersContainScooter = dbContext.ElectricScooterOffers.Any(x => x.Title == "Test");

            Assert.True(scooterOffersContainScooter);

            var mockScooter = dbContext.ElectricScooterOffers.FirstOrDefault(x => x.Title == "Test");

            dbContext.ElectricScooterOffers.Remove(mockScooter);
            dbContext.SaveChanges();
        }
Beispiel #17
0
        public async Task ShouldReturnTotalSumOfFiltredOffers_WhenValidOfferIdIsPassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            var     validOfferId  = 1;
            decimal expectedTotal = (decimal)((1 * 1 + 1 * 2) * (1 - 0.1 / 100));

            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var sut = new OfferService(context, dateTimeNowProvider.Object);

                //Act
                var actualTotal = await sut.GetOfferQuantityAsync(offerID : validOfferId);

                //Assert
                Assert.AreEqual(expectedTotal, actualTotal);
            }
        }
Beispiel #18
0
        public async Task FindProperOffer_WhenValidOfferIdIsPassed()
        {
            //Arrange
            var databaseName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            var options = DbSeed.GetOptions(databaseName);

            DbSeed.SeedDatabase(options);

            var validOfferID = 1;

            using (var context = new StoreSystemDbContext(options))
            {
                var dateTimeNowProvider = new Mock <IDateTimeNowProvider>();
                var validDate           = new DateTime(2019, 4, 1);
                var sut = new OfferService(context, dateTimeNowProvider.Object);

                //Act
                var actualOffer = await sut.GetOfferByIDAsync(validOfferID);

                //Assert
                Assert.AreEqual(validOfferID, actualOffer.OfferID);
            }
        }
        public void CheckIfAddCarAddsTheCar()
        {
            var dbContext = new AutomobileDbContext();
            var service   = new OfferService(dbContext);

            IFormFile file = new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("This is a dummy file")), 0, 0, "Data", "dummy.txt");

            service.AddCar(new AddCarViewModel()
            {
                Title             = "Test",
                Make              = "Audi",
                Model             = "A3",
                Year              = 2003,
                Price             = 220,
                Condition         = (Condition)Enum.Parse(typeof(Condition), "New"),
                Color             = "black",
                SteeringWheelSide = 0,
                FuelType          = (FuelType)Enum.Parse(typeof(FuelType), "Diesel"),
                HorsePower        = 150,
                EngineSize        = 1060,
                Gearbox           = (Gearbox)Enum.Parse(typeof(Gearbox), "Automatic"),
                Doors             = "2",
                Kilometers        = 15000,
                ContactNumber     = "03210320232",
                MainImageFile     = file
            }, "e4bf2992-cc46-4ebb-baf2-667f245a3582");

            var carOffersContainCar = dbContext.CarOffers.Any(x => x.Title == "Test");

            Assert.True(carOffersContainCar);

            var mockCar = dbContext.CarOffers.FirstOrDefault(x => x.Title == "Test");

            dbContext.CarOffers.Remove(mockCar);
            dbContext.SaveChanges();
        }
        protected override void OnInit(EventArgs e)
        {
            ddlAction.DataSource     = OfferService.GetOfferActionAttributes(isCatalog: true, isCart: null);
            ddlAction.DataTextField  = "Name";
            ddlAction.DataValueField = "Id";
            ddlAction.DataBind();

            ddlOptionOperator.DataSource     = OfferService.GetOfferOperatorsByAttribute((int)OfferAttributeType.OPTION);
            ddlOptionOperator.DataTextField  = "Operator";
            ddlOptionOperator.DataValueField = "Id";
            ddlOptionOperator.DataBind();

            var types = OfferService.GetOfferTypes().ToList();

            types.Insert(0, new OfferType {
                Type = AppConstant.DEFAULT_SELECT
            });
            ddlOfferTypes.DataTextField  = "Type";
            ddlOfferTypes.DataValueField = "Id";
            ddlOfferTypes.DataSource     = types;
            ddlOfferTypes.DataBind();

            base.OnInit(e);
        }
Beispiel #21
0
        public void GetOffersForOrder_ForwardsRequestToUnderlyingRepository()
        {
            // GIVEN
            Mock <IOfferRepository> repo = new Mock <IOfferRepository>();

            repo.Setup(x => x.GetOffersForOrder(It.IsAny <int>())).Returns((int id) => Observable.Return(new List <Offer> {
                new Offer(new OfferEntity {
                    Id = id
                })
            }));
            IOfferService service = new OfferService(repo.Object);

            // WHEN
            List <Offer> offers = null;

            service.GetOffersForOrder(42)
            .Subscribe(x => offers = x.ToList());

            // THEN
            Assert.IsNotNull(offers);
            Assert.AreEqual(1, offers.Count);
            Assert.AreEqual(42, offers[0].Id);
            repo.Verify(x => x.GetOffersForOrder(42), Times.Once());
        }
Beispiel #22
0
 public IndexModel(OfferService offerService)
 {
     _offerService = offerService;
 }
Beispiel #23
0
 public OffersController(PeopleService peopleService, ProductService productService, OfferService offerService)
 {
     _peopleService  = peopleService;
     _productService = productService;
     _offerService   = offerService;
 }
Beispiel #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ProductId == 0)
            {
                Error404();
                return;
            }

            //if not have category
            if (ProductService.GetCountOfCategoriesByProductId(ProductId) == 0)
            {
                Error404();
                return;
            }

            // --- Check product exist ------------------------
            CurrentProduct = ProductService.GetProduct(ProductId);

            if (CurrentProduct == null || CurrentProduct.Enabled == false || CurrentProduct.CategoryEnabled == false)
            {
                Error404();
                return;
            }

            btnAdd.Text            = SettingsCatalog.BuyButtonText;
            btnOrderByRequest.Text = SettingsCatalog.PreOrderButtonText;

            if (CurrentProduct.TotalAmount <= 0 || CurrentProduct.MainPrice == 0)
            {
                divAmount.Visible = false;
            }


            //CompareControl.ProductId = ProductId;

            CurrentOffer = OfferService.GetMainOffer(CurrentProduct.Offers, CurrentProduct.AllowPreOrder, Request["color"].TryParseInt(true), Request["size"].TryParseInt(true));

            if (CurrentOffer != null)
            {
                BuyInOneClick.OfferID = CurrentOffer.OfferId;

                sizeColorPicker.SelectedOfferId = CurrentOffer.OfferId;

                //CompareControl.Visible = divCompare.Visible = SettingsCatalog.EnableCompareProducts;
                //CompareControl.OfferId = CurrentOffer.OfferId;
                //CompareControl.IsSelected =
                //    ShoppingCartService.CurrentCompare.Any(p => p.Offer.OfferId == CurrentOffer.OfferId);

                //WishlistControl.OfferId = CurrentOffer.OfferId;
                //divWishlist.Visible = SettingsDesign.WishListVisibility;
            }
            else
            {
                //CompareControl.Visible = divCompare.Visible = false;
                //divWishlist.Visible = false;
                pnlPrice.Visible = false;
            }

            BuyInOneClick.ProductId       = CurrentProduct.ProductId;
            BuyInOneClick.SelectedOptions = productCustomOptions.SelectedOptions;
            BuyInOneClick.CustomOptions   = productCustomOptions.CustomOptions;

            sizeColorPicker.ProductId = ProductId;

            divUnit.Visible = (CustomerContext.CurrentCustomer.IsAdmin || AdvantShop.Trial.TrialService.IsTrialEnabled) && SettingsMain.EnableInplace ? true : CurrentProduct.Unit.IsNotEmpty();

            rating.ProductId  = CurrentProduct.ID;
            rating.Rating     = CurrentProduct.Ratio;
            rating.ShowRating = SettingsCatalog.EnableProductRating;
            rating.ReadOnly   = RatingService.DoesUserVote(ProductId, CustomerContext.CustomerId);

            pnlSize.Visible   = !string.IsNullOrEmpty(CurrentProduct.Size) && (CurrentProduct.Size != "0|0|0") && SettingsCatalog.DisplayDimensions;
            pnlWeight.Visible = CurrentProduct.Weight != 0 && SettingsCatalog.DisplayWeight;

            CurrentBrand     = CurrentProduct.Brand;
            pnlBrand.Visible = CurrentBrand != null && CurrentBrand.Enabled;
            //pnlBrnadLogo.Visible = CurrentBrand != null && CurrentBrand.Enabled && CurrentBrand.BrandLogo != null;

            productPropertiesView.ProductId      = ProductId;
            productBriefPropertiesView.ProductId = ProductId;

            productPhotoView.Product = CurrentProduct;

            ProductVideoView.ProductID = ProductId;
            relatedProducts.ProductIds.Add(ProductId);
            alternativeProducts.ProductIds.Add(ProductId);
            breadCrumbs.Items =
                CategoryService.GetParentCategories(CurrentProduct.CategoryId).Reverse().Select(cat => new BreadCrumbs
            {
                Name = cat.Name,
                Url  = UrlService.GetLink(ParamType.Category, cat.UrlPath, cat.ID)
            }).ToList();
            breadCrumbs.Items.Insert(0, new BreadCrumbs
            {
                Name = Resource.Client_MasterPage_MainPage,
                Url  = UrlService.GetAbsoluteLink("/")
            });

            breadCrumbs.Items.Add(new BreadCrumbs {
                Name = CurrentProduct.Name, Url = null
            });

            RecentlyViewService.SetRecentlyView(CustomerContext.CustomerId, ProductId);

            productReviews.EntityType = EntityType.Product;
            productReviews.EntityId   = ProductId;

            int reviewsCount = SettingsCatalog.ModerateReviews
                                   ? ReviewService.GetCheckedReviewsCount(ProductId, EntityType.Product)
                                   : ReviewService.GetReviewsCount(ProductId, EntityType.Product);

            if (reviewsCount > 0)
            {
                lReviewsCount.Text = string.Format("({0})", reviewsCount);
            }

            //Добавим новые meta
            MetaInfo newMetaInfo = new MetaInfo();

            newMetaInfo                 = CurrentProduct.Meta;
            newMetaInfo.Title           = CurrentProduct.Name + " купить в интернет-магазине Корпорация Игрушек";
            newMetaInfo.MetaDescription = "Интернет-магазин Корпорация Игрушек представляет: " + CurrentProduct.Name + " и еще более 5,5 тысяч видов товаров по оптовым ценам. Порадуйте своего ребенка!";
            newMetaInfo.MetaKeywords    = CurrentProduct.Name;

            metaInfo = SetMeta(newMetaInfo, CurrentProduct.Name);

            //metaInfo = SetMeta(CurrentProduct.Meta, CurrentProduct.Name,
            //    CategoryService.GetCategory(CurrentProduct.CategoryId).Name,
            //    CurrentProduct.Brand != null ? CurrentProduct.Brand.Name : string.Empty,
            //    CatalogService.GetStringPrice(CurrentProduct.MainPrice -
            //                                  CurrentProduct.MainPrice * CurrentProduct.Discount / 100));

            if (SettingsSEO.ProductAdditionalDescription.IsNotEmpty())
            {
                liAdditionalDescription.Text =
                    GlobalStringVariableService.TranslateExpression(
                        SettingsSEO.ProductAdditionalDescription, MetaType.Product, CurrentProduct.Name,
                        CategoryService.GetCategory(CurrentProduct.CategoryId).Name,
                        CurrentProduct.Brand != null ? CurrentProduct.Brand.Name : string.Empty,
                        CatalogService.GetStringPrice(CurrentProduct.MainPrice -
                                                      CurrentProduct.MainPrice * CurrentProduct.Discount / 100));
            }

            LoadModules();

            if (GoogleTagManager.Enabled)
            {
                var tagManager = ((AdvantShopMasterPage)Master).TagManager;
                tagManager.PageType       = GoogleTagManager.ePageType.product;
                tagManager.ProdId         = CurrentOffer != null ? CurrentOffer.ArtNo : CurrentProduct.ArtNo;
                tagManager.ProdName       = CurrentProduct.Name;
                tagManager.ProdValue      = CurrentOffer != null ? CurrentOffer.Price : 0;
                tagManager.CatCurrentId   = CurrentProduct.MainCategory.ID;
                tagManager.CatCurrentName = CurrentProduct.MainCategory.Name;
            }
        }
Beispiel #25
0
        public async Task <ActionResult> ConfirmEmailJson(string userId, string offerToken, string code)
        {
            var confirmEmailResult = new DealConfirmEmailResult();

            if (userId == null || offerToken == null)
            {
                var errors = Json(confirmEmailResult);
                if (userId == null)
                {
                    confirmEmailResult.IsSuccessful = false;
                    confirmEmailResult.ErrorMessages.Add("userId invalid");
                    errors = Json(confirmEmailResult);
                }
                if (offerToken == null)
                {
                    confirmEmailResult.IsSuccessful = false;
                    confirmEmailResult.ErrorMessages.Add("offerToken invalid");
                    errors = Json(confirmEmailResult);
                }
                errors.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return(errors);
            }
            OfferService offerService = new OfferService();
            var          model        = new DealRegisterViewModel();
            var          offer        = offerService.GetOfferByToken(offerToken);
            //TODO: If offer is null we need to return unsuccessful Message: "Offer not found"
            var existingOfferCode = CodeForUser(offer.Id, userId);

            if (existingOfferCode == null)//if user does not have code yet, claim next
            {
                var offerCode = offerService.ClaimNextCode(offer.Id, userId);
                model.OfferCode   = offerCode;
                model.Title       = offer.Title;
                model.Description = offer.Description;
                model.Url         = offer.Url;
            }
            else//otherwise use the code that user already has
            {
                model.OfferCode   = existingOfferCode;
                model.Title       = offer.Title;
                model.Description = offer.Description;
                model.Url         = offer.Url;
            }
            //TODO: Handle if userId is bad.
            try
            {
                var result = await UserManager.ConfirmEmailAsync(userId, code);

                if (result.Succeeded)
                {
                    confirmEmailResult.IsSuccessful = true;
                    confirmEmailResult.Code         = model.OfferCode;
                    confirmEmailResult.Description  = model.Description;
                    confirmEmailResult.Url          = model.Url;
                    var success = Json(confirmEmailResult);
                    success.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return(success);
                }
                else
                {
                    confirmEmailResult.IsSuccessful = false;
                    confirmEmailResult.Code         = null;
                    //TODO: change error message assignment to foreach
                    confirmEmailResult.ErrorMessages[0] = "Unhandled error occurred.";
                    var errors = Json(confirmEmailResult);
                    errors.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return(errors);
                }
            }
            catch (System.InvalidOperationException ex)
            {
                confirmEmailResult.IsSuccessful = false;
                confirmEmailResult.ErrorMessages.Add(ex.Message);
                var errors = Json(confirmEmailResult);
                errors.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return(errors);
            }
            catch (Exception ex)
            {
                confirmEmailResult.IsSuccessful = false;
                confirmEmailResult.ErrorMessages.Add("Unknown Error");
                var errors = Json(confirmEmailResult);
                errors.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return(errors);
            }
        }
Beispiel #26
0
        public async Task <ActionResult> RegisterJson(DealRegisterViewModel model)
        {
            var registerResult = new DealRegisterResult();

            if (ModelState.IsValid)
            {
                //password = kf6Ua?a<2DhfZ<,t
                var offerService = new OfferService();
                var user         = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

                var result = await UserManager.CreateAsync(user, "kf6Ua?a<2DhfZ<,t");

                if (result.Succeeded)
                {
                    //Line below commented out to prevent log in until the user is confirmed.
                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link

                    //Create company with user ID


                    //Add user role of buyer
                    await UserManager.AddToRoleAsync(user.Id, "Buyer");


                    string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account", model.OfferToken);

                    registerResult.IsSuccessful   = true;
                    registerResult.SuccessMessage = "Please check your email to receive your code.";

#if DEBUG
                    registerResult.SuccessMessage += callbackUrl;
#endif
                    // Uncomment to debug locally
                    // TempData["ViewBagLink"] = callbackUrl;

                    var jsonResult = Json(registerResult);
                    jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return(jsonResult);
                    //return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result, registerResult);
                    registerResult.IsSuccessful = false;
                    var jsonResult = Json(registerResult);
                    jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

                    return(jsonResult);
                }
            }
            foreach (var value in ModelState.Values)
            {
                foreach (var error in value.Errors)
                {
                    registerResult.ErrorMessages.Add(error.ErrorMessage);
                }
            }
            var errorResult = Json(registerResult);
            errorResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return(errorResult);
        }
Beispiel #27
0
        protected void lbSave_Click(object sender, EventArgs e)
        {
            string urlKey = txtUrlKey.Text.Trim();

            // If urlKey is empty, regenerate with given name
            if (urlKey == string.Empty)
            {
                urlKey         = AdminStoreUtility.GetFriendlyUrlKey(txtRuleAlias.Text.Trim());
                txtUrlKey.Text = urlKey;
            }

            // Make sure urlKey is unique
            if (((OfferService.GetOfferRuleByUrlKey(urlKey) != null) && (OfferService.GetOfferRuleByUrlKey(urlKey).Id != QueryOfferRuleId)))
            {
                enbNotice.Message = "Offer was failed to create. URL key is not unique.";
            }
            else
            {
                string htmlMsg;

                if (ftbDesc.Visible)
                {
                    htmlMsg = AdminStoreUtility.CleanFtbOutput(ftbDesc.Text);
                }
                else
                {
                    htmlMsg = txtDescription.Text.Trim();
                }

                var rule = new OfferRule
                {
                    Name                 = txtRuleName.Text.Trim(),
                    ProceedForNext       = Convert.ToBoolean(rblProceed.SelectedValue),
                    IsActive             = Convert.ToBoolean(rblStatus.SelectedValue),
                    IsCart               = true,
                    PromoCode            = txtPromoCode.Text.Trim(),
                    UsesPerCustomer      = Convert.ToInt32(txtUsesPerCust.Text.Trim()),
                    Priority             = Convert.ToInt32(txtPriority.Text.Trim()),
                    HtmlMessage          = htmlMsg,
                    OfferedItemIncluded  = cbOfferedItemIncluded.Checked,
                    Alias                = txtRuleAlias.Text.Trim(),
                    ShowOfferTag         = false,
                    ShowRRP              = false,
                    ShortDescription     = string.Empty,
                    LongDescription      = string.Empty,
                    SmallImage           = string.Empty,
                    LargeImage           = string.Empty,
                    UrlRewrite           = urlKey,
                    ShowInOfferPage      = false,
                    OfferUrl             = string.Empty,
                    PointSpendable       = chkPointSpendable.Checked,
                    UseInitialPrice      = cbUseInitialPrice.Checked,
                    NewCustomerOnly      = cbNewCustomerOnly.Checked,
                    ShowCountDown        = cbShowCountDownTimer.Checked,
                    DisplayOnProductPage = cbDisplayOnProductPage.Checked,
                    OfferTypeId          = Convert.ToInt32(ddlOfferTypes.SelectedValue)
                };

                if (ddlRelatedTypes.SelectedValue != string.Empty)
                {
                    switch (ddlRelatedTypes.SelectedValue)
                    {
                    case "products":
                        rule.RelatedProducts = txtRelatedItems.Text.ToString();
                        break;

                    case "brands":
                        rule.RelatedBrands = txtRelatedItems.Text.ToString();
                        break;

                    case "category":
                        rule.RelatedCategory = txtRelatedItems.Text.ToString();
                        break;
                    }
                }

                if (!string.IsNullOrEmpty(txtDateFrom.Text.Trim()))
                {
                    rule.StartDate = DateTime.ParseExact(txtDateFrom.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture);
                }

                if (!string.IsNullOrEmpty(txtDateTo.Text.Trim()))
                {
                    rule.EndDate = DateTime.ParseExact(txtDateTo.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture);
                }

                object freeProductItself  = DBNull.Value;
                object freeProductId      = DBNull.Value;
                object freeProductPriceId = DBNull.Value;
                object freeProductQty     = DBNull.Value;

                // Determine if there is any free item settings
                if (rbFreeItself.Checked || rbFreeItem.Checked)
                {
                    freeProductItself = rbFreeItself.Checked;

                    if (rbFreeItem.Checked)
                    {
                        freeProductId      = txtFreeProductId.Text.Trim();
                        freeProductPriceId = txtFreeProductPriceId.Text.Trim();
                        freeProductQty     = txtFreeQuantity.Text.Trim();
                    }
                }

                object discountQtyStep = DBNull.Value;
                object minimumAmount   = DBNull.Value;
                object discountAmount  = DBNull.Value;
                int    rewardPoint     = 0;

                if (txtDiscountQtyStep.Text.Trim() != string.Empty)
                {
                    discountQtyStep = txtDiscountQtyStep.Text.Trim();
                }

                if (txtMinimumAmount.Text.Trim() != string.Empty)
                {
                    minimumAmount = txtMinimumAmount.Text.Trim();
                }

                if (txtDiscountAmount.Text.Trim() != string.Empty)
                {
                    discountAmount = txtDiscountAmount.Text.Trim();
                }

                if (txtRewardPoint.Text.Trim() != string.Empty)
                {
                    rewardPoint = Convert.ToInt32(txtRewardPoint.Text.Trim());
                }

                // Retrieve option target if any
                object optionOperatorId = DBNull.Value;
                object optionOperator   = DBNull.Value;
                object optionOperand    = DBNull.Value;

                if (txtOption.Text.Trim() != string.Empty)
                {
                    optionOperand    = txtOption.Text.Trim();
                    optionOperatorId = ddlOptionOperator.SelectedValue;
                    optionOperator   = OfferService.GetOfferOperator(Convert.ToInt32(optionOperatorId)).Operator;
                }

                // Assign action to this rule object's action
                var newAction = new OfferAction();

                if (discountAmount != DBNull.Value)
                {
                    newAction.DiscountAmount = Convert.ToDecimal(discountAmount);
                }
                if (freeProductItself != DBNull.Value)
                {
                    newAction.FreeProductItself = Convert.ToBoolean(freeProductItself);
                }
                if (freeProductId != DBNull.Value)
                {
                    newAction.FreeProductId = Convert.ToInt32(freeProductId);
                }
                if (freeProductPriceId != DBNull.Value)
                {
                    newAction.FreeProductPriceId = Convert.ToInt32(freeProductPriceId);
                }
                if (freeProductQty != DBNull.Value)
                {
                    newAction.FreeProductQty = Convert.ToInt32(freeProductQty);
                }
                newAction.OfferActionAttributeId = Convert.ToInt32(ddlAction.SelectedValue);
                newAction.Name   = ddlAction.SelectedItem.Text;
                newAction.IsCart = true;
                if (discountQtyStep != DBNull.Value)
                {
                    newAction.DiscountQtyStep = Convert.ToInt32(discountQtyStep);
                }
                if (minimumAmount != DBNull.Value)
                {
                    newAction.MinimumAmount = Convert.ToDecimal(minimumAmount);
                }
                newAction.RewardPoint = rewardPoint;
                if (optionOperatorId != DBNull.Value)
                {
                    newAction.OptionOperatorId = Convert.ToInt32(optionOperatorId);
                }
                if (optionOperand != DBNull.Value)
                {
                    newAction.OptionOperand = Convert.ToString(optionOperand);
                }

                if ((optionOperator != DBNull.Value) && (optionOperatorId != DBNull.Value))
                {
                    newAction.OptionOperator = new OfferOperator
                    {
                        Id       = Convert.ToInt32(optionOperatorId),
                        Operator = Convert.ToString(optionOperator)
                    }
                }
                ;

                newAction.XValue = Convert.ToInt32(txtXValue.Text.Trim());
                newAction.YValue = Convert.ToDecimal(txtYValue.Text.Trim());

                rule.Action = newAction;

                var proceed = true;

                // Assign root condition to this rule object's condition
                rule.Condition = OfferUtility.OfferRuleConditions[QueryTempOfferRuleId];

                if (rule.Condition == null)
                {
                    enbNotice.Message = "Offer was failed to create. There is no condition setup for this offer. It could be due to session lost. Please try to create again.";
                    proceed           = false;
                }

                // Assign root condition to this action object's condition
                rule.Action.Condition = OfferUtility.OfferActionConditions[QueryTempOfferRuleId];

                if (rule.Action.Condition == null)
                {
                    enbNotice.Message = "Offer was failed to create. There is no <u>action</u> condition setup for this offer. It could be due to session lost. Please try to create again.";
                    proceed           = false;
                }

                if (proceed)
                {
                    // Save into database
                    var id = OfferService.ProcessOfferInsertion(rule);

                    ResetCartOfferSessions();

                    // Redirect to info page
                    Response.Redirect("/marketing/promo_cart_offer_info.aspx?offerruleid=" + id + "&" + QueryKey.MSG_TYPE + "=" + (int)MessageType.OfferCreated);
                }
            }
        }
Beispiel #28
0
        public OfferTransactionServiceTest()
        {
            var fakedItemDescriptionRepoService = A.Fake <IItemDescriptionRepoService>();
            var fakedTransactionFactory         = A.Fake <ITransactionFactory>();
            var fakedRepoServiceFactory         = A.Fake <IRepoServiceFactory>();

            _fakedItemInOfferTransactionRepoService = A.Fake <IItemInOfferTransactionRepoService>();
            _fakedOfferTranascrionRepoService       = A.Fake <IOfferTranascrionRepoService>();
            _fakedUserRepoService = A.Fake <IUserRepoService>();
            _fakedBotRepoService  = A.Fake <IBotRepoService>();
            _fakedItemRepoService = A.Fake <IItemRepoService>();

            _fakedTransactionWrapper = A.Fake <ITransactionWrapper>();

            A.CallTo(() => fakedRepoServiceFactory.ItemInOfferTransactionRepoService).Returns(_fakedItemInOfferTransactionRepoService);
            A.CallTo(() => fakedRepoServiceFactory.OfferTranascrionRepoService).Returns(_fakedOfferTranascrionRepoService);
            A.CallTo(() => fakedRepoServiceFactory.UserRepoService).Returns(_fakedUserRepoService);
            A.CallTo(() => fakedRepoServiceFactory.BotRepoService).Returns(_fakedBotRepoService);
            A.CallTo(() => fakedRepoServiceFactory.ItemDescriptionRepoService).Returns(fakedItemDescriptionRepoService);
            A.CallTo(() => fakedRepoServiceFactory.ItemRepoService).Returns(_fakedItemRepoService);
            A.CallTo(() => fakedTransactionFactory.BeginTransaction()).Returns(_fakedTransactionWrapper);

            _offerMinmalInfo = new OfferStatusRequest
            {
                Bot = new Bot
                {
                    Username = "******",
                    SteamId  = "botSteamId"
                },
                SteamId       = "userSteamId",
                StatusCode    = int.MinValue,
                StatusMessage = "",
                OfferSend     = new OfferStatusOffer
                {
                    SteamOffer = new SteamOffer
                    {
                        ItemsToGive =
                        {
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "1", MarketHashName = "SomeWeapon1"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "2", MarketHashName = "SomeWeapon1"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "3", MarketHashName = "SomeWeapon2"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "4", MarketHashName = "SomeWeapon3"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "5", MarketHashName = "SomeWeapon4"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "6", MarketHashName = "SomeWeapon2"
                            },
                        },
                        ItemsToReceive =
                        {
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "11", MarketHashName = "SomeWeapon1"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "12", MarketHashName = "SomeWeapon1"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "13", MarketHashName = "SomeWeapon2"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "14", MarketHashName = "SomeWeapon3"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "15", MarketHashName = "SomeWeapon4"
                            },
                            new Item {
                                AppId = 730, ContextId = "2", AssetId = "16", MarketHashName = "SomeWeapon2"
                            },
                        },
                    }
                }
            };


            var someWeapon1 = new DatabaseModel.ItemDescription("SomeWeapon1", new decimal(11.22), "720", "2", "imgUrl", true, 1);
            var someWeapon2 = new DatabaseModel.ItemDescription("SomeWeapon2", new decimal(45.5), "720", "2", "imgUrl", true, 2);
            var someWeapon3 = new DatabaseModel.ItemDescription("SomeWeapon3", new decimal(78.00), "720", "2", "imgUrl", true, 3);
            var someWeapon4 = new DatabaseModel.ItemDescription("SomeWeapon4", new decimal(5.47), "720", "2", "imgUrl", true, 4);

            A.CallTo(() => fakedItemDescriptionRepoService.FindAsync("SomeWeapon1")).Returns(someWeapon1);
            A.CallTo(() => fakedItemDescriptionRepoService.FindAsync("SomeWeapon2")).Returns(someWeapon2);
            A.CallTo(() => fakedItemDescriptionRepoService.FindAsync("SomeWeapon3")).Returns(someWeapon3);
            A.CallTo(() => fakedItemDescriptionRepoService.FindAsync("SomeWeapon4")).Returns(someWeapon4);

            A.CallTo(() => fakedItemDescriptionRepoService.FindAsync(A <List <string> > ._)).Returns(new List <DatabaseModel.ItemDescription>
            {
                someWeapon1,
                someWeapon2,
                someWeapon3,
                someWeapon4,
            });


            _offerService = new OfferService(fakedRepoServiceFactory, fakedTransactionFactory, A.Dummy <ILogServiceFactory>());
        }
Beispiel #29
0
 public ApplyForOfferFacade(IUnitOfWorkProvider uowProvider, FreelancerService freeService, CorporationService corpService, OfferService offerService)
     : base(uowProvider)
 {
     freelancerService  = freeService;
     corporationService = corpService;
     this.offerService  = offerService;
 }
Beispiel #30
0
 public OffersController(OfferService offerService)
 {
     _offerService = offerService;
 }