Пример #1
0
        public string DoRenderIntoFinalStep(IOrder order)
        {
            var listid = ModuleSettingsProvider.GetSettingValue <string>("PriceListID", ModuleID);
            var offers = order.OrderItems.Select(item => OfferService.GetOffer(item.ArtNo));

            return(string.Format("<script type='text/javascript'>var _tmr = _tmr || [];_tmr.push({{type: 'itemView', productid: [{0}], pagetype: 'purchase', totalvalue: '{1}', list: '{2}' }});</script>", offers.Select(o => "'" + o.OfferId + "'").AggregateString(","), order.OrderItems.Sum(item => item.Price * item.Amount), listid));
        }
Пример #2
0
        public void GetOfferShouldReturnNullTest()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "Get_Offer_Null")
                          .Options;

            var offer = new Offer {
                Id = "offerid"
            };



            Offer result;

            using (var context = new ApplicationDbContext(options))
            {
                context.Offers.Add(offer);
                context.SaveChanges();

                IOfferService service = new OfferService(context);
                result = service.GetOffer("false");
            }

            Assert.Null(result);
        }
        protected void btnSendLink_Click(object sender, EventArgs e)
        {
            if (chkCloseAfterConfirmation.Checked)
            {
                chkIsComplete.Checked = true;
            }

            var preOrder = OrderByRequestService.GetOrderByRequest(OrderByRequestId);
            var offer    = OfferService.GetOffer(preOrder.OfferId);

            if (offer.Price == 0)
            {
                lblMessage.Text      = Resource.Admin_OrderByRequest_ZeroPrice;
                lblMessage.Visible   = true;
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
            else
            {
                SaveOrder();
                LoadOrder();

                OrderByRequestService.SendConfirmationMessage(OrderByRequestId);

                lblMessage.Text    = Resource.Admin_OrderByRequest_MailSend;
                lblMessage.Visible = true;
            }
        }
Пример #4
0
        private bool CheckOffer(Offer offer)
        {
            var offerDb = OfferService.GetOffer(offer.ArtNo);

            if (Offers.Any(o => o.ArtNo == offer.ArtNo && o.OfferId != offer.OfferId) || (offerDb != null && offerDb.ProductId != offer.ProductId))
            {
                lErrorOffer.Text    = Resource.Admin_Product_Offers_DuplicateArtNo;
                lErrorOffer.Visible = true;
                return(false);
            }

            if (Offers.Any(o => o.ColorID != null) && Offers.Any(o => o.ColorID == null))
            {
                lErrorOffer.Text    = Resource.Admin_Product_Offers_ColorIsNotNull;
                lErrorOffer.Visible = true;
                return(false);
            }

            if (Offers.Any(o => o.SizeID != null) && Offers.Any(o => o.SizeID == null))
            {
                lErrorOffer.Text    = Resource.Admin_Product_Offers_SizeIsNotNull;
                lErrorOffer.Visible = true;
                return(false);
            }

            if (Offers.GroupBy(x => new { x.SizeID, x.ColorID }).Any(x => x.Count() > 1))
            {
                lErrorOffer.Text    = Resource.Admin_Product_Offers_Duplicate;
                lErrorOffer.Visible = true;
                return(false);
            }

            return(true);
        }
Пример #5
0
        public static void GetRemains(string productsArtS, string warehouse)
        {
            var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
            var endPointAddr = new EndpointAddress("http://cc.Ritm-Z.com:8008/RitmZ_GM82/ws/GetRemains.1cws");
            var getRemains   = new RitmzRemains.WSGetRemainsPortTypeClient(binding, endPointAddr);

            getRemains.ClientCredentials.UserName.UserName = SettingsRitmz.RitmzLogin;
            getRemains.ClientCredentials.UserName.Password = SettingsRitmz.RitmzPassword;
            var ritmzRemains = getRemains.ПолучитьОстатки(productsArtS, warehouse);

            if (ritmzRemains.remains != null)
            {
                for (int i = 0; i < ritmzRemains.remains.Length; ++i)
                {
                    int productId = 0;
                    if (!(Int32.TryParse(ritmzRemains.remains[i].item.id, out productId) && ProductService.IsExists(productId)))
                    {
                        continue;
                    }

                    var offer = OfferService.GetOffer(productId, CatalogService.DefaultOfferListId);
                    offer.Amount = ritmzRemains.remains[0].quantity;
                    OfferService.UpdateOfferByProductId(productId, offer);
                }
            }
        }
Пример #6
0
        // GET: OfferCode
        public ActionResult List(int offerId)
        {
            OfferCodeListViewModel model = new OfferCodeListViewModel();

            model.OfferId       = offerId;
            model.OfferCodeList = new List <OfferCodeViewModel>();
            OfferService offerService = new OfferService();
            Offer        offer        = offerService.GetOffer(offerId);

            if (offer == null || !offerIsOwnedByUserCompany(offerId))
            {
                model.ErrorMessage = "Offer not found.";
                return(View(model));
            }
            model.OfferTitle = offer.Title;

            //Pull data from database and display in table.
            var offerCodeList = offerService.GetAllOfferCodes(offer.Id);
            var offerList     = offerService.GetAllOfferCodes(offer.Id);

            foreach (var item in offerCodeList)
            {
                OfferCodeViewModel offerCodeViewModel = new OfferCodeViewModel();
                offerCodeViewModel.Code        = item.Code;
                offerCodeViewModel.OfferId     = item.OfferId;
                offerCodeViewModel.Id          = item.Id;
                offerCodeViewModel.BuyerEmail  = item.BuyerEmail;
                offerCodeViewModel.DateClaimed = item.ClaimedOn;
                model.OfferCodeList.Add(offerCodeViewModel);
            }
            return(View(model));
        }
Пример #7
0
        public bool isCodeAvailable(int offerId)
        {
            var   offerService = new OfferService();
            Offer offer        = offerService.GetOffer(offerId);
            //List<OfferCode> offerCodeList = new List<OfferCode>();
            var offerCodeList = offerService.GetAllOfferCodes(offer.Id);

            return(offerCodeList.Any(oc => String.IsNullOrEmpty(oc.ClaimingUser)));
            //foreach (OfferCode item in offerCodeList)
            //{
            //    offerCodeList.Add(item);
            //    if (item.ClaimingUser == null)
            //    {
            //        nullCount++;
            //    }
            //}
            //if (nullCount > 0)
            //{
            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
        }
Пример #8
0
        protected void dlItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var item = e.Item;

            if ((item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem))
            {
                var   strQuantity = ((TextBox)item.FindControl("txtQuantity")).Text;
                float quantity    = 0;
                if (float.TryParse(strQuantity, out quantity))
                {
                    var offer = OfferService.GetOffer(((Literal)item.FindControl("ltArtNo")).Text);
                    if ((offer == null) || (quantity > offer.Amount))
                    {
                        var avail = offer == null ? 0 : offer.Amount;
                        ((Label)(item.FindControl("lbMaxCount"))).Text = string.Format("{0}: {1} {2}",
                                                                                       Resource.Client_ShoppingCart_NotAvailable,
                                                                                       avail, Resource.Client_ShoppingCart_NotAvailable_End);
                        ((Label)(item.FindControl("lbMaxCount"))).ForeColor = System.Drawing.Color.Red;
                    }
                    else if (quantity <= offer.Amount)
                    {
                        ((Label)(item.FindControl("lbMaxCount"))).Text      = Resource.Client_ShoppingCart_Available;
                        ((Label)(item.FindControl("lbMaxCount"))).ForeColor = System.Drawing.Color.Green;
                    }
                }
                var btn = ((LinkButton)e.Item.FindControl("buttonDelete"));
                btn.Attributes["data-confirm"] = string.Format(Resource.Admin_OrderItem_Delete);
            }
        }
