public static int AddProductRate(int productID, int Rate, Guid UserID = new Guid())
        {
            var rate = new ProductRate();

            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            if (UserID == Guid.Empty)
            {
                return(0);
            }
            rate = LS.CurrentEntityContext.ProductRates.FirstOrDefault(x => x.ProductID == productID && x.UserID == UserID);
            if (rate != null)
            {
                var product = LS.CurrentEntityContext.Products.FirstOrDefault(x => x.ID == productID);
                if (product != null)
                {
                    product.Rate = (product.Rate * product.RateCount - rate.Rate + Rate) / (product.RateCount);
                    // pr.RateCount++;
                    rate.Rate = Rate;
                    LS.CurrentEntityContext.SaveChanges();
                }
                return(rate.ID);
            }
            rate           = new ProductRate();
            rate.UserID    = UserID;
            rate.Rate      = Rate;
            rate.ProductID = productID;

            LS.CurrentEntityContext.ProductRates.Add(rate);
            LS.CurrentEntityContext.SaveChanges();

            var pr = LS.CurrentEntityContext.Products.FirstOrDefault(x => x.ID == productID);

            if (pr != null)
            {
                pr.Rate = (pr.Rate * pr.RateCount + Rate) / (pr.RateCount + 1);
                pr.RateCount++;
                LS.CurrentEntityContext.SaveChanges();
            }
            return(rate.ID);
        }
示例#2
0
        public ActionResult Details(long id)
        {
            var session = (UserLogin)Session[CommonConstants.USER_SESSION];

            if (session == null)
            {
                ViewBag.Session = "null";
            }
            else
            {
                ViewBag.Session = session;
                ViewBag.Watched = session;
            }
            var product = new ProductData().ViewDetail(id);
            //Thêm barcode
            Image img = null;

            using (var ms = new MemoryStream())
            {
                var writer = new ZXing.BarcodeWriter()
                {
                    Format = BarcodeFormat.CODE_128
                };
                writer.Options.Height      = 40;
                writer.Options.Width       = 140;
                writer.Options.PureBarcode = true;
                img = writer.Write(product.BarCode);
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ViewBag.BarcodeImage = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
                //return File(ms.ToArray(), "image/jpeg");
            }
            ViewBag.Product = product;
            //ViewBag.Comment = new CommentData().GetListComment(id);
            ViewBag.Type   = new ProductData().RelateProduct(product.ProductID, product.CategoryID);
            ViewBag.User   = new UserData().ListAll();
            ViewBag.Rating = new RatingData().ListProductRate(id);
            var productRate = new ProductRate()
            {
                ProductID = product.ProductID
            };

            return(View(productRate));
        }
        public async Task <bool> Handle(AddProductRateCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(false);
            }

            var product = await _productRepository.FindById(request.ProductCode);

            if (product == null)
            {
                await _bus.Publish(new ExceptionNotification("001", "Produto informado não encontrato."),
                                   CancellationToken.None);

                return(false);
            }
            var evaluation     = product.FindEvaluateByUserId(request.UserId);
            var userEvaluation = new ProductRate(request.RatePoints, request.Comment, request.UserId, request.UserName);

            if (evaluation != null)
            {
                product.RemoveProductEvaluation(evaluation.Id);
            }
            product.AddEvaluationToProduct(userEvaluation);

            if (await Commit())
            {
                return(true);
            }

            await _bus.Publish(new ExceptionNotification("002",
                                                         "Algo de errado aconteceu ao adicionar sua avaliaçõa! Tente mais tarde."),
                               CancellationToken.None);

            return(false);
        }
示例#4
0
 public void Initialize()
 {
     //New instance of Product Rate
     _productRate = new ProductRate();
 }