Пример #9
0
        public bool offerCodeIsOwnedByUserCompany(OfferCode offerCode)
        {
            OfferService offerService = new OfferService();

            if (offerCode != null)
            {
                Offer offer = new Offer();
                offer = offerService.GetOffer(offerCode.OfferId);
                var company = UserCompany;
                if (offer != null && offer.CompanyId != company.Id)
                {
                    offerCode = null;
                }
                if (offerCode == null)
                {
                    //offer ain't there.
                    return(false);
                }
                //if we got this far, should be valid.
                return(true);
            }
            //if offer code is null
            else
            {
                return(false);
            }
        }
Пример #10
0
        public string GetOfferCodeString(int offerId)
        {
            var offerService  = new OfferService();
            var offer         = offerService.GetOffer(offerId);
            var offerCodeList = offerService.GetAllOfferCodes(offerId);
            //offerCodeList = offerCodeList.Where(oc => oc.ClaimedOn != null).ToList();
            string offerCodeString = "Offer Title,Category,Code,Buyer,Date\n";

            foreach (var item in offerCodeList)
            {
                //from https://stackoverflow.com/questions/29893631/how-to-add-double-quotes-to-a-string-which-contains-comma
                //text = text.Contains(",") ? String.Format("\"{0}\"", text) : text;



                offerCodeString +=
                    (offer.Title.Contains(",") ? String.Format("\"{0}\"", offer.Title) : offer.Title)
                    + ",";
                offerCodeString +=
                    (offer.Category.Contains(",") ? String.Format("\"{0}\"", offer.Category) : offer.Category)
                    + ",";
                offerCodeString +=
                    (item.Code.Contains(",") ? String.Format("\"{0}\"", item.Code) : item.Code)
                    + ",";
                offerCodeString +=
                    (item.BuyerEmail.Contains(",") ? String.Format("\"{0}\"", item.BuyerEmail) : item.BuyerEmail)
                    + ",";
                offerCodeString +=
                    (item.ClaimedOn.Contains(",") ? String.Format("\"{0}\"", item.ClaimedOn) : item.ClaimedOn)
                    + ",";
                offerCodeString += "\n";    //new row
            }
            return(offerCodeString);
        }
Пример #11
0
        public ActionResult Edit(int id)
        {
            // ViewBag.Message = "Edit page.";

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

            var offer = offerService.GetOffer(id);

            var model = new OfferViewModel();

            if (offer != null && offer.CompanyId != UserCompany.Id)
            {
                offer = null;
            }
            if (offer == null)
            {
                //offer ain't there.
                model.ErrorMessage = "Offer not found.";
            }

            else
            {
                model.Title       = offer.Title;
                model.Description = offer.Description;
                model.Token       = offer.Token;
                model.Url         = offer.Url;
                model.Category    = offer.Category;
            }

            return(View(model));
        }
Пример #12
0
        static void getOffer()
        {
            Paymill.ApiKey = Properties.Settings.Default.ApiKey;
            Paymill.ApiUrl = Properties.Settings.Default.ApiUrl;
            OfferService offerService = Paymill.GetService <OfferService>();

            Console.WriteLine("Request offer...");
            string offerID = "offer_6eea405f83d4d3098604";
            Offer  offer   = offerService.GetOffer(offerID);

            Console.WriteLine("OfferID:" + offer.Id);
            Console.WriteLine("Created at:" + offer.Created_At.ToShortDateString());
            Console.Read();
        }
Пример #13
0
        public string CodeForUser(int offerId, string userId)
        {
            var   offerService = new OfferService();
            Offer offer        = offerService.GetOffer(offerId);

            var offerCodeList = offerService.GetAllOfferCodes(offer.Id);
            var offerCode     = offerCodeList.Where(oc => oc.ClaimingUser == userId).FirstOrDefault();

            if (offerCode != null)
            {
                return(offerCode.Code);
            }
            else
            {
                return(null);
            }
        }
Пример #14
0
        public ActionResult DownloadCsv(int offerId)
        {
            OfferService service  = new OfferService();
            string       codesCsv = service.GetAllOfferCodesCsv(offerId);
            var          offer    = service.GetOffer(offerId);
            //should offer.Title be model.Title?
            var fileName = "ClaimedOfferCodes_" + offer.Title.Replace(" ", "") + ".csv";

            Response.Clear();
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
            Response.ContentType = "text/csv";
            Response.Write(codesCsv);
            Response.Flush();
            Response.End();

            return(null);
        }
Пример #15
0
        public static void SendConfirmationMessage(int orderByRequestId)
        {
            var orderByRequest = GetOrderByRequest(orderByRequestId);
            var code           = CreateCode(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 linkByRequestMailTemplate = new LinkByRequestMailTemplate(orderByRequest.OrderByRequestId.ToString(),
                                                                          orderByRequest.ArtNo,
                                                                          orderByRequest.ProductName + " " + optionsRender,
                                                                          orderByRequest.Quantity.ToString(), code,
                                                                          orderByRequest.UserName,
                                                                          orderByRequest.LetterComment,
                                                                          offer != null && offer.Color != null
                                                                              ? offer.Color.ColorName
                                                                              : "",
                                                                          offer != null && offer.Size != null
                                                                              ? offer.Size.SizeName
                                                                              : "");

            linkByRequestMailTemplate.BuildMail();
            SendMail.SendMailNow(orderByRequest.Email, linkByRequestMailTemplate.Subject, linkByRequestMailTemplate.Body, true);
        }
Пример #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Code))
            {
                Response.Redirect("~/");
                return;
            }

            // Если код правильный, и такого же товара нет в корзине - то всё ок.
            var orderByRequest = OrderByRequestService.GetOrderByRequest(Code);

            if (orderByRequest == null)
            {
                lblMessage.Text      = Resources.Resource.Client_OrderProduct_Message;
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return;
            }

            if (ShoppingCartService.CurrentShoppingCart.Any(p => p.Offer.OfferId == orderByRequest.OfferId))
            {
                Response.Redirect("shoppingcart.aspx");
            }

            var offer = OfferService.GetOffer(orderByRequest.OfferId);

            if (orderByRequest != null && orderByRequest.IsValidCode && ProductService.IsExists(orderByRequest.ProductId) && offer != null && offer.Price > 0)
            {
                ShoppingCartService.AddShoppingCartItem(new ShoppingCartItem
                {
                    OfferId          = orderByRequest.OfferId,
                    Amount           = orderByRequest.Quantity,
                    ShoppingCartType = ShoppingCartType.ShoppingCart,
                    AttributesXml    = orderByRequest.Options
                });
                Response.Redirect("shoppingcart.aspx");
            }
            else
            {
                lblMessage.Text      = Resources.Resource.Client_OrderProduct_Message;
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }
        }
Пример #17
0
        //overloaded for offerId
        public bool offerIsOwnedByUserCompany(int offerId)
        {
            OfferService offerService = new OfferService();
            var          offer        = offerService.GetOffer(offerId);

            if (offer != null)
            {
                var company = UserCompany;
                if (offer.CompanyId != company.Id)
                {
                    return(false);
                }
                //if we got this far, should be valid.
                return(true);
            }
            //if offer code is null
            else
            {
                return(false);
            }
        }