示例#5
0
        private void ParseProductBody(Product product, string bodyNative, List <string> discovered)
        {
            var document = new HtmlDocument();

            document.LoadHtml(bodyNative);

            #region Stock
            var outstockNode     = document.DocumentNode.Descendants().SingleOrDefaultByNameNClass("h5", "notice");
            var stockWarningNode = document.DocumentNode.Descendants().SingleOrDefaultByNameNClass("div", "unit-labels");

            if (outstockNode != null && outstockNode.InnerText.TrimStart().TrimEnd() == "This item is currently out of stock")
            {
                product.Availability = ProductAvailability.OutStock;
                product.StockCount   = null;
            }
            else if (stockWarningNode != null && stockWarningNode.InnerText.TrimStart().TrimEnd() != "")
            {
                var stockCount = int.Parse(stockWarningNode.InnerText.Replace("Only ", "")
                                           .Replace(" left in stock!", "").TrimStart().TrimEnd());

                product.Availability = ProductAvailability.NearOutStock;
                product.StockCount   = stockCount;
            }
            else
            {
                product.Availability = ProductAvailability.InStock;
            }
            #endregion

            #region Rating
            var ratingNode = document.DocumentNode.Descendants()
                             .SingleByNameNContainClass("div", new[] { "product-rating" });

            var averageRatingNode = ratingNode.Descendants().SingleByNameNContainClass("div", new[] { "avg" });
            var stars5RatingNode  = ratingNode.Descendants().FindByNameNContainClass("div", new[] { "rate-avg" })
                                    .SelectMany(l => l.Descendants())
                                    .SingleOrDefaultByNameNContainClass("span", new[] { "label", "starRating_5" });
            var stars4RatingNode = ratingNode.Descendants().FindByNameNContainClass("div", new[] { "rate-avg" })
                                   .SelectMany(l => l.Descendants())
                                   .SingleOrDefaultByNameNContainClass("span", new[] { "label", "starRating_4" });
            var stars3RatingNode = ratingNode.Descendants().FindByNameNContainClass("div", new[] { "rate-avg" })
                                   .SelectMany(l => l.Descendants())
                                   .SingleOrDefaultByNameNContainClass("span", new[] { "label", "starRating_3" });
            var stars2RatingNode = ratingNode.Descendants().FindByNameNContainClass("div", new[] { "rate-avg" })
                                   .SelectMany(l => l.Descendants())
                                   .SingleOrDefaultByNameNContainClass("span", new[] { "label", "starRating_2" });
            var stars1RatingNode = ratingNode.Descendants().FindByNameNContainClass("div", new[] { "rate-avg" })
                                   .SelectMany(l => l.Descendants())
                                   .SingleOrDefaultByNameNContainClass("span", new[] { "label", "starRating_1" });
            var totalReviewsNode   = ratingNode.Descendants().SingleOrDefaultByNameNClass("div", "reviews-total");
            var recommendationNode = ratingNode.Descendants().SingleOrDefaultByNameNClass("span", "messaging");

            var averageRateValue = float.Parse(averageRatingNode.InnerText.TrimStart().TrimEnd());

            if (averageRateValue > 0)
            {
                var stars5RatingValue = int.Parse(stars5RatingNode.InnerText.Replace(",", "").Replace("(", "").Replace(")", ""));
                var stars4RatingValue = int.Parse(stars4RatingNode.InnerText.Replace(",", "").Replace("(", "").Replace(")", ""));
                var stars3RatingValue = int.Parse(stars3RatingNode.InnerText.Replace(",", "").Replace("(", "").Replace(")", ""));
                var stars2RatingValue = int.Parse(stars2RatingNode.InnerText.Replace(",", "").Replace("(", "").Replace(")", ""));
                var stars1RatingValue = int.Parse(stars1RatingNode.InnerText.Replace(",", "").Replace("(", "").Replace(")", ""));
                var totalRatingValue  =
                    int.Parse(totalReviewsNode.InnerText.Replace("ratings", "").Replace("rating", "").TrimStart().TrimEnd());
                var recommendationValue = recommendationNode.InnerText.TrimStart().TrimEnd() != ""
                    ? (float?)float.Parse(recommendationNode.InnerText.TrimStart().TrimEnd())
                    : null;

                ProductRate productRate = new ProductRate()
                {
                    AverageRate              = averageRateValue,
                    Rate5Count               = stars5RatingValue,
                    Rate4Count               = stars4RatingValue,
                    Rate3Count               = stars3RatingValue,
                    Rate2Count               = stars2RatingValue,
                    Rate1Count               = stars1RatingValue,
                    TotalRateCount           = totalRatingValue,
                    RecommendationPercentage = recommendationValue
                };

                product.HasRating = true;
                product.Rate      = productRate;
            }
            #endregion

            #region Price

            if (product.Availability != ProductAvailability.OutStock)
            {
                var priceNode = document.DocumentNode.Descendants()
                                .SingleByNameNContainClass("div", new[] { "price-container" });
                var currentPriceNode  = priceNode.Descendants().SingleByNameNContainClass("h3", new[] { "price", "is" });
                var absolutePriceNode = priceNode.Descendants().SingleOrDefaultByNameNClass("span", "was");
                var savePriceNode     = priceNode.Descendants().SingleOrDefaultByNameNClass("span", "saved ")?.Descendants()
                                        .SingleByNameNClass("span", "noWrap");

                var currentPriceValue = double.Parse(currentPriceNode.InnerText
                                                     .Replace("&nbsp;", "")
                                                     .ToUpper().Replace("EGP", "")
                                                     .TrimStart().TrimEnd());

                product.CurrentPrice = currentPriceValue;

                if (absolutePriceNode != null && savePriceNode != null)
                {
                    var absolutePriceValue =
                        double.Parse(absolutePriceNode.InnerText
                                     .Replace("&nbsp;", "")
                                     .ToUpper().Replace("EGP", "").TrimStart().TrimEnd());
                    var savingPriceValue =
                        double.Parse(savePriceNode.InnerText
                                     .Replace("&nbsp;", "")
                                     .ToUpper().Replace("EGP", "").TrimStart().TrimEnd());

                    product.HasDiscount        = true;
                    product.AbsolutePrice      = absolutePriceValue;
                    product.DiscountSaving     = savingPriceValue;
                    product.DiscountPercentage =
                        (int?)Math.Ceiling((1.0d - (product.CurrentPrice / product.AbsolutePrice.Value)) * 100);
                }
                else
                {
                    product.HasDiscount        = false;
                    product.AbsolutePrice      = null;
                    product.DiscountSaving     = null;
                    product.DiscountPercentage = null;
                }
            }

            #endregion

            #region Condition

            if (product.Availability != ProductAvailability.OutStock)
            {
                var conditionNode = document.DocumentNode.Descendants().SingleByNameNClass("dd", "unit-condition");
                product.Condition = conditionNode.InnerText.TrimStart().TrimEnd();
            }

            #endregion

            #region Seller

            if (product.Availability != ProductAvailability.OutStock)
            {
                var sellerNode = document.DocumentNode.Descendants().SingleByNameNClass("span", "unit-seller-link")
                                 .Descendants().SingleByName("a");
                var sellerNotesNode   = document.DocumentNode.Descendants().SingleOrDefaultByNameNClass("span", "seller-notes");
                var sellerName        = sellerNode.InnerText.TrimStart().TrimEnd();
                var sellerPortfoliUrl = sellerNode.Attributes["href"].Value;
                var sellerId          = sellerPortfoliUrl.ExtractSellerId();

                Console.WriteLine(sellerId);

                _semaphore_SellerQuery.WaitOne();

                try
                {
                    if (sellers.All(l => l.Name != sellerName))
                    {
                        //Debugger.Break();
                        throw new Exception("Inconsist Product Body & Bucket");
                    }
                    else
                    {
                        var sellerObj = sellers.Single(l => l.Name == sellerName);
                        sellerObj.Url    = sellerPortfoliUrl;
                        sellerObj.UserId = sellerId;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "Inconsist Product Body & Bucket")
                    {
                        Debugger.Break();
                    }

                    _semaphore_SellerQuery.Release();

                    throw;
                }

                _semaphore_SellerQuery.Release();

                product.SellerNote = sellerNotesNode?.InnerText.TrimStart().TrimEnd();
            }

            #endregion

            #region Connections

            var connectionsNode = document.DocumentNode.Descendants().SingleOrDefaultByNameNClass("div", "product-connections");

            if (connectionsNode != null)
            {
                var connectionsDictionaryNodes = connectionsNode.Descendants()
                                                 .FindByNameNClass("div", "connection-stand")
                                                 .ToDictionary(l => l.PreviousSibling.PreviousSibling, l => l);

                foreach (var connectionNode in connectionsDictionaryNodes)
                {
                    var connectionsValuesNode =
                        connectionNode.Value.Descendants().FindByNameNClass("a", "value size-value");
                    var connectionTitle  = connectionNode.Key.InnerText.TrimStart().TrimEnd();
                    var connectionsValue = connectionsValuesNode.Select(l => new
                    {
                        Url       = l.Attributes["data-url"].Value,
                        IsEnabled = bool.Parse(l.Attributes["data-enabled"].Value),
                        Value     = l.InnerText.TrimStart().TrimEnd()
                    }).ToList();

                    var discoveredProducts = connectionsValue.Where(l => !l.IsEnabled).Select(l => l.Url);

                    foreach (var discoveredProduct in discoveredProducts)
                    {
                        if (discovered.All(l => l != discoveredProduct))
                        {
                            discovered.Add(discoveredProduct);
                        }
                    }

                    _semaphore_AttributeQuery.WaitOne();

                    ProductAttributeDefinition definition =
                        attributeDefinitons.SingleOrDefault(l => l.Name == connectionTitle);

                    _semaphore_AttributeQuery.Release();

                    if (definition == null)
                    {
                        definition = new ProductAttributeDefinition()
                        {
                            Id         = Guid.NewGuid(),
                            Name       = connectionTitle,
                            Attributes = new List <ProductAttribute>()
                        };
                        attributeDefinitons.Add(definition);
                    }

                    definition.Values = definition.Values ?? new List <ProductAttributeValue>();
                    var activeConnectionValue = connectionsValue.Single(l => l.IsEnabled);
                    var attributeValue        = definition.Values.SingleOrDefault(l => l.Value == activeConnectionValue.Value);

                    if (attributeValue == null)
                    {
                        attributeValue = new ProductAttributeValue()
                        {
                            Id = Guid.NewGuid(),
                            ProductAttributeDefinition = definition,
                            Value     = activeConnectionValue.Value,
                            Type      = CheckType(activeConnectionValue.Value),
                            Attribute = new List <ProductAttribute>()
                        };

                        definition.Values.Add(attributeValue);
                    }

                    var attributeInstance = new ProductAttribute()
                    {
                        Definition      = definition,
                        Value           = attributeValue,
                        IsConfiguration = true,
                    };

                    if (product.Attributes == null)
                    {
                        product.Attributes = new List <ProductAttribute>();
                    }

                    product.Attributes.Add(attributeInstance);
                    attributeValue.Attribute.Add(attributeInstance);
                    definition.Attributes.Add(attributeInstance);
                }
            }

            #endregion

            #region Attributes

            var specsContainerNode = document.DocumentNode.Descendants().SingleOrDefaultByNameNAttribute("div", "id", "specs-full") ??
                                     document.DocumentNode.Descendants().SingleByNameNAttribute("div", "id", "specs-short");

            var specsNode            = specsContainerNode.ChildNodes.SingleByNameNClass("dl", "stats");
            var specsDictionaryNodes =
                specsNode.ChildNodes.FindByName("dd").ToDictionary(l => l.PreviousSibling, l => l);

            foreach (var specNode in specsDictionaryNodes)
            {
                var title      = specNode.Key.InnerText.TrimStart().TrimEnd();
                var valueText  = specNode.Value.InnerText.TrimStart().TrimEnd().Replace("&nbsp;Read more", "");
                var valueClass = specNode.Value.ChildNodes.SingleOrDefaultByExcludeClass(new[] { "expand", "readmore", "collapsed" })?.Attributes["class"]?.Value ?? null;

                if (valueClass != null)
                {
                    switch (valueClass)
                    {
                    case "fi-x":
                        valueText = "False";
                        break;

                    case "fi-check":
                        valueText = "True";
                        break;

                    default:
                        //Debugger.Break();
                        break;
                    }
                }

                _semaphore_AttributeQuery.WaitOne();

                ProductAttributeDefinition definition =
                    attributeDefinitons.SingleOrDefault(l => l.Name == title);

                _semaphore_AttributeQuery.Release();

                if (definition == null)
                {
                    definition = new ProductAttributeDefinition()
                    {
                        Id         = Guid.NewGuid(),
                        Name       = title,
                        Attributes = new List <ProductAttribute>()
                    };
                    attributeDefinitons.Add(definition);
                }

                definition.Values = definition.Values ?? new List <ProductAttributeValue>();
                var attributeValue = definition.Values.SingleOrDefault(l => l.Value == valueText);

                if (attributeValue == null)
                {
                    attributeValue = new ProductAttributeValue()
                    {
                        Id = Guid.NewGuid(),
                        ProductAttributeDefinition = definition,
                        Value     = valueText,
                        Type      = CheckType(valueText),
                        Attribute = new List <ProductAttribute>()
                    };

                    definition.Values.Add(attributeValue);
                }

                if (product.Attributes == null)
                {
                    product.Attributes = new List <ProductAttribute>();
                }

                if (product.Attributes.All(l => l.Definition.Name != definition.Name))
                {
                    var attributeInstance = new ProductAttribute()
                    {
                        Definition      = definition,
                        Value           = attributeValue,
                        IsConfiguration = false,
                    };

                    product.Attributes.Add(attributeInstance);
                    attributeValue.Attribute.Add(attributeInstance);
                    definition.Attributes.Add(attributeInstance);
                }
            }

            #endregion

            #region ProductImages

            var imagesContainerNode = document.DocumentNode.Descendants().SingleOrDefaultByNameNClass("div", "vip-item-img-container");

            if (imagesContainerNode != null)
            {
                var imagesNodes = imagesContainerNode.Descendants().FindByNameNAttribute("img", "data-url");
                product.Hyperlinks = new List <Hyperlink>();

                foreach (var imageNode in imagesNodes)
                {
                    var imageUrl  = imageNode.Attributes["data-url"].Value;
                    var hyperlink = new Hyperlink()
                    {
                        Id  = Guid.NewGuid(),
                        Url = imageUrl
                    };
                    product.Hyperlinks.Add(hyperlink);
                }

                product.ImageUrl = product.Hyperlinks.FirstOrDefault()?.Url;
            }
            else
            {
                var imageContainerNode = document.DocumentNode.Descendants()
                                         .SingleByNameNContainClass("div", new[] { "vip-outofstock-item-img-container" });
                var imageNode = imageContainerNode.ChildNodes.SingleByName("img");
                product.ImageUrl = imageNode.Attributes["src"].Value;
            }

            #endregion

            #region Fulfiled

            var isFulfiledNode = document.DocumentNode.Descendants()
                                 .SingleOrDefaultByNameNContainAttribute("span", "data-toggle", "Fullfilled-tooltip");

            if (isFulfiledNode != null)
            {
                product.IsSouqFulfiled = true;
            }

            #endregion

            #region Shipping

            var isShippingFree = document.DocumentNode.Descendants()
                                 .SingleOrDefaultByNameNContainAttribute("a", "data-open", "freeShipping");

            if (isShippingFree != null)
            {
                product.IsFreeShipping = true;
            }

            #endregion
        }
        public IActionResult Put([FromBody] ProductRate body)
        {
            var entity = _manager.Update(body);

            return(ResponseJson(_manager.Update(entity)));
        }
        public IActionResult Post([FromBody] ProductRate body)
        {
            var entity = _manager.Add(body);

            return(ResponseJson(entity));
        }