Пример #18
0
        protected void btnAddProductByArtNo_Click(object sender, EventArgs e)
        {
            Product product = null;
            Offer   offer   = null;

            if (hfOffer.Value.IsNotEmpty())
            {
                int offerId = hfOffer.Value.Trim().TryParseInt();
                if (offerId != 0)
                {
                    offer   = OfferService.GetOffer(offerId);
                    product = ProductService.GetProduct(offer.ProductId);
                }
            }
            else if (txtArtNo.Text.IsNotEmpty())
            {
                string searchTerm = txtArtNo.Text.Trim();

                product = ProductService.GetProduct(searchTerm, true);
                if (product == null)
                {
                    product = ProductService.GetProductByName(searchTerm);
                    if (product == null)
                    {
                        return;
                    }
                }
                else
                {
                    offer = product.Offers.Find(o => o.ArtNo == searchTerm);
                }
            }

            if (product == null)
            {
                return;
            }

            if (offer == null)
            {
                offer = product.Offers[0];
            }

            var item = new OrderItem
            {
                OrderItemID     = GenItemId(),
                Name            = product.Name,
                Price           = offer.Price * (100 - Math.Max(product.Discount, GroupDiscount)) / 100,
                SupplyPrice     = offer.SupplyPrice,
                ProductID       = product.ProductId,
                Amount          = 1,
                ArtNo           = offer.ArtNo,
                Color           = offer.Color != null ? offer.Color.ColorName : null,
                Size            = offer.Size != null ? offer.Size.SizeName : null,
                PhotoID         = offer.Photo != null ? offer.Photo.PhotoId : default(int),
                SelectedOptions = new List <EvaluatedCustomOptions>(),
                IsCouponApplied = CouponCode.IsNotEmpty() && CouponService.GetCouponByCode(CouponCode) != null && CouponService.IsCouponAppliedToProduct(CouponService.GetCouponByCode(CouponCode).CouponID, product.ProductId),
                Weight          = product.Weight
            };


            if (OrderItems == null)
            {
                OrderItems = new List <OrderItem>();
            }

            if (OrderItems.Contains(item))
            {
                OrderItems[OrderItems.IndexOf(item)].Amount += 1;
            }
            else
            {
                OrderItems.Add(item);
            }

            txtArtNo.Text = "";
            hfOffer.Value = "";
            LoadProducts();
            ItemsUpdated(this, new EventArgs());
        }
Пример #19
0
        // POST /cart
        protected static void Cart(string json)
        {
            var yaCart = JsonConvert.DeserializeObject <YaCart>(json);

            if (yaCart == null || yaCart.cart == null)
            {
                return;
            }

            var yaResponse = new YaMarketCartResponse();

            try
            {
                var shoppingCart = new ShoppingCart();

                foreach (var marketItem in yaCart.cart.items)
                {
                    var offer     = OfferService.GetOffer(Convert.ToInt32(marketItem.offerId));
                    var isEnabled = offer != null && offer.Product.Enabled;

                    yaResponse.items.Add(new YaMarketItem(marketItem)
                    {
                        price    = isEnabled ? offer.Price : 0,
                        count    = isEnabled ? offer.Amount : 0,
                        delivery = isEnabled
                    });

                    if (isEnabled)
                    {
                        shoppingCart.Add(new ShoppingCartItem()
                        {
                            OfferId          = offer.OfferId,
                            Amount           = marketItem.count,
                            AttributesXml    = string.Empty,
                            ShoppingCartType = ShoppingCartType.ShoppingCart,
                        });
                    }
                }

                var city   = GetByType("CITY", yaCart.cart.delivery.region) ?? string.Empty;
                var region = GetByType("REGION", yaCart.cart.delivery.region) ??
                             (GetByType("SUBJECT_FEDERATION", yaCart.cart.delivery.region) ?? string.Empty);
                var country   = GetByType("COUNTRY", yaCart.cart.delivery.region) ?? "Россия";
                var countryId = CountryService.GetCountryByName(country).CountryId;

                var shippingManager   = new ShippingManager();
                var shippingRates     = shippingManager.GetShippingRates(countryId, "", city, region, shoppingCart, 0);
                var yaMarketShippings = YaMarketByuingService.GetShippings();


                foreach (var shippingRate in shippingRates.OrderBy(x => x.Rate))
                {
                    var shipping = yaMarketShippings.FirstOrDefault(x => x.ShippingMethodId == shippingRate.MethodId);
                    if (shipping == null)
                    {
                        continue;
                    }

                    var delivery = new YaMarketDeliveryResponse()
                    {
                        id          = shippingRate.Id.ToString(),
                        type        = shipping.Type,
                        serviceName = shippingRate.MethodNameRate,
                        price       = shippingRate.Rate,
                        dates       = new YaMarketDate()
                        {
                            fromDate = DateTime.Now.AddDays(shipping.MinDate).ToString("dd-MM-yyyy"), // todo
                            toDate   = DateTime.Now.AddDays(shipping.MaxDate).ToString("dd-MM-yyyy")
                        }
                    };

                    if (delivery.type == "PICKUP" && YaMarketBuyingSettings.Outlets.IsNotEmpty())
                    {
                        delivery.outlets = new List <YaMarketOutlet>();
                        foreach (var outlet in YaMarketBuyingSettings.Outlets.Split(';'))
                        {
                            delivery.outlets.Add(new YaMarketOutlet()
                            {
                                id = Convert.ToInt32(outlet)
                            });
                        }
                    }

                    yaResponse.deliveryOptions.Add(delivery);
                }

                foreach (var payment in YaMarketBuyingSettings.Payments.Split(';'))
                {
                    yaResponse.paymentMethods.Add(payment);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }

            var context = HttpContext.Current;

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(new { cart = yaResponse }));
            context.Response.End();
        }
Пример #20
0
        public void OfferCodeCRUDUsingToken()
        {
            //create (offer)
            var Offer           = new Offer();
            var testTitle       = "Sword Sale";
            var testDescription = "90% off these real dull swords!";
            var testUrl         = "fakeurl.bamazon.swords/";
            var testCategory    = "Weapons";
            var testCompanyId   = RandomInteger();

            Offer.Title       = testTitle;
            Offer.Description = testDescription;
            Offer.Url         = testUrl;
            Offer.Category    = testCategory;
            Offer.CompanyId   = testCompanyId;

            //create (offercode)
            var OfferCode = new OfferCode();
            var testCode  = "ABCDEF" + RandomDigits();

            OfferCode.OfferId = Offer.Id;
            OfferCode.Code    = testCode;

            var OfferService = new OfferService();

            OfferService.SaveOffer(Offer);
            Assert.IsTrue(Offer.Id != 0);

            OfferService.SaveOfferCode(OfferCode);
            Assert.IsTrue(OfferCode.Id != 0);

            var offer1 = OfferService.GetOffer(Offer.Id);

            // get it, verify it's there (offer)
            var OfferToken = offer1.Token;
            var Offer2     = OfferService.GetOfferByToken(OfferToken);

            Assert.IsNotNull(Offer2);

            // get it, verify it's there (offercode)
            var OfferCodeId = OfferCode.Id;
            var OfferCode2  = OfferService.GetOfferCode(OfferCodeId);

            Assert.IsNotNull(OfferCode2);

            // verify property values (offer)
            Assert.AreEqual(Offer2.Title, testTitle);
            Assert.AreEqual(Offer2.Description, testDescription);
            Assert.AreEqual(Offer2.Url, testUrl);
            Assert.AreEqual(Offer2.Category, testCategory);
            Assert.AreEqual(Offer2.CompanyId, testCompanyId);

            //verify property values (offercode)
            Assert.AreEqual(OfferCode2.OfferId, OfferCode.OfferId);
            Assert.AreEqual(OfferCode2.Code, testCode);

            //update offercode
            var testCode2 = "XYZ123" + RandomDigits();

            OfferCode2.Code = testCode2;
            OfferService.SaveOfferCode(OfferCode2);

            // get it again, verify property values
            var OfferCode3 = OfferService.GetOfferCode(OfferCode2.Id);

            Assert.AreEqual(testCode2, OfferCode3.Code);

            //delete it
            OfferService.DeleteOfferCode(OfferCodeId);
            OfferCode3 = OfferService.GetOfferCode(OfferCodeId);
            Assert.IsNull(OfferCode3);
            //var Offer = new Offer();
            //var testTitle = "Bracelets";
            //var testDescription = "70% off this gold jewelry shining so bright! " +
            //    "Goes great with strawberry champagne!";
            //var testUrl = "fakeurl.bamazon.whatilike/";
            //var testCategory = "Jewelry";

            //var testCompanyId = RandomInteger();

            //Offer.Title = testTitle;
            //Offer.Description = testDescription;
            //Offer.Url = testUrl;
            //Offer.Category = testCategory;
            //Offer.CompanyId = testCompanyId;

            ////create (offercode)
            //var offerCode1 = new OfferCode();
            //offerCode1.Code = "A" + RandomDigits();
            //var offerCode2 = new OfferCode();
            //offerCode2.Code = "B" + RandomDigits();
            //var offerCode3 = new OfferCode();
            //offerCode3.Code = "C" + RandomDigits();
            //offerCode1.OfferId = Offer.Id;
            //offerCode2.OfferId = Offer.Id;
            //offerCode3.OfferId = Offer.Id;

            //OfferService offerService = new OfferService();

            //offerService.SaveOffer(Offer);
            //Assert.IsTrue(Offer.Id != 0);

            //offerCode1.OfferId = Offer.Id;
            //offerCode2.OfferId = Offer.Id;
            //offerCode3.OfferId = Offer.Id;

            //offerService.SaveOfferCode(offerCode1);
            //offerService.SaveOfferCode(offerCode2);
            //offerService.SaveOfferCode(offerCode3);
            //Assert.IsTrue(offerCode1.Id != 0);
            //Assert.IsTrue(offerCode2.Id != 0);
            //Assert.IsTrue(offerCode3.Id != 0);

            //var userId1 = "Jackie Bolton";

            //var code1 = offerService.ClaimNextCode(Offer.Id, userId1);
            //Assert.IsTrue(!String.IsNullOrEmpty(code1));
            ////Verify that the first code is claimed by Jackie
            //offerCode1 = offerService.GetOfferCode(offerCode1.Id);
            //Assert.IsTrue(offerCode1.ClaimingUser.Equals(userId1));

            //var userId2 = "Sandra Lollygagger";

            //var code2 = offerService.ClaimNextCode(Offer.Id, userId2);
            //Assert.IsTrue(!String.IsNullOrEmpty(code2));
            ////Verify that the second code is claimed by Sandra
            //offerCode2 = offerService.GetOfferCode(offerCode2.Id);
            //Assert.IsTrue(offerCode2.ClaimingUser.Equals(userId2));
            //Assert.IsTrue(!offerCode1.ClaimingUser.Equals(offerCode2.ClaimingUser));

            //var userId3 = "Kevin Spaceman";

            //var code3 = offerService.ClaimNextCode(Offer.Id, userId3);
            //Assert.IsTrue(!String.IsNullOrEmpty(code3));
            ////Verify that the third code is claimed by Kevin
            //offerCode3 = offerService.GetOfferCode(offerCode3.Id);
            //Assert.IsTrue(offerCode3.ClaimingUser.Equals(userId3));
            //Assert.IsTrue(!offerCode1.ClaimingUser.Equals(offerCode3.ClaimingUser));

            //var userId4 = "Richmond Nocode";

            //var code4 = offerService.ClaimNextCode(Offer.Id, userId4);
            ////This time verifying that code4 IS empty because we have no more codes in the offer.
            //Assert.IsTrue(String.IsNullOrEmpty(code4));

            //offerService.DeleteOfferCode(offerCode1.Id);
            //offerService.DeleteOfferCode(offerCode2.Id);
            //offerService.DeleteOfferCode(offerCode3.Id);

            //offerService.DeleteOffer(Offer.Id);
        }
Пример #21
0
        public void OfferCodeCRUD()
        {
            //create (offer)
            var Offer           = new Offer();
            var testTitle       = "Sword Sale";
            var testDescription = "90% off these real dull swords!";
            var testUrl         = "fakeurl.bamazon.swords/";
            var testCategory    = "Weapons";
            var testCompanyId   = RandomInteger();

            Offer.Title       = testTitle;
            Offer.Description = testDescription;
            Offer.Url         = testUrl;
            Offer.Category    = testCategory;
            Offer.CompanyId   = testCompanyId;

            //create (offercode)
            var OfferCode = new OfferCode();
            var testCode  = "ABCDEF" + RandomDigits();

            OfferCode.OfferId = Offer.Id;
            OfferCode.Code    = testCode;

            var OfferService = new OfferService();

            OfferService.SaveOffer(Offer);
            Assert.IsTrue(Offer.Id != 0);

            OfferService.SaveOfferCode(OfferCode);
            Assert.IsTrue(OfferCode.Id != 0);

            // get it, verify it's there (offer)
            var OfferId = Offer.Id;
            var Offer2  = OfferService.GetOffer(OfferId);

            Assert.IsNotNull(Offer2);

            // get it, verify it's there (offercode)
            var OfferCodeId = OfferCode.Id;
            var OfferCode2  = OfferService.GetOfferCode(OfferCodeId);

            Assert.IsNotNull(OfferCode2);

            // verify property values (offer)
            Assert.AreEqual(Offer2.Title, testTitle);
            Assert.AreEqual(Offer2.Description, testDescription);
            Assert.AreEqual(Offer2.Url, testUrl);
            Assert.AreEqual(Offer2.Category, testCategory);
            Assert.AreEqual(Offer2.CompanyId, testCompanyId);

            //verify property values (offercode)
            Assert.AreEqual(OfferCode2.OfferId, OfferCode.OfferId);
            Assert.AreEqual(OfferCode2.Code, testCode);

            //update offercode
            var testCode2 = "XYZ123" + RandomDigits();

            OfferCode2.Code = testCode2;
            OfferService.SaveOfferCode(OfferCode2);

            // get it again, verify property values
            var OfferCode3 = OfferService.GetOfferCode(OfferCode2.Id);

            Assert.AreEqual(testCode2, OfferCode3.Code);

            //delete it
            OfferService.DeleteOfferCode(OfferCodeId);
            OfferCode3 = OfferService.GetOfferCode(OfferCodeId);
            Assert.IsNull(OfferCode3);
        }
Пример #22
0
        // POST /order/accept
        protected static void Accept(string json)
        {
            var yaOrder = JsonConvert.DeserializeObject <YaMarketOrderRequest>(json);

            if (yaOrder == null || yaOrder.order == null)
            {
                return;
            }

            Order order = null;

            try
            {
                var adminComment = "";

                adminComment = "Заказ номер: " + yaOrder.order.id + (yaOrder.order.fake ? "(тестовый)" : "") + "\r\n";

                if (yaOrder.order.paymentType.IsNotEmpty())
                {
                    adminComment += "Тип оплаты заказа: " +
                                    (yaOrder.order.paymentType == "PREPAID"
                                        ? "предоплата"
                                        : "постоплата при получении заказа") + "\r\n";
                }

                if (yaOrder.order.paymentMethod.IsNotEmpty())
                {
                    adminComment += "Способ оплаты заказа: ";
                    switch (yaOrder.order.paymentMethod)
                    {
                    case "YANDEX":
                        adminComment += "оплата при оформлении";
                        break;

                    case "SHOP_PREPAID":
                        adminComment += "предоплата напрямую магазину (только для Украины)";
                        break;

                    case "CASH_ON_DELIVERY":
                        adminComment += "наличный расчет при получении заказа";
                        break;

                    case "CARD_ON_DELIVERY":
                        adminComment += "оплата банковской картой при получении заказа";
                        break;
                    }
                }

                adminComment += "\r\n";

                var orderContact       = new OrderContact();
                var shippingCost       = 0f;
                var shippingMethodName = "";

                if (yaOrder.order.delivery != null)
                {
                    adminComment += string.Format("Доставка: {0}, стоимость доставки: {1}, даты: {2} до {3}\r\n",
                                                  yaOrder.order.delivery.serviceName, yaOrder.order.delivery.price ?? 0,
                                                  yaOrder.order.delivery.dates.fromDate, yaOrder.order.delivery.dates.toDate);

                    orderContact = new OrderContact
                    {
                        Address =
                            yaOrder.order.delivery.address.street + " " + yaOrder.order.delivery.address.house + " " +
                            yaOrder.order.delivery.address.subway + " " + yaOrder.order.delivery.address.block + " " +
                            yaOrder.order.delivery.address.floor,
                        City    = yaOrder.order.delivery.address.city,
                        Country = yaOrder.order.delivery.address.country,
                        Name    = string.Empty,
                        Zip     = yaOrder.order.delivery.address.postcode ?? string.Empty,
                        Zone    = string.Empty
                    };

                    if (yaOrder.order.delivery.price != null)
                    {
                        shippingCost = (float)yaOrder.order.delivery.price;
                    }

                    shippingMethodName = yaOrder.order.delivery.serviceName;
                }

                var orderItems = (from item in yaOrder.order.items
                                  let offer = OfferService.GetOffer(Convert.ToInt32(item.offerId))
                                              where offer != null
                                              let product = offer.Product
                                                            select new OrderItem()
                {
                    Name = product.Name,
                    Price = item.price,
                    Amount = item.count,
                    SupplyPrice = product.Offers[0].SupplyPrice,
                    ProductID = product.ProductId,
                    ArtNo = product.ArtNo,
                    IsCouponApplied = false,
                    Weight = product.Weight
                }).ToList();

                var orderCurrency = yaOrder.order.currency == "RUR"
                    ? (CurrencyService.GetAllCurrencies(true)
                       .FirstOrDefault(x => x.Iso3 == yaOrder.order.currency || x.Iso3 == "RUB") ??
                       CurrencyService.GetAllCurrencies(true).FirstOrDefault())
                    : (CurrencyService.GetAllCurrencies(true).FirstOrDefault(x => x.Iso3 == yaOrder.order.currency) ??
                       CurrencyService.GetAllCurrencies(true).FirstOrDefault());

                order = new Order()
                {
                    AdminOrderComment = adminComment,
                    CustomerComment   = yaOrder.order.notes,
                    OrderCustomer     = new OrderCustomer()
                    {
                        Email      = "*****@*****.**",
                        CustomerIP = "127.0.0.1"
                    },
                    OrderItems           = orderItems,
                    OrderCurrency        = orderCurrency,
                    ShippingContact      = orderContact,
                    BillingContact       = orderContact,
                    ShippingCost         = shippingCost,
                    ArchivedShippingName = shippingMethodName,
                    OrderStatusId        = OrderService.DefaultOrderStatus,
                    OrderDate            = DateTime.Now,
                    Number = OrderService.GenerateNumber(1),
                };

                order.OrderID = OrderService.AddOrder(order);
                order.Number  = OrderService.GenerateNumber(order.OrderID);
                OrderService.UpdateNumber(order.OrderID, order.Number);
                OrderService.ChangeOrderStatus(order.OrderID, OrderService.DefaultOrderStatus);


                if (order.OrderID != 0)
                {
                    YaMarketByuingService.AddOrder(new YaOrder()
                    {
                        MarketOrderId = yaOrder.order.id.TryParseInt(),
                        OrderId       = order.OrderID,
                        Status        = string.Format("[{0}] Создан заказ {1}", DateTime.Now.ToString("g"), order.OrderID)
                    });

                    try
                    {
                        var orderTable = OrderService.GenerateHtmlOrderTable(order.OrderItems, order.OrderCurrency,
                                                                             orderItems.Sum(x => x.Price * x.Amount), 0, null, null, 0, 0, 0, 0, 0, 0);

                        var mailTemplate = new BuyInOneClickMailTemplate(order.OrderID.ToString(), "", "", "", orderTable);
                        mailTemplate.BuildMail();

                        SendMail.SendMailNow(SettingsMail.EmailForOrders, "Заказ через Яндекс.Маркет", mailTemplate.Body,
                                             true);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(ex);
            }

            /*
             * Если магазин считает запрос, поступающий от Яндекс.Маркета, некорректным,
             * магазин должен вернуть статус ответа 400 с описанием причины ошибки в теле ответа.
             * Такие ответы будут анализироваться на предмет нарушений и недоработок API со стороны Яндекс.Маркета.
             *
             */
            var orderResponse = new YaMarketOrderResponse()
            {
                order = new YaMarketOrderAccept()
                {
                    accepted = order != null && order.OrderID != 0,
                    id       = yaOrder.order.id
                }
            };

            var context = HttpContext.Current;

            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(orderResponse));
            context.Response.End();
        }
Пример #23
0
            public void OfferCRUD()
            {
                // create
                var Offer           = new Offer();
                var testTitle       = "Knife Sale";
                var testDescription = "40% off these real sharp knives!";
                var testUrl         = "fakeurl.amazon.com/";
                var testCategory    = "Kitchen Supplies";
                var testCompanyId   = RandomInteger();

                Offer.Title       = testTitle;
                Offer.Description = testDescription;
                Offer.Url         = testUrl;
                Offer.Category    = testCategory;
                Offer.CompanyId   = testCompanyId;


                var OfferService = new OfferService();

                OfferService.SaveOffer(Offer);
                Assert.IsTrue(Offer.Id != 0);

                // get it, verify it's there
                var OfferId = Offer.Id;
                var Offer2  = OfferService.GetOffer(OfferId);

                Assert.IsNotNull(Offer2);

                // verify property values
                Assert.AreEqual(Offer2.Title, testTitle);
                Assert.AreEqual(Offer2.Description, testDescription);
                Assert.AreEqual(Offer2.Url, testUrl);
                Assert.AreEqual(Offer2.Category, testCategory);
                Assert.AreEqual(Offer2.CompanyId, testCompanyId);



                //// Verify that I can get by user id
                //var OfferUserId = OfferService.GetByUserId(testUserId);
                //Assert.IsNotNull(OfferUserId);

                // update it
                var testTitle2       = "Jills Offer " + RandomDigits();
                var testDescription2 = "Since no one's buying, 95% off these real sharp knives!";
                var testCategory2    = "Weapons";

                Offer2.Title       = testTitle2;
                Offer2.Description = testDescription2;
                Offer2.Category    = testCategory2;
                OfferService.SaveOffer(Offer2);


                // get it again, verify property values
                var Offer3 = OfferService.GetOffer(OfferId);

                Assert.AreEqual(testTitle2, Offer3.Title);
                Assert.AreEqual(testDescription2, Offer3.Description);
                Assert.AreEqual(testCategory2, Offer3.Category);


                // delete it
                OfferService.DeleteOffer(OfferId);
                Offer3 = OfferService.GetOffer(OfferId);
                Assert.IsNull(Offer3);
            }
Пример #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            lDemoWarning.Visible = Demo.IsDemoEnabled || TrialService.IsTrialEnabled;

            //BuyInOneClick.Visible = SettingsOrderConfirmation.BuyInOneClick;

            if (!IsPostBack)
            {
                if (Request["products"].IsNotEmpty())
                {
                    foreach (var item in Request["products"].Split(";"))
                    {
                        int offerId;
                        var newItem = new ShoppingCartItem()
                        {
                            ShoppingCartType = ShoppingCartType.ShoppingCart, CustomerId = CustomerContext.CustomerId
                        };

                        var parts = item.Split("-");
                        if (parts.Length > 0 && (offerId = parts[0].TryParseInt(0)) != 0 && OfferService.GetOffer(offerId) != null)
                        {
                            newItem.OfferId = offerId;
                        }
                        else
                        {
                            continue;
                        }

                        if (parts.Length > 1)
                        {
                            newItem.Amount = parts[1].TryParseFloat();
                        }
                        else
                        {
                            newItem.Amount = 1;
                        }

                        var currentItem = ShoppingCartService.CurrentShoppingCart.FirstOrDefault(shpCartitem => shpCartitem.OfferId == newItem.OfferId);

                        if (currentItem != null)
                        {
                            currentItem.Amount = newItem.Amount;
                            ShoppingCartService.UpdateShoppingCartItem(currentItem);
                        }
                        else
                        {
                            ShoppingCartService.AddShoppingCartItem(newItem);
                        }
                    }
                    Response.Redirect("shoppingcart.aspx");
                    return;
                }

                UpdateBasket();
                SetMeta(new MetaInfo(string.Format("{0} - {1}", SettingsMain.ShopName, Resource.Client_ShoppingCart_ShoppingCart)), string.Empty);

                if (GoogleTagManager.Enabled)
                {
                    var tagManager = ((AdvantShopMasterPage)Master).TagManager;
                    tagManager.PageType   = GoogleTagManager.ePageType.cart;
                    tagManager.ProdIds    = ShoppingCartService.CurrentShoppingCart.Select(item => item.Offer.ArtNo).ToList();
                    tagManager.TotalValue = ShoppingCartService.CurrentShoppingCart.TotalPrice;
                }
            }

            var showConfirmButtons = true;

            //подключение модуля
            foreach (var module in AttachedModules.GetModules <IRenderIntoShoppingCart>())
            {
                var moduleObject = (IRenderIntoShoppingCart)Activator.CreateInstance(module, null);

                ltrlBottomContent.Text = moduleObject.DoRenderToBottom();
                ltrlTopContent.Text    = moduleObject.DoRenderToTop();

                if (!string.IsNullOrEmpty(moduleObject.ClientSideControlNameBottom))
                {
                    var userControl =
                        (this).LoadControl(moduleObject.ClientSideControlNameBottom);

                    if (userControl != null)
                    {
                        ((IUserControlInSc)userControl).ProductIds =
                            ShoppingCartService.CurrentShoppingCart.Select(p => p.Offer.ProductId).ToList();
                        pnlBottomContent.Controls.Add(userControl);
                    }
                }
                if (!string.IsNullOrEmpty(moduleObject.ClientSideControlNameTop))
                {
                    var userControl =
                        (this).LoadControl(moduleObject.ClientSideControlNameTop);

                    if (userControl != null)
                    {
                        ((IUserControlInSc)userControl).ProductIds =
                            ShoppingCartService.CurrentShoppingCart.Select(p => p.Offer.ProductId).ToList();
                        pnlTopContent.Controls.Add(userControl);
                    }
                }
                showConfirmButtons &= moduleObject.ShowConfirmButtons;
            }

            BuyInOneClick.Visible = showConfirmButtons && SettingsOrderConfirmation.BuyInOneClick;
            aCheckOut.Visible     = showConfirmButtons;
        }