Esempio n. 1
0
        public object GetVshopIndexProduct(long pid)
        {
            var productInfo = ServiceProvider.Instance <IProductService> .Create.GetProduct(pid);

            if (productInfo != null)
            {
                decimal discount   = 1M;
                long    SelfShopId = 0;
                var     CartInfo   = new Entities.ShoppingCartInfo();
                long    userId     = 0;
                if (CurrentUser != null)
                {
                    userId   = CurrentUser.Id;
                    discount = CurrentUser.MemberDiscount;
                    var shopInfo = ShopApplication.GetSelfShop();
                    SelfShopId = shopInfo.Id;
                    CartInfo   = ServiceProvider.Instance <ICartService> .Create.GetCart(CurrentUser.Id);
                }

                decimal MinSalePrice = 0M;
                long    activeId     = 0;
                int     activetype   = 0;
                var     limitBuy     = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetLimitTimeMarketItemByProductId(pid);

                if (limitBuy != null)
                {
                    MinSalePrice = limitBuy.MinPrice;
                    activeId     = limitBuy.Id;
                    activetype   = 1;
                }

                long stock = 0;
                var  skus  = ProductManagerApplication.GetSKUs(productInfo.Id);
                stock = skus.Sum(x => x.Stock);
                if (productInfo.MaxBuyCount > 0)
                {
                    stock = productInfo.MaxBuyCount;
                }
                if (productInfo.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                {
                    var ChoiceProducts = new
                    {
                        ProductId       = pid,
                        ProductName     = productInfo.ProductName,
                        SalePrice       = productInfo.MinSalePrice.ToString("0.##"),
                        ThumbnailUrl160 = productInfo.ImagePath,
                        MarketPrice     = productInfo.MarketPrice.ToString("0.##"),
                        HasSKU          = productInfo.HasSKU,
                        SkuId           = GetSkuIdByProductId(pid),
                        ActiveId        = activeId,
                        ActiveType      = activetype,//获取该商品是否参与活动
                        Stock           = stock,
                        IsVirtual       = productInfo.ProductType == 1
                    };
                    return(Json(ChoiceProducts));
                }
                return(ErrorResult <dynamic>("商品已下架!"));
            }
            return(ErrorResult <dynamic>("商品信息有误!"));
        }
Esempio n. 2
0
        /// <summary>
        /// 获取拼团项用于新增活动
        /// </summary>
        /// <param name="productId">商品编号</param>
        /// <returns></returns>
        public static FightGroupGetSkuListModel GetNewActiveItems(long productId)
        {
            FightGroupGetSkuListModel result = new FightGroupGetSkuListModel();
            var pro = GetService <IProductService>().GetProduct(productId);

            result.ProductImg = MallIO.GetProductSizeImage(pro.RelativePath, 1, (int)Mall.CommonModel.ImageSize.Size_150);
            result.skulist    = new List <FightGroupActiveItemModel>();
            var price = 0m;

            if (pro.IsOpenLadder)
            {
                var ladder = ProductManagerApplication.GetLadderPriceByProductIds(productId);
                if (ladder.Any())
                {
                    price = ladder.OrderBy(m => m.MinBath).FirstOrDefault().Price;
                }
            }
            var skus = ProductManagerApplication.GetSKUs(pro.Id);

            foreach (var item in skus)
            {
                FightGroupActiveItemModel data = new FightGroupActiveItemModel();
                data.ProductId    = productId;
                data.SkuId        = item.Id;
                data.SkuName      = item.Color + " " + item.Size + " " + item.Version;
                data.ProductPrice = price > 0 ? price : item.SalePrice;
                data.ProductStock = item.Stock;
                data.ActivePrice  = data.ProductPrice;
                data.ActiveStock  = 0; //活动库存置空
                result.skulist.Add(data);
            }
            return(result);
        }
Esempio n. 3
0
        public object GetProductSku(long pid)
        {
            CheckUserLogin();
            var sku = ProductManagerApplication.GetSKUs(pid);

            return(new { success = true, sku = sku });
        }
Esempio n. 4
0
        /// <summary>
        /// 商品列表信息项转换
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private product_list_model ProductInfoListMapChange(Entities.ProductInfo data)
        {
            product_list_model dresult = null;
            var prodata = data;

            dresult = new product_list_model();

            if (prodata == null)
            {
                throw new MallApiException(OpenApiErrorCode.Product_Not_Exists, "num_iid");
            }

            #region 装配信息
            dresult.num_iid    = (int)prodata.Id;
            dresult.outer_id   = prodata.ProductCode;
            dresult.brand_id   = (int)prodata.BrandId;
            dresult.brand_name = prodata.BrandName;
            dresult.cid        = (int)prodata.CategoryId;
            dresult.type_id    = (int)prodata.TypeId;

            var category = CategoryApplication.GetCategory(prodata.CategoryId);
            if (category != null)
            {
                dresult.cat_name = category.Name;
                var type = TypeApplication.GetType(category.TypeId);
                if (type != null)
                {
                    dresult.type_name = type.Name;
                }
            }
            dresult.price = prodata.MinSalePrice;
            var skus = ProductManagerApplication.GetSKUs(prodata.Id);
            if (skus.Count > 0)
            {
                dresult.num = (int)skus.Sum(d => d.Stock);
            }
            else
            {
                dresult.num = 0;
                dresult.num = prodata.Quantity;
            }
            dresult.title         = prodata.ProductName.Trim();
            dresult.list_time     = prodata.AddedDate;
            dresult.modified      = prodata.AddedDate;
            dresult.sold_quantity = (int)prodata.SaleCounts;
            dresult.pic_url       = new System.Collections.ArrayList();
            dresult.pic_url.Add(System.IO.Path.Combine(OpenAPIHelper.HostUrl, prodata.GetImage(ImageSize.Size_350, 1)));
            ProductStatus ps = GetProductStatus(prodata);
            dresult.approve_status = ps.ToString();
            #endregion

            return(dresult);
        }
Esempio n. 5
0
        /// <summary>
        /// 根据商品ID取门店sku信息
        /// </summary>
        /// <param name="shopBranchId"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static List <DTO.SKU> GetSkusByProductId(long shopBranchId, long pid)
        {
            var sku            = ProductManagerApplication.GetSKUs(pid);
            var shopBranchSkus = Service.GetSkusByIds(shopBranchId, sku.Select(e => e.Id).ToList());

            foreach (var item in sku)
            {
                var branchSku = shopBranchSkus.FirstOrDefault(e => e.SkuId == item.Id);
                if (branchSku != null)
                {
                    item.Stock = branchSku.Stock;
                }
            }
            return(sku);
        }
Esempio n. 6
0
        public JsonResult GetSKUInfo(long pId, long colloPid = 0)
        {
            var product = ServiceApplication.Create <IProductService>().GetProduct(pId);
            List <Mall.Entities.CollocationSkuInfo> collProduct = null;

            if (colloPid != 0)
            {
                collProduct = ServiceApplication.Create <ICollocationService>().GetProductColloSKU(pId, colloPid);
            }
            var skuArray = new List <ProductSKUModel>();
            var skus     = ProductManagerApplication.GetSKUs(product.Id);

            foreach (var sku in skus.Where(s => s.Stock > 0))
            {
                var price = sku.SalePrice;
                if (collProduct != null && collProduct.Count > 0)
                {
                    var collsku = collProduct.FirstOrDefault(a => a.SkuID == sku.Id);
                    if (collsku != null)
                    {
                        price = collsku.Price;
                    }
                }
                skuArray.Add(new ProductSKUModel
                {
                    Price = price,
                    SkuId = sku.Id,
                    Stock = sku.Stock
                });
            }
            //foreach (var item in skuArray)
            //{
            //    var str = item.SKUId.Split('_');
            //    item.SKUId = string.Format("{0};{1};{2}", str[1], str[2], str[3]);
            //}
            return(Json(new
            {
                skuArray = skuArray
            }));
        }
Esempio n. 7
0
        /// <summary>
        /// 拼团活动商品详情
        /// </summary>
        /// <param name="id">拼团活动ID</param>
        /// /// <param name="grouId">团活动ID</param>
        /// <returns></returns>
        public JsonResult <Result <dynamic> > GetActiveDetail(long id, long grouId = 0, bool isFirst = true, string ids = "")
        {
            var userList = new List <FightGroupOrderInfo>();
            var data     = FightGroupApplication.GetActive(id, true, true);
            FightGroupActiveModel result = data;

            //先初始化拼团商品主图
            result.InitProductImages();
            var imgpath = data.ProductImgPath;

            if (result != null)
            {
                result.IsEnd = true;
                if (data.EndTime.Date >= DateTime.Now.Date)
                {
                    result.IsEnd = false;
                }
                //商品图片地址修正
                result.ProductDefaultImage = HimallIO.GetRomoteProductSizeImage(imgpath, 1, (int)ImageSize.Size_350);
                result.ProductImgPath      = HimallIO.GetRomoteProductSizeImage(imgpath, 1);
            }
            if (result.ProductImages != null)
            {//将主图相对路径处理为绝对路径
                result.ProductImages = result.ProductImages.Select(e => HimallIO.GetRomoteImagePath(e)).ToList();
            }

            if (!string.IsNullOrWhiteSpace(result.IconUrl))
            {
                result.IconUrl = Himall.Core.HimallIO.GetRomoteImagePath(result.IconUrl);
            }
            bool IsUserEnter = false;
            long currentUser = 0;

            if (CurrentUser != null)
            {
                currentUser = CurrentUser.Id;
            }
            if (grouId > 0)//获取已参团的用户
            {
                userList = ServiceProvider.Instance <IFightGroupService> .Create.GetActiveUsers(id, grouId);

                foreach (var item in userList)
                {
                    item.Photo        = !string.IsNullOrWhiteSpace(item.Photo) ? Core.HimallIO.GetRomoteImagePath(item.Photo) : "";
                    item.HeadUserIcon = !string.IsNullOrWhiteSpace(item.HeadUserIcon) ? Core.HimallIO.GetRomoteImagePath(item.HeadUserIcon) : "";
                    if (currentUser.Equals(item.OrderUserId))
                    {
                        IsUserEnter = true;
                    }
                }
            }
            #region 商品规格
            var product = ProductManagerApplication.GetProduct((long)result.ProductId);

            ProductShowSkuInfoModel model = new ProductShowSkuInfoModel();
            model.MinSalePrice     = data.MiniSalePrice;
            model.ProductImagePath = string.IsNullOrWhiteSpace(imgpath) ? "" : HimallIO.GetRomoteProductSizeImage(imgpath, 1, (int)Himall.CommonModel.ImageSize.Size_350);

            List <SKUDataModel> skudata = data.ActiveItems.Where(d => d.ActiveStock > 0).Select(d => new SKUDataModel
            {
                SkuId     = d.SkuId,
                Color     = d.Color,
                Size      = d.Size,
                Version   = d.Version,
                Stock     = (int)d.ActiveStock,
                CostPrice = d.ProductCostPrice,
                SalePrice = d.ProductPrice,
                Price     = d.ActivePrice,
            }).ToList();

            Entities.TypeInfo typeInfo = ServiceProvider.Instance <ITypeService> .Create.GetType(product.TypeId);

            string colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;
            if (product != null)
            {
                colorAlias   = !string.IsNullOrWhiteSpace(product.ColorAlias) ? product.ColorAlias : colorAlias;
                sizeAlias    = !string.IsNullOrWhiteSpace(product.SizeAlias) ? product.SizeAlias : sizeAlias;
                versionAlias = !string.IsNullOrWhiteSpace(product.VersionAlias) ? product.VersionAlias : versionAlias;
            }
            model.ColorAlias   = colorAlias;
            model.SizeAlias    = sizeAlias;
            model.VersionAlias = versionAlias;

            if (result.ActiveItems != null && result.ActiveItems.Count() > 0)
            {
                long colorId = 0, sizeId = 0, versionId = 0;
                var  skus = ProductManagerApplication.GetSKUs((long)result.ProductId);
                foreach (var sku in result.ActiveItems)
                {
                    var specs = sku.SkuId.Split('_');
                    if (specs.Count() > 0 && !string.IsNullOrEmpty(sku.Color))
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }
                        if (colorId != 0)
                        {
                            if (!model.Color.Any(v => v.Value.Equals(sku.Color)))
                            {
                                var c = result.ActiveItems.Where(s => s.Color.Equals(sku.Color)).Sum(s => s.ActiveStock);
                                model.Color.Add(new ProductSKU
                                {
                                    //Name = "选择颜色",
                                    Name         = "选择" + colorAlias,
                                    EnabledClass = c != 0 ? " " : "disabled",
                                    //SelectedClass = !model.Color.Any(c1 => c1.SelectedClass.Equals("selected")) && c != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = colorId,
                                    Value         = sku.Color,
                                    Img           = string.IsNullOrWhiteSpace(sku.ShowPic) ? "" : Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                });
                            }
                        }
                    }
                    if (specs.Count() > 1 && !string.IsNullOrEmpty(sku.Size))
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!model.Size.Any(v => v.Value.Equals(sku.Size)))
                            {
                                var ss = result.ActiveItems.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.ActiveStock);
                                model.Size.Add(new ProductSKU
                                {
                                    //Name = "选择尺码",
                                    Name          = "选择" + sizeAlias,
                                    EnabledClass  = ss != 0 ? "enabled" : "disabled",
                                    SelectedClass = "",
                                    SkuId         = sizeId,
                                    Value         = sku.Size
                                });
                            }
                        }
                    }

                    if (specs.Count() > 2 && !string.IsNullOrEmpty(sku.Version))
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!model.Version.Any(v => v.Value.Equals(sku.Version)))
                            {
                                var v = result.ActiveItems.Where(s => s.Version.Equals(sku.Version)).Sum(s => s.ActiveStock);
                                model.Version.Add(new ProductSKU
                                {
                                    //Name = "选择规格",
                                    Name          = "选择" + versionAlias,
                                    EnabledClass  = v != 0 ? "enabled" : "disabled",
                                    SelectedClass = "",
                                    SkuId         = versionId,
                                    Value         = sku.Version
                                });
                            }
                        }
                    }
                }
            }
            #endregion

            var cashDepositModel = CashDepositsApplication.GetCashDepositsObligation((long)result.ProductId);//提供服务(消费者保障、七天无理由、及时发货)

            var GroupsData = new List <FightGroupsListModel>();
            List <FightGroupBuildStatus> stlist = new List <FightGroupBuildStatus>();
            stlist.Add(FightGroupBuildStatus.Ongoing);
            GroupsData = FightGroupApplication.GetGroups(id, stlist, null, null, 1, 10).Models.ToList();
            foreach (var item in GroupsData)
            {
                TimeSpan mid = item.AddGroupTime.AddHours((double)item.LimitedHour) - DateTime.Now;
                item.Seconds         = (int)mid.TotalSeconds;
                item.EndHourOrMinute = item.ShowHourOrMinute(item.GetEndHour);
                item.HeadUserIcon    = !string.IsNullOrWhiteSpace(item.HeadUserIcon) ? Core.HimallIO.GetRomoteImagePath(item.HeadUserIcon) : "";
            }

            #region 商品评论
            ProductCommentShowModel modelSay = new ProductCommentShowModel();
            modelSay.ProductId = (long)result.ProductId;
            var productSay = ProductManagerApplication.GetProduct((long)result.ProductId);
            modelSay.CommentList       = new List <ProductDetailCommentModel>();
            modelSay.IsShowColumnTitle = true;
            modelSay.IsShowCommentList = true;

            if (productSay == null)
            {
                //跳转到404页面
                throw new Core.HimallException("商品不存在");
            }
            var comments = CommentApplication.GetCommentsByProduct(product.Id);
            modelSay.CommentCount = comments.Count;
            if (comments.Count > 0)
            {
                var comment   = comments.OrderByDescending(a => a.ReviewDate).FirstOrDefault();
                var orderItem = OrderApplication.GetOrderItem(comment.SubOrderId);
                var order     = OrderApplication.GetOrder(orderItem.OrderId);
                modelSay.CommentList = comments.OrderByDescending(a => a.ReviewDate)
                                       .Take(1)
                                       .Select(c => {
                    var images = CommentApplication.GetProductCommentImagesByCommentIds(new List <long> {
                        c.Id
                    });
                    return(new ProductDetailCommentModel
                    {
                        Sku = ServiceProvider.Instance <IProductService> .Create.GetSkuString(orderItem.SkuId),
                        UserName = c.UserName,
                        ReviewContent = c.ReviewContent,
                        AppendContent = c.AppendContent,
                        AppendDate = c.AppendDate,
                        ReplyAppendContent = c.ReplyAppendContent,
                        ReplyAppendDate = c.ReplyAppendDate,
                        FinshDate = order.FinishDate,
                        Images = images.Where(a => a.CommentType == 0).Select(a => a.CommentImage).ToList(),
                        AppendImages = images.Where(a => a.CommentType == 1).Select(a => a.CommentImage).ToList(),
                        ReviewDate = c.ReviewDate,
                        ReplyContent = string.IsNullOrWhiteSpace(c.ReplyContent) ? "暂无回复" : c.ReplyContent,
                        ReplyDate = c.ReplyDate,
                        ReviewMark = c.ReviewMark,
                        BuyDate = order.OrderDate
                    });
                }).ToList();
                foreach (var citem in modelSay.CommentList)
                {
                    if (citem.Images.Count > 0)
                    {
                        for (var _imgn = 0; _imgn < citem.Images.Count; _imgn++)
                        {
                            citem.Images[_imgn] = Himall.Core.HimallIO.GetRomoteImagePath(citem.Images[_imgn]);
                        }
                    }
                    if (citem.AppendImages.Count > 0)
                    {
                        for (var _imgn = 0; _imgn < citem.AppendImages.Count; _imgn++)
                        {
                            citem.AppendImages[_imgn] = Himall.Core.HimallIO.GetRomoteImagePath(citem.AppendImages[_imgn]);
                        }
                    }
                }
            }
            #endregion

            #region 店铺信息
            VShopShowShopScoreModel modelShopScore = new VShopShowShopScoreModel();
            modelShopScore.ShopId = result.ShopId;
            var shop = ServiceProvider.Instance <IShopService> .Create.GetShop(result.ShopId);

            if (shop == null)
            {
                throw new HimallException("错误的店铺信息");
            }

            modelShopScore.ShopName = shop.ShopName;

            #region 获取店铺的评价统计
            var shopStatisticOrderComments = ServiceProvider.Instance <IShopService> .Create.GetShopStatisticOrderComments(result.ShopId);

            var productAndDescription = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescription).FirstOrDefault();
            var sellerServiceAttitude = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitude).FirstOrDefault();
            var sellerDeliverySpeed   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                         Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeed).FirstOrDefault();

            var productAndDescriptionPeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionPeer).FirstOrDefault();
            var sellerServiceAttitudePeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudePeer).FirstOrDefault();
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                             Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedPeer).FirstOrDefault();

            var productAndDescriptionMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMax).FirstOrDefault();
            var productAndDescriptionMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMin).FirstOrDefault();

            var sellerServiceAttitudeMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMax).FirstOrDefault();
            var sellerServiceAttitudeMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMin).FirstOrDefault();

            var sellerDeliverySpeedMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMax).FirstOrDefault();
            var sellerDeliverySpeedMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMin).FirstOrDefault();

            decimal defaultValue = 5;

            modelShopScore.SellerServiceAttitude     = defaultValue;
            modelShopScore.SellerServiceAttitudePeer = defaultValue;
            modelShopScore.SellerServiceAttitudeMax  = defaultValue;
            modelShopScore.SellerServiceAttitudeMin  = defaultValue;

            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null && !shop.IsSelf)
            {
                modelShopScore.ProductAndDescription     = productAndDescription.CommentValue;
                modelShopScore.ProductAndDescriptionPeer = productAndDescriptionPeer.CommentValue;
                modelShopScore.ProductAndDescriptionMin  = productAndDescriptionMin.CommentValue;
                modelShopScore.ProductAndDescriptionMax  = productAndDescriptionMax.CommentValue;
            }
            else
            {
                modelShopScore.ProductAndDescription     = defaultValue;
                modelShopScore.ProductAndDescriptionPeer = defaultValue;
                modelShopScore.ProductAndDescriptionMin  = defaultValue;
                modelShopScore.ProductAndDescriptionMax  = defaultValue;
            }

            //卖家服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null && !shop.IsSelf)
            {
                modelShopScore.SellerServiceAttitude     = sellerServiceAttitude.CommentValue;
                modelShopScore.SellerServiceAttitudePeer = sellerServiceAttitudePeer.CommentValue;
                modelShopScore.SellerServiceAttitudeMax  = sellerServiceAttitudeMax.CommentValue;
                modelShopScore.SellerServiceAttitudeMin  = sellerServiceAttitudeMin.CommentValue;
            }
            else
            {
                modelShopScore.SellerServiceAttitude     = defaultValue;
                modelShopScore.SellerServiceAttitudePeer = defaultValue;
                modelShopScore.SellerServiceAttitudeMax  = defaultValue;
                modelShopScore.SellerServiceAttitudeMin  = defaultValue;
            }
            //卖家发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null && !shop.IsSelf)
            {
                modelShopScore.SellerDeliverySpeed     = sellerDeliverySpeed.CommentValue;
                modelShopScore.SellerDeliverySpeedPeer = sellerDeliverySpeedPeer.CommentValue;
                modelShopScore.SellerDeliverySpeedMax  = sellerDeliverySpeedMax != null ? sellerDeliverySpeedMax.CommentValue : 0;
                modelShopScore.sellerDeliverySpeedMin  = sellerDeliverySpeedMin != null ? sellerDeliverySpeedMin.CommentValue : 0;
            }
            else
            {
                modelShopScore.SellerDeliverySpeed     = defaultValue;
                modelShopScore.SellerDeliverySpeedPeer = defaultValue;
                modelShopScore.SellerDeliverySpeedMax  = defaultValue;
                modelShopScore.sellerDeliverySpeedMin  = defaultValue;
            }
            #endregion

            modelShopScore.ProductNum = ServiceProvider.Instance <IProductService> .Create.GetShopOnsaleProducts(result.ShopId);

            modelShopScore.IsFavoriteShop    = false;
            modelShopScore.FavoriteShopCount = ServiceProvider.Instance <IShopService> .Create.GetShopFavoritesCount(result.ShopId);

            if (CurrentUser != null)
            {
                modelShopScore.IsFavoriteShop = ServiceProvider.Instance <IShopService> .Create.GetFavoriteShopInfos(CurrentUser.Id).Any(d => d.ShopId == result.ShopId);
            }

            long vShopId;
            var  vshopinfo = ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id);

            if (vshopinfo == null)
            {
                vShopId = -1;
            }
            else
            {
                vShopId = vshopinfo.Id;
            }
            modelShopScore.VShopId  = vShopId;
            modelShopScore.VShopLog = ServiceProvider.Instance <IVShopService> .Create.GetVShopLog(vShopId);

            if (!string.IsNullOrWhiteSpace(modelShopScore.VShopLog))
            {
                modelShopScore.VShopLog = Himall.Core.HimallIO.GetRomoteImagePath(modelShopScore.VShopLog);
            }

            // 客服
            var customerServices = CustomerServiceApplication.GetMobileCustomerServiceAndMQ(shop.Id);
            #endregion
            #region 根据运费模板获取发货地址
            var    freightTemplateService = ServiceApplication.Create <IFreightTemplateService>();
            var    template       = freightTemplateService.GetFreightTemplate(product.FreightTemplateId);
            string productAddress = string.Empty;
            if (template != null)
            {
                var fullName = ServiceApplication.Create <IRegionService>().GetFullName(template.SourceAddress);
                if (fullName != null)
                {
                    var ass = fullName.Split(' ');
                    if (ass.Length >= 2)
                    {
                        productAddress = ass[0] + " " + ass[1];
                    }
                    else
                    {
                        productAddress = ass[0];
                    }
                }
            }

            var ProductAddress  = productAddress;
            var FreightTemplate = template;
            #endregion

            #region 获取店铺优惠信息
            VShopShowPromotionModel modelVshop = new VShopShowPromotionModel();
            modelVshop.ShopId = result.ShopId;
            var shopInfo = ServiceProvider.Instance <IShopService> .Create.GetShop(result.ShopId);

            if (shopInfo == null)
            {
                throw new HimallException("错误的店铺编号");
            }

            modelVshop.FreeFreight = shop.FreeFreight;


            var bonus = ServiceApplication.Create <IShopBonusService>().GetByShopId(result.ShopId);
            if (bonus != null)
            {
                modelVshop.BonusCount             = bonus.Count;
                modelVshop.BonusGrantPrice        = bonus.GrantPrice;
                modelVshop.BonusRandomAmountStart = bonus.RandomAmountStart;
                modelVshop.BonusRandomAmountEnd   = bonus.RandomAmountEnd;
            }
            FullDiscountActive fullDiscount = null;
            //var fullDiscount = FullDiscountApplication.GetOngoingActiveByProductId(id, shop.Id);
            #endregion
            //商品描述

            var description = ProductManagerApplication.GetProductDescription(result.ProductId);
            if (description == null)
            {
                throw new HimallException("错误的商品编号");
            }

            string DescriptionPrefix = "", DescriptiondSuffix = "";
            var    iprodestempser = ServiceApplication.Create <IProductDescriptionTemplateService>();
            if (description.DescriptionPrefixId != 0)
            {
                var desc = iprodestempser.GetTemplate(description.DescriptionPrefixId, product.ShopId);
                DescriptionPrefix = desc == null ? "" : desc.MobileContent;
            }

            if (description.DescriptiondSuffixId != 0)
            {
                var desc = iprodestempser.GetTemplate(description.DescriptiondSuffixId, product.ShopId);
                DescriptiondSuffix = desc == null ? "" : desc.MobileContent;
            }
            var productDescription = DescriptionPrefix + description.ShowMobileDescription + DescriptiondSuffix;
            //统计商品浏览量、店铺浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);

            AutoMapper.Mapper.CreateMap <FightGroupActiveModel, FightGroupActiveResult>();
            var     fightGroupData = AutoMapper.Mapper.Map <FightGroupActiveResult>(result);
            decimal discount       = 1M;
            if (CurrentUser != null)
            {
                discount = CurrentUser.MemberDiscount;
            }
            var shopItem = ShopApplication.GetShop(result.ShopId);
            fightGroupData.MiniSalePrice = shopItem.IsSelf ? fightGroupData.MiniSalePrice * discount : fightGroupData.MiniSalePrice;

            string loadShowPrice = string.Empty;//app拼团详细页加载时显示的区间价
            loadShowPrice = fightGroupData.MiniSalePrice.ToString("f2");

            if (fightGroupData != null && fightGroupData.ActiveItems.Count() > 0)
            {
                decimal min = fightGroupData.ActiveItems.Min(s => s.ActivePrice);
                decimal max = fightGroupData.ActiveItems.Max(s => s.ActivePrice);
                loadShowPrice = (min < max) ? (min.ToString("f2") + " - " + max.ToString("f2")) : min.ToString("f2");
            }

            var _result = new
            {
                success        = true,
                FightGroupData = fightGroupData,
                ShowSkuInfo    = new
                {
                    ColorAlias       = model.ColorAlias,
                    SizeAlias        = model.SizeAlias,
                    VersionAlias     = model.VersionAlias,
                    MinSalePrice     = model.MinSalePrice,
                    ProductImagePath = model.ProductImagePath,
                    Color            = model.Color.OrderByDescending(p => p.SkuId),
                    Size             = model.Size.OrderByDescending(p => p.SkuId),
                    Version          = model.Version.OrderByDescending(p => p.SkuId)
                },
                ShowPromotion       = modelVshop,
                fullDiscount        = fullDiscount,
                ShowNewCanJoinGroup = GroupsData,
                ProductCommentShow  = modelSay,
                ProductDescription  = productDescription.Replace("src=\"/Storage/", "src=\"" + Core.HimallIO.GetRomoteImagePath("/Storage") + "/"),
                ShopScore           = modelShopScore,
                CashDepositsServer  = cashDepositModel,
                ProductAddress      = ProductAddress,
                //Free = FreightTemplate.IsFree == FreightTemplateType.Free ? "免运费" : "",
                userList              = userList,
                IsUserEnter           = IsUserEnter,
                SkuData               = skudata,
                CustomerServices      = customerServices,
                IsOpenLadder          = product.IsOpenLadder,
                VideoPath             = string.IsNullOrWhiteSpace(product.VideoPath) ? string.Empty : Himall.Core.HimallIO.GetRomoteImagePath(product.VideoPath),
                LoadShowPrice         = loadShowPrice,                                                                                                           //商品时区间价
                ProductSaleCountOnOff = (SiteSettingApplication.SiteSettings.ProductSaleCountOnOff == 1),                                                        //是否显示销量
                SaleCounts            = data.ActiveItems.Sum(d => d.BuyCount),                                                                                   //销量
                FreightStr            = FreightTemplateApplication.GetFreightStr(product.Id, FreightTemplate, CurrentUser, product),                             //运费多少或免运费
                SendTime              = (FreightTemplate != null && !string.IsNullOrEmpty(FreightTemplate.SendTime) ? (FreightTemplate.SendTime + "h内发货") : ""), //运费模板发货时间
            };
            return(JsonResult <dynamic>(_result));
        }
Esempio n. 8
0
        public object GetLimitBuyProduct(long id)
        {
            ProductDetailModelForMobie model = new ProductDetailModelForMobie()
            {
                Product = new ProductInfoModel(),
                Shop    = new ShopInfoModel(),
                Color   = new CollectionSKU(),
                Size    = new CollectionSKU(),
                Version = new CollectionSKU()
            };

            Entities.ProductInfo product = null;
            Entities.ShopInfo    shop    = null;
            FlashSaleModel       market  = null;

            market = ServiceProvider.Instance <ILimitTimeBuyService> .Create.Get(id);

            if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                //可能参数是商品ID
                market = market == null ? ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetFlaseSaleByProductId(id) : market;

                if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
                {
                    //跳转到404页面
                    throw new MallApiException("你所请求的限时购或者商品不存在!");
                }
            }

            if (market != null && (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing || DateTime.Parse(market.EndDate) < DateTime.Now))
            {
                return(new { success = true, IsValidLimitBuy = false });
            }

            model.MaxSaleCount = market.LimitCountOfThePeople;
            model.Title        = market.Title;

            product = ServiceProvider.Instance <IProductService> .Create.GetProduct(market.ProductId);

            bool hasSku = false;

            #region 商品SKU
            Entities.TypeInfo typeInfo = ServiceProvider.Instance <ITypeService> .Create.GetType(product.TypeId);

            string colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;
            if (product != null)
            {
                colorAlias   = !string.IsNullOrWhiteSpace(product.ColorAlias) ? product.ColorAlias : colorAlias;
                sizeAlias    = !string.IsNullOrWhiteSpace(product.SizeAlias) ? product.SizeAlias : sizeAlias;
                versionAlias = !string.IsNullOrWhiteSpace(product.VersionAlias) ? product.VersionAlias : versionAlias;
            }
            var skus = ProductManagerApplication.GetSKUs(product.Id);
            if (skus.Count > 0)
            {
                hasSku = true;
                long colorId = 0, sizeId = 0, versionId = 0;
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 0 && !string.IsNullOrEmpty(sku.Color))
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }
                        if (colorId != 0)
                        {
                            if (!model.Color.Any(v => v.Value == sku.Color))
                            {
                                var c = skus.Where(s => s.Color == sku.Color).Sum(s => s.Stock);
                                model.Color.Add(new ProductSKU
                                {
                                    //Name = "选择颜色" ,
                                    Name          = "选择" + colorAlias,
                                    EnabledClass  = c != 0 ? "enabled" : "disabled",
                                    SelectedClass = "",
                                    SkuId         = colorId,
                                    Value         = sku.Color,
                                    Img           = sku.ShowPic
                                });
                            }
                        }
                    }
                    if (specs.Count() > 1 && !string.IsNullOrEmpty(sku.Size))
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!model.Size.Any(v => v.Value.Equals(sku.Size)))
                            {
                                var ss = skus.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.Stock);
                                model.Size.Add(new ProductSKU
                                {
                                    //Name = "选择尺码" ,
                                    Name         = "选择" + sizeAlias,
                                    EnabledClass = ss != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Size.Any(s1 => s1.SelectedClass.Equals("selected")) && ss != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = sizeId,
                                    Value         = sku.Size
                                });
                            }
                        }
                    }

                    if (specs.Count() > 2 && !string.IsNullOrEmpty(sku.Version))
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!model.Version.Any(v => v.Value.Equals(sku.Version)))
                            {
                                var v = skus.Where(s => s.Version.Equals(sku.Version)).Sum(s => s.Stock);
                                model.Version.Add(new ProductSKU
                                {
                                    //Name = "选择版本" ,
                                    Name         = "选择" + versionAlias,
                                    EnabledClass = v != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Version.Any(v1 => v1.SelectedClass.Equals("selected")) && v != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = versionId,
                                    Value         = sku.Version
                                });
                            }
                        }
                    }
                }
            }
            #endregion

            #region 店铺
            shop = ServiceProvider.Instance <IShopService> .Create.GetShop(product.ShopId);

            var mark = Web.Framework.ShopServiceMark.GetShopComprehensiveMark(shop.Id);
            model.Shop.PackMark          = mark.PackMark;
            model.Shop.ServiceMark       = mark.ServiceMark;
            model.Shop.ComprehensiveMark = mark.ComprehensiveMark;
            model.Shop.Name        = shop.ShopName;
            model.Shop.ProductMark = CommentApplication.GetProductAverageMark(product.Id);
            model.Shop.Id          = product.ShopId;
            model.Shop.FreeFreight = shop.FreeFreight;
            model.Shop.ProductNum  = ServiceProvider.Instance <IProductService> .Create.GetShopOnsaleProducts(product.ShopId);


            var shopStatisticOrderComments = ServiceProvider.Instance <IShopService> .Create.GetShopStatisticOrderComments(product.ShopId);

            var productAndDescription = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescription);
            var sellerServiceAttitude = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitude);
            var sellerDeliverySpeed   = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeed);

            var productAndDescriptionPeer = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionPeer);
            var sellerServiceAttitudePeer = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudePeer);
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.FirstOrDefault(c => c.CommentKey == StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedPeer);



            decimal defaultValue = 5;
            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null)
            {
                model.Shop.ProductAndDescription = productAndDescription.CommentValue;
            }
            else
            {
                model.Shop.ProductAndDescription = defaultValue;
            }
            //卖家服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null)
            {
                model.Shop.SellerServiceAttitude = sellerServiceAttitude.CommentValue;
            }
            else
            {
                model.Shop.SellerServiceAttitude = defaultValue;
            }
            //卖家发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null)
            {
                model.Shop.SellerDeliverySpeed = sellerDeliverySpeed.CommentValue;
            }
            else
            {
                model.Shop.SellerDeliverySpeed = defaultValue;
            }
            if (ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id) == null)
            {
                model.Shop.VShopId = -1;
            }
            else
            {
                model.Shop.VShopId = ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id).Id;
            }

            //优惠券
            var result = GetCouponList(shop.Id);//取设置的优惠券
            if (result != null)
            {
                var couponCount = result.Count();
                model.Shop.CouponCount = couponCount;
            }
            #endregion

            #region 商品
            var consultations = ServiceProvider.Instance <IConsultationService> .Create.GetConsultations(product.Id);

            var  comments   = CommentApplication.GetCommentsByProduct(product.Id);
            var  total      = comments.Count;
            var  niceTotal  = comments.Count(item => item.ReviewMark >= 4);
            bool isFavorite = false;
            if (CurrentUser == null)
            {
                isFavorite = false;
            }
            else
            {
                isFavorite = ServiceProvider.Instance <IProductService> .Create.IsFavorite(product.Id, CurrentUser.Id);
            }
            var limitBuy = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetLimitTimeMarketItemByProductId(product.Id);

            var productImage = new List <string>();

            var env = EngineContext.Current.Resolve <IWebHostEnvironment>();

            for (int i = 1; i < 6; i++)
            {
                if (System.IO.File.Exists(env.ContentRootPath + product.RelativePath + string.Format("/{0}.png", i)))
                {
                    productImage.Add(Core.MallIO.GetRomoteImagePath(product.RelativePath + string.Format("/{0}.png", i)));
                }
            }
            var desc = ProductManagerApplication.GetProductDescription(product.Id);
            model.Product = new ProductInfoModel()
            {
                ProductId          = product.Id,
                CommentCount       = CommentApplication.GetCommentCountByProduct(product.Id),
                Consultations      = consultations.Count(),
                ImagePath          = productImage,
                IsFavorite         = isFavorite,
                MarketPrice        = market.MinPrice,
                MinSalePrice       = product.MinSalePrice,
                NicePercent        = model.Shop.ProductMark == 0 ? 100 : (int)((niceTotal / total) * 100),
                ProductName        = product.ProductName,
                ProductSaleStatus  = product.SaleStatus,
                AuditStatus        = product.AuditStatus,
                ShortDescription   = product.ShortDescription,
                ProductDescription = desc.ShowMobileDescription,
                MeasureUnit        = product.MeasureUnit,
                IsOnLimitBuy       = limitBuy != null,
                VideoPath          = string.IsNullOrWhiteSpace(product.VideoPath) ? string.Empty : Mall.Core.MallIO.GetRomoteImagePath(product.VideoPath),
            };
            #endregion

            LogProduct(market.ProductId);
            //统计商品浏览量、店铺浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);

            TimeSpan end    = new TimeSpan(DateTime.Parse(market.EndDate).Ticks);
            TimeSpan start  = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts     = end.Subtract(start);
            var      second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;

            return(new
            {
                success = true,
                IsOnLimitBuy = true,
                HasSku = hasSku,
                MaxSaleCount = market.LimitCountOfThePeople,
                Title = market.Title,
                Second = second,
                Product = model.Product,
                Shop = model.Shop,
                Color = model.Color.OrderBy(p => p.SkuId),
                Size = model.Size.OrderBy(p => p.SkuId),
                Version = model.Version.OrderBy(p => p.SkuId),
                ColorAlias = colorAlias,
                SizeAlias = sizeAlias,
                VersionAlias = versionAlias
            });
        }
Esempio n. 9
0
        // GET: Web/Search/SearchAd
        /// <summary>
        ///  商品搜索页面
        /// </summary>
        /// <param name="keywords">搜索关键字</param>
        /// <param name="cid">分类ID</param>
        /// <param name="b_id">品牌ID</param>
        /// <param name="a_id">属性ID, 表现形式:attrId_attrValueId</param>
        /// <param name="orderKey">序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间)</param>
        /// <param name="orderType">排序方式(1:升序,2:降序)</param>
        /// <param name="pageNo">页码</param>
        /// <param name="pageSize">每页显示数据量</param>
        /// <returns></returns>
        public ActionResult SearchAd(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性值ID, 表现形式:valueid,valueid */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 60  /*每页显示数据量*/
            )
        {
            try
            {
                var  siteSetingInfo = SiteSettingApplication.SiteSettings;
                bool isShow         = siteSetingInfo.ProductSaleCountOnOff == 1;
                if (string.IsNullOrEmpty(keywords) && cid <= 0 && b_id <= 0 && a_id == "")
                {
                    keywords = siteSetingInfo.Keyword;
                }

                #region 初始化查询Model
                SearchProductQuery model = new SearchProductQuery();
                model.ShopId  = 0;
                model.BrandId = b_id;
                if (cid != 0)
                {
                    var catelist = _iCategoryService.GetCategories();
                    var cate     = catelist.FirstOrDefault(r => r.Id == cid);
                    if (cate != null)
                    {
                        if (cate.Depth == 1)
                        {
                            model.FirstCateId = cid;
                        }
                        else if (cate.Depth == 2)
                        {
                            model.SecondCateId = cid;
                        }
                        else if (cate.Depth == 3)
                        {
                            model.ThirdCateId = cid;
                        }
                        ViewBag.pageTitle = cate.Name;
                    }
                }
                model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                model.Keyword    = keywords;
                model.OrderKey   = orderKey;
                model.OrderType  = orderType == 1;
                model.PageNumber = pageNo;
                model.PageSize   = pageSize;
                #endregion
                SearchProductResult result = _iSearchProductService.SearchProduct(model);
                int total = result.Total;

                //当查询的结果少于一页时用like进行补偿
                if (result.Total < pageSize)
                {
                    model.IsLikeSearch = true;
                    SearchProductResult result2 = _iSearchProductService.SearchProduct(model);
                    var idList1 = result.Data.Select(a => a.ProductId).ToList();
                    var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                    if (nresult.Count > 0)
                    {
                        result.Total += nresult.Count;
                        result.Data.AddRange(nresult);
                    }
                    //补充数据后,重新排序
                    Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderby     = null;
                    Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderByDesc = null;
                    switch (model.OrderKey)
                    {
                    case 2:
                        //order.Append(" ORDER BY SaleCount ");
                        orderby     = e => e.OrderBy(p => p.SaleCount + TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                        orderByDesc = e => e.OrderByDescending(p => p.SaleCount + TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                        break;

                    case 3:
                        //order.Append(" ORDER BY SalePrice ");
                        orderby     = e => e.OrderBy(p => p.SalePrice);
                        orderByDesc = e => e.OrderByDescending(p => p.SalePrice);
                        break;

                    case 4:
                        //order.Append(" ORDER BY Comments ");
                        orderby     = e => e.OrderBy(p => p.Comments);
                        orderByDesc = e => e.OrderByDescending(p => p.Comments);
                        break;

                    default:
                        //order.Append(" ORDER BY Id ");
                        //按最新的排序规则作为默认排序【序号越大,在前台展示的商品越靠前,序号一致时,优先销量排前,销量一致时,优先上架时间排前】
                        //orderby = e => e.OrderBy(p => p.ProductId);
                        if (isShow)
                        {    //底层已经将虚拟销量累加到销量中
                            orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.SaleCount).ThenByDescending(p => p.ProductId);
                        }
                        else
                        {
                            orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.ProductId);
                        }
                        break;
                    }
                    if (model.OrderKey > 1)
                    {
                        if (model.OrderType)
                        {
                            result.Data = orderby(result.Data).ToList();
                        }
                        else
                        {
                            result.Data = orderByDesc(result.Data).ToList();
                        }
                    }
                    else
                    {
                        result.Data = orderByDesc(result.Data).ToList();
                    }
                }
                if (result.Total == 0)
                {
                    ViewBag.BrowsedHistory = BrowseHistrory.GetBrowsingProducts(13, CurrentUser == null ? 0 : CurrentUser.Id);
                    var    category     = _iCategoryService.GetCategory(model.ThirdCateId);
                    string categoryName = category == null ? string.Empty : category.Name;
                    var    brand        = _iBrandService.GetBrand(b_id) ?? new Entities.BrandInfo();
                    string bname        = brand == null ? "" : brand.Name;
                    ViewBag.categoryName = categoryName;
                    ViewBag.bName        = bname;
                }
                total = result.Total;

                //补商品状态
                foreach (var item in result.Data)
                {
                    var _pro = _iProductService.GetProduct(item.ProductId);
                    var skus = ProductManagerApplication.GetSKUs(item.ProductId);
                    if (_pro == null || skus == null)
                    {
                        continue;
                    }
                    if (_pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale && _pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                    {
                        item.ShowStatus = 0;
                        if (skus.Sum(d => d.Stock) < 1)
                        {
                            item.ShowStatus = 2;
                        }
                    }
                    else
                    {
                        if (_pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && _pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.InStock)
                        {
                            item.ShowStatus = 3;
                        }
                        else
                        {
                            item.ShowStatus = 1;
                        }
                    }
                }

                if (Core.HimallIO.GetHimallIO().GetType().FullName.Equals("Himall.Strategy.OSS"))
                {
                    ViewBag.IsOss = true;
                }
                else
                {
                    ViewBag.IsOss = false;
                }

                ViewBag.keywords  = model.Keyword;
                ViewBag.cid       = cid;
                ViewBag.b_id      = b_id;
                ViewBag.a_id      = a_id;
                ViewBag.orderKey  = orderKey;
                ViewBag.orderType = orderType;

                #region 分页控制
                PagingInfo info = new PagingInfo
                {
                    CurrentPage  = model.PageNumber,
                    ItemsPerPage = pageSize,
                    TotalItems   = total
                };
                ViewBag.pageInfo = info;
                #endregion
                ViewBag.isSaleCountOnOff = isShow;

                return(View(result.Data));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Esempio n. 10
0
        public JsonResult GetShopBranchs(long shopId, long regionId, bool getParent, string[] skuIds, int[] counts, int page, int rows, long shippingAddressId)
        {
            var shippingAddressInfo = ShippingAddressApplication.GetUserShippingAddress(shippingAddressId);
            int streetId = 0, districtId = 0;//收货地址的街道、区域

            var query = new ShopBranchQuery()
            {
                ShopId   = shopId,
                PageNo   = page,
                PageSize = rows,
                Status   = ShopBranchStatus.Normal,
                ShopBranchProductStatus = ShopBranchSkuStatus.Normal
            };

            if (shippingAddressInfo != null)
            {
                query.FromLatLng = string.Format("{0},{1}", shippingAddressInfo.Latitude, shippingAddressInfo.Longitude); //需要收货地址的经纬度
                streetId         = shippingAddressInfo.RegionId;
                var parentAreaInfo = RegionApplication.GetRegion(shippingAddressInfo.RegionId, Region.RegionLevel.Town);  //判断当前区域是否为第四级
                if (parentAreaInfo != null && parentAreaInfo.ParentId > 0)
                {
                    districtId = parentAreaInfo.ParentId;
                }
                else
                {
                    districtId = streetId; streetId = 0;
                }
            }
            bool hasLatLng = false;

            if (!string.IsNullOrWhiteSpace(query.FromLatLng))
            {
                hasLatLng = query.FromLatLng.Split(',').Length == 2;
            }

            var region = RegionApplication.GetRegion(regionId, getParent ? Region.RegionLevel.City : Region.RegionLevel.County);

            if (region != null)
            {
                query.AddressPath = region.GetIdPath();
            }

            #region 旧排序规则
            //var skuInfos = ProductManagerApplication.GetSKUs(skuIds);

            //query.ProductIds = skuInfos.Select(p => p.ProductId).ToArray();
            //var data = ShopBranchApplication.GetShopBranchs(query);

            //var shopBranchSkus = ShopBranchApplication.GetSkus(shopId, data.Models.Select(p => p.Id));

            //var models = new
            //{
            //    Rows = data.Models.Select(sb => new
            //    {
            //        sb.ContactUser,
            //        sb.ContactPhone,
            //        sb.AddressDetail,
            //        sb.ShopBranchName,
            //        sb.Id,
            //        Enabled = skuInfos.All(skuInfo => shopBranchSkus.Any(sbSku => sbSku.ShopBranchId == sb.Id && sbSku.Stock >= counts[skuInfos.IndexOf(skuInfo)] && sbSku.SkuId == skuInfo.Id))
            //    }).OrderByDescending(p => p.Enabled).ToArray(),
            //    data.Total
            //};
            #endregion
            #region 3.0版本排序规则
            var skuInfos = ProductManagerApplication.GetSKUs(skuIds);
            query.ProductIds = skuInfos.Select(p => p.ProductId).ToArray();
            var data           = ShopBranchApplication.GetShopBranchsAll(query);
            var shopBranchSkus = ShopBranchApplication.GetSkus(shopId, data.Models.Select(p => p.Id).ToList());//获取该商家下具有订单内所有商品的门店状态正常数据,不考虑库存
            data.Models.ForEach(p =>
            {
                p.Enabled = skuInfos.All(skuInfo => shopBranchSkus.Any(sbSku => sbSku.ShopBranchId == p.Id && sbSku.Stock >= counts[skuInfos.IndexOf(skuInfo)] && sbSku.SkuId == skuInfo.Id));
            });

            List <ShopBranch> newList    = new List <ShopBranch>();
            List <long>       fillterIds = new List <long>();
            var currentList = data.Models.Where(p => hasLatLng && p.Enabled && (p.Latitude > 0 && p.Longitude > 0)).OrderBy(p => p.Distance).ToList();
            if (currentList != null && currentList.Count() > 0)
            {
                fillterIds.AddRange(currentList.Select(p => p.Id));
                newList.AddRange(currentList);
            }
            var currentList2 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains(CommonConst.ADDRESS_PATH_SPLIT + streetId + CommonConst.ADDRESS_PATH_SPLIT)).ToList();
            if (currentList2 != null && currentList2.Count() > 0)
            {
                fillterIds.AddRange(currentList2.Select(p => p.Id));
                newList.AddRange(currentList2);
            }
            var currentList3 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains(CommonConst.ADDRESS_PATH_SPLIT + districtId + CommonConst.ADDRESS_PATH_SPLIT)).ToList();
            if (currentList3 != null && currentList3.Count() > 0)
            {
                fillterIds.AddRange(currentList3.Select(p => p.Id));
                newList.AddRange(currentList3);
            }
            var currentList4 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled).ToList();//非同街、非同区,但一定会同市
            if (currentList4 != null && currentList4.Count() > 0)
            {
                fillterIds.AddRange(currentList4.Select(p => p.Id));
                newList.AddRange(currentList4);
            }
            var currentList5 = data.Models.Where(p => !fillterIds.Contains(p.Id)).ToList();//库存不足的排最后
            if (currentList5 != null && currentList5.Count() > 0)
            {
                newList.AddRange(currentList5);
            }
            if (newList.Count() != data.Models.Count())//如果新组合的数据与原数据数量不一致,则异常
            {
                return(Json <dynamic>(true, data: new { Rows = "" }, camelCase: true));
            }
            var needDistance = false;
            if (shippingAddressInfo != null && shippingAddressInfo.Latitude != 0 && shippingAddressInfo.Longitude != 0)
            {
                needDistance = true;
            }
            var models = new
            {
                Rows = newList.Select(sb => new
                {
                    sb.ContactUser,
                    sb.ContactPhone,
                    sb.AddressDetail,
                    sb.ShopBranchName,
                    sb.Id,
                    Enabled  = sb.Enabled,
                    Distance = needDistance ? RegionApplication.GetDistance(sb.Latitude, sb.Longitude, shippingAddressInfo.Latitude, shippingAddressInfo.Longitude) : 0
                }).ToArray(),
                Total = newList.Count
            };
            #endregion
            return(SuccessResult <dynamic>(data: models, camelCase: true));
        }
Esempio n. 11
0
        /// <summary>
        /// 查询商品
        /// </summary>
        /// <param name="timeStamp"></param>
        /// <param name="uCode"></param>
        /// <param name="mType"></param>
        /// <param name="Sign"></param>
        /// <param name="PageSize"></param>
        /// <param name="Page"></param>
        /// <param name="GoodsType"></param>
        /// <param name="OuterID"></param>
        /// <param name="GoodsName"></param>
        /// <returns></returns>
        public string findProduct(HttpContext context)
        {
            string uCode     = context.Request["uCode"];
            string PageSize  = context.Request["PageSize"];
            string Page      = context.Request["Page"];
            string GoodsType = context.Request["GoodsType"];
            string OuterID   = context.Request["OuterID"];
            string GoodsName = context.Request["GoodsName"];


            ProductQuery query      = new ProductQuery();
            int          page_size  = 0;
            int          page_index = 0;

            if (!string.IsNullOrEmpty(PageSize))
            {
                page_size = Convert.ToInt32(PageSize);
            }
            if (!string.IsNullOrEmpty(Page))
            {
                page_index = Convert.ToInt32(Page);
            }
            string type = null;
            string code = null;
            string name = null;

            Entities.ProductInfo.ProductSaleStatus status = new Entities.ProductInfo.ProductSaleStatus();
            if (!string.IsNullOrWhiteSpace(GoodsType)) //按类型
            {
                type = GoodsType;                      //1在售 2下架
                if (type.Equals("OnSale"))
                {
                    status = Entities.ProductInfo.ProductSaleStatus.OnSale;
                }
                else if (type.Equals("InStock"))
                {
                    status = Entities.ProductInfo.ProductSaleStatus.InStock;
                }
            }
            else if (!string.IsNullOrWhiteSpace(OuterID))//按商家编码
            {
                code = OuterID;
            }
            else if (!string.IsNullOrWhiteSpace(GoodsName))//按商品名称
            {
                name = GoodsName;
            }
            query.PageSize    = page_size;
            query.PageNo      = page_index;
            query.SaleStatus  = status;
            query.KeyWords    = name;
            query.ProductCode = code;
            query.ShopId      = 1;
            if (ServiceApplication.Create <IShopService>().GetshopInfoByCode(uCode) != null)
            {
                query.ShopId = ServiceApplication.Create <IShopService>().GetshopInfoByCode(uCode).ShopId; //根据uCode获取店铺信息
            }
            var           products = ProductManagerApplication.GetProducts(query);
            StringBuilder sb       = new StringBuilder();

            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            try
            {
                sb.Append("<Goods>");
                foreach (var item in products.Models)
                {
                    sb.Append("<Ware>");

                    bool hasSku = ProductManagerApplication.HasSKU(item.Id);

                    int isSku = hasSku ? 1 : 0;
                    sb.Append(string.Format("<ItemID><![CDATA[{0}]]></ItemID>", item.Id));
                    sb.Append(string.Format("<ItemName><![CDATA[{0}]]></ItemName>", item.ProductName));
                    sb.Append(string.Format("<OuterID><![CDATA[{0}]]></OuterID>", item.ProductCode));
                    sb.Append(string.Format("<Price><![CDATA[{0}]]></Price>", item.MinSalePrice));
                    sb.Append(string.Format("<IsSku><![CDATA[{0}]]></IsSku>", isSku));
                    var skus = ProductManagerApplication.GetSKUs(item.Id);
                    sb.Append(string.Format("<Num><![CDATA[{0}]]></Num>", skus.Sum(d => d.Stock)));//总数
                    sb.Append("<Items>");
                    if (hasSku)
                    {
                        foreach (var sku in skus)
                        {
                            sb.Append("<Item>");
                            sb.Append(string.Format("<Unit><![CDATA[{0}]]></Unit>", sku.Color + " " + sku.Size + " " + sku.Version));
                            sb.Append(string.Format("<SkuOuterID><![CDATA[{0}]]></SkuOuterID>", sku.Sku));
                            sb.Append(string.Format("<SkuID><![CDATA[{0}]]></SkuID>", sku.Id));
                            sb.Append(string.Format("<Num><![CDATA[{0}]]></Num>", sku.Stock));
                            sb.Append(string.Format("<SkuPrice><![CDATA[{0}]]></SkuPrice>", sku.SalePrice));
                            sb.Append("</Item>");
                        }
                    }
                    sb.Append("</Items>");
                    sb.Append("</Ware>");
                }
                sb.Append("<Result>1</Result>");
                sb.Append(string.Format("<TotalCount>{0}</TotalCount>", products.Total));
                sb.Append("<Cause></Cause>");
                sb.Append("</Goods>");
            }
            catch (Exception ex)
            {
                sb.Clear();
                sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                sb.Append("<Rsp><Result>0</Result><Cause>" + ex.Message + "</Cause></Rsp>");
            }
            return(sb.ToString());
        }
Esempio n. 12
0
        /// <summary>
        /// 首页商品信息
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public JsonResult <Result <List <dynamic> > > GetIndexProductData(string openId = "", int pageIndex = 1, int pageSize = 10)
        {
            var homeProducts = ServiceProvider.Instance <IWXSmallProgramService> .Create.GetWXSmallHomeProducts(pageIndex, pageSize);

            decimal discount    = 1M;
            long    SelfShopId  = 0;
            var     CartInfo    = new Himall.Entities.ShoppingCartInfo();
            var     ids         = homeProducts.Models.Select(p => p.Id).ToList();
            var     productList = new List <dynamic>();
            var     cartitems   = new List <Himall.Entities.ShoppingCartItem>();
            long    userId      = 0;

            if (CurrentUser != null)
            {
                userId   = CurrentUser.Id;
                discount = CurrentUser.MemberDiscount;
                var shopInfo = ShopApplication.GetSelfShop();
                SelfShopId = shopInfo.Id;
                CartInfo   = ServiceProvider.Instance <ICartService> .Create.GetCart(CurrentUser.Id);

                cartitems = CartApplication.GetCartQuantityByIds(CurrentUser.Id, ids);
            }

            foreach (var item in homeProducts.Models)
            {
                long activeId   = 0;
                int  activetype = 0;
                item.ImagePath = Core.HimallIO.GetRomoteProductSizeImage(Core.HimallIO.GetImagePath(item.ImagePath), 1, (int)Himall.CommonModel.ImageSize.Size_350);
                if (item.ShopId == SelfShopId)
                {
                    item.MinSalePrice = item.MinSalePrice * discount;
                }
                var limitBuy = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetLimitTimeMarketItemByProductId(item.Id);

                if (limitBuy != null)
                {
                    item.MinSalePrice = limitBuy.MinPrice;
                    activeId          = limitBuy.Id;
                    activetype        = 1;
                }
                int quantity = 0;
                quantity = cartitems.Where(d => d.ProductId == item.Id).Sum(d => d.Quantity);

                long stock = 0;

                var productInfo = ServiceProvider.Instance <IProductService> .Create.GetProduct(item.Id);

                if (productInfo != null)
                {
                    var skus = ProductManagerApplication.GetSKUs(productInfo.Id);
                    stock = skus.Sum(x => x.Stock);
                    if (productInfo.MaxBuyCount > 0)
                    {
                        stock = productInfo.MaxBuyCount;
                    }
                }
                if (productInfo.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                {
                    var ChoiceProducts = new
                    {
                        ProductId       = item.Id,
                        ProductName     = item.ProductName,
                        SalePrice       = item.MinSalePrice.ToString("0.##"),
                        ThumbnailUrl160 = item.ImagePath,
                        MarketPrice     = item.MarketPrice.ToString("0.##"),
                        CartQuantity    = quantity,
                        HasSKU          = item.HasSKU,
                        SkuId           = GetSkuIdByProductId(item.Id),
                        ActiveId        = activeId,
                        ActiveType      = activetype,//获取该商品是否参与活动
                        Stock           = stock,
                        IsVirtual       = item.ProductType == 1
                    };
                    productList.Add(ChoiceProducts);
                }
            }
            return(JsonResult(productList));
        }
Esempio n. 13
0
        public object GetSearchProducts(
            string keywords = "", /* 搜索关键字 */
            long cid        = 0,  /* 分类ID */
            long b_id       = 0,  /* 品牌ID */
            string a_id     = "", /* 属性ID, 表现形式:attrId_attrValueId */
            int orderKey    = 1,  /* 排序项(1:默认,2:销量,3:价格,4:评论数,5:上架时间) */
            int orderType   = 1,  /* 排序方式(1:升序,2:降序) */
            int pageNo      = 1,  /*页码*/
            int pageSize    = 10, /*每页显示数据量*/
            long vshopId    = 0,
            long sid        = 0   /*商家ID*/
            )
        {
            var  siteSetingInfo = SiteSettingApplication.SiteSettings;
            bool isShow         = siteSetingInfo.ProductSaleCountOnOff == 1;

            if (string.IsNullOrEmpty(keywords) && vshopId == 0 && cid <= 0 && b_id <= 0 && a_id == "")
            {
                keywords = siteSetingInfo.Keyword;
            }
            #region 初始化查询Model
            SearchProductQuery model = new SearchProductQuery();
            model.VShopId = vshopId;
            model.ShopId  = sid;
            model.BrandId = b_id;
            if (vshopId == 0 && cid != 0)
            {
                var catelist = ServiceProvider.Instance <ICategoryService> .Create.GetCategories();

                var cate = catelist.FirstOrDefault(r => r.Id == cid);
                if (cate != null)
                {
                    if (cate.Depth == 1)
                    {
                        model.FirstCateId = cid;
                    }
                    else if (cate.Depth == 2)
                    {
                        model.SecondCateId = cid;
                    }
                    else if (cate.Depth == 3)
                    {
                        model.ThirdCateId = cid;
                    }
                }
            }
            else if (vshopId != 0 && cid != 0)
            {
                model.ShopCategoryId = cid;
            }
            model.AttrValIds = a_id.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            model.Keyword    = keywords;
            model.OrderKey   = orderKey;
            model.OrderType  = orderType == 1;
            model.PageNumber = pageNo;
            model.PageSize   = pageSize;
            #endregion
            SearchProductResult result = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

            int total = result.Total;
            //当查询的结果少于一页时用like进行补偿(与PC端同步)
            if (result.Total < pageSize)
            {
                model.IsLikeSearch = true;
                SearchProductResult result2 = ServiceProvider.Instance <ISearchProductService> .Create.SearchProduct(model);

                var idList1 = result.Data.Select(a => a.ProductId).ToList();
                var nresult = result2.Data.Where(a => !idList1.Contains(a.ProductId)).ToList();
                if (nresult.Count > 0)
                {
                    result.Total += nresult.Count;
                    result.Data.AddRange(nresult);
                }
                //补充数据后,重新排序
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderby     = null;
                Func <IEnumerable <ProductView>, IOrderedEnumerable <ProductView> > orderByDesc = null;
                switch (model.OrderKey)
                {
                case 2:
                    //order.Append(" ORDER BY SaleCount ");
                    orderby     = e => e.OrderBy(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    orderByDesc = e => e.OrderByDescending(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts));
                    break;

                case 3:
                    //order.Append(" ORDER BY SalePrice ");
                    orderby     = e => e.OrderBy(p => p.SalePrice);
                    orderByDesc = e => e.OrderByDescending(p => p.SalePrice);
                    break;

                case 4:
                    //order.Append(" ORDER BY Comments ");
                    orderby     = e => e.OrderBy(p => p.Comments);
                    orderByDesc = e => e.OrderByDescending(p => p.Comments);
                    break;

                default:
                    //order.Append(" ORDER BY Id ");
                    //orderby = e => e.OrderBy(p => p.ProductId);
                    //orderByDesc = e => e.OrderByDescending(p => p.ProductId);
                    //break;
                    //按最新的排序规则作为默认排序【序号越大,在前台展示的商品越靠前,序号一致时,优先销量排前,销量一致时,优先上架时间排前】
                    if (isShow)
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.SaleCount + Himall.Core.Helper.TypeHelper.ObjectToInt(p.VirtualSaleCounts)).ThenByDescending(p => p.ProductId);
                    }
                    else
                    {
                        orderByDesc = e => e.OrderByDescending(p => p.DisplaySequence).ThenByDescending(p => p.ProductId);
                    }
                    break;
                }
                if (model.OrderKey > 1)
                {
                    if (model.OrderType)
                    {
                        result.Data = orderby(result.Data).ToList();
                    }
                    else
                    {
                        result.Data = orderByDesc(result.Data).ToList();
                    }
                }
                else
                {
                    result.Data = orderByDesc(result.Data).ToList();
                }
            }
            total = result.Total;

            //补商品状态
            foreach (var item in result.Data)
            {
                var pro = ServiceProvider.Instance <IProductService> .Create.GetProduct(item.ProductId);

                var skus = ProductManagerApplication.GetSKUs(pro.Id);
                if (pro == null || skus == null)
                {
                    continue;
                }
                if (pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale && pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited)
                {
                    item.ShowStatus = 0;
                    if (skus.Sum(d => d.Stock) < 1)
                    {
                        item.ShowStatus = 2;
                    }
                }
                else
                {
                    if (pro.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && pro.SaleStatus == Entities.ProductInfo.ProductSaleStatus.InStock)
                    {
                        item.ShowStatus = 3;
                    }
                    else
                    {
                        item.ShowStatus = 1;
                    }
                }
            }
            #region 价格更新
            //会员折扣
            //decimal discount = 1M;
            //long SelfShopId = 0;
            //if (CurrentUser != null)
            //{
            //    discount = CurrentUser.MemberDiscount;
            //    var shopInfo = ShopApplication.GetSelfShop();
            //    SelfShopId = shopInfo.Id;
            //}

            //var limit = LimitTimeApplication.GetLimitProducts();
            var fight = FightGroupApplication.GetFightGroupPrice();

            foreach (var item in result.Data)
            {
                item.ImagePath = Core.HimallIO.GetRomoteProductSizeImage(Core.HimallIO.GetImagePath(item.ImagePath), 1, (int)Himall.CommonModel.ImageSize.Size_350);
                //if (item.ShopId == SelfShopId)
                //    item.SalePrice = item.SalePrice * discount;
                //var isLimit = limit.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                var isFight = fight.Where(r => r.ProductId == item.ProductId).FirstOrDefault();
                //if (isLimit != null)
                //    item.SalePrice = isLimit.MinPrice;
                if (isFight != null)
                {
                    //item.SalePrice = isFight.ActivePrice;
                    item.FightGroupId = isFight.ActiveId;
                }
            }
            #endregion

            return(new
            {
                success = true,
                Product = result.Data,
                total = total,
                keywords = model.Keyword,
                cid = cid,
                b_id = b_id,
                a_id = a_id,
                orderKey = orderKey,
                orderType = orderType,
                isSaleCountOnOff = isShow
            });
        }
Esempio n. 14
0
        /// <summary>
        /// 加载门店编辑商品列表
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="shopbranchId"></param>
        /// <returns></returns>
        public JsonResult GetProductsByIds(string ids, long shopbranchId)
        {
            if (string.IsNullOrWhiteSpace(ids))
            {
                return(Json(new { success = false, msg = "参数传递错误" }));
            }

            var pIds     = ConvertToIEnumerable(ids);
            var products = ProductManagerApplication.GetAllProductByIds(pIds);

            //查询门店SKU库存
            var           allSKU         = ProductManagerApplication.GetSKUByProducts(products.Select(p => p.Id));
            List <string> skuids         = allSKU.Select(p => p.Id).ToList();
            var           shopBranchSkus = ShopBranchApplication.GetSkusByIds(shopbranchId, skuids);

            List <ProductModel> productlist = new List <ProductModel>();

            foreach (var item in products)
            {
                var          skus    = ProductManagerApplication.GetSKUs(item.Id);
                ProductModel product = new ProductModel()
                {
                    Name  = item.ProductName,
                    Id    = item.Id,
                    Image = item.GetImage(ImageSize.Size_50),
                    Price = item.MinSalePrice
                };
                List <SKuModel> skulist = new List <SKuModel>();
                foreach (var skuInfo in skus)
                {
                    var shopbranckSku = shopBranchSkus.Where(s => s.SkuId == skuInfo.Id).FirstOrDefault();
                    var str           = string.Empty;
                    if (!string.IsNullOrWhiteSpace(skuInfo.Color))
                    {
                        str += item.ColorAlias + ":" + skuInfo.Color;
                    }
                    else
                    {
                        str += " " + item.ColorAlias + ";";
                    }
                    if (!string.IsNullOrWhiteSpace(skuInfo.Size))
                    {
                        str += " " + item.SizeAlias + ":" + skuInfo.Size;
                    }
                    else
                    {
                        str += " " + item.SizeAlias + ";";
                    }
                    if (!string.IsNullOrWhiteSpace(skuInfo.Version))
                    {
                        str += " " + item.VersionAlias + ":" + skuInfo.Version;
                    }
                    else
                    {
                        str += " " + item.VersionAlias + ";";
                    }
                    var model = new SKuModel()
                    {
                        ProductName = (item.HasSKU ? str.TrimEnd(';') : ""),
                        Sku         = item.HasSKU ? (skuInfo.Sku ?? string.Empty) : item.ProductCode,
                        Id          = skuInfo.Id,
                        AutoId      = shopbranckSku.Id,
                        Stock       = shopbranckSku.Stock,
                        MarketPrice = item.MarketPrice,
                        SalePrice   = item.HasSKU ? skuInfo.SalePrice : item.MinSalePrice,//有规格则取规格商城价,否则取商品本身商城价
                        ProductId   = item.Id,
                        HasSKU      = item.HasSKU ? 1 : 0
                    };
                    if (skus.IndexOf(skuInfo) == 0)
                    {
                        model.IsFirst = 1;
                    }
                    skulist.Add(model);
                }
                product.Skus = skulist;
                productlist.Add(product);
            }
            return(Json(new
            {
                success = true,
                model = productlist
            }));
        }
Esempio n. 15
0
        ///// <summary>
        ///// 获取限时抢购商品详情
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        public JsonResult <Result <dynamic> > GetLimitBuyProduct(string openId, long countDownId)
        {
            //CheckUserLogin();
            ProductDetailModelForMobie model = new ProductDetailModelForMobie()
            {
                Product = new ProductInfoModel(),
                Shop    = new ShopInfoModel(),
                Color   = new CollectionSKU(),
                Size    = new CollectionSKU(),
                Version = new CollectionSKU()
            };

            Entities.ShopInfo shop   = null;
            FlashSaleModel    market = null;

            market = ServiceProvider.Instance <ILimitTimeBuyService> .Create.Get(countDownId);


            if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                //可能参数是商品ID
                market = market == null ? ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetFlaseSaleByProductId(countDownId) : market;

                if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
                {
                    //跳转到404页面
                    return(Json(ErrorResult <dynamic>("你所请求的限时购或者商品不存在!")));
                }
            }

            if (market != null && (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing || DateTime.Parse(market.EndDate) < DateTime.Now))
            {
                return(JsonResult <dynamic>(new { IsValidLimitBuy = false }));
            }

            model.MaxSaleCount = market.LimitCountOfThePeople;
            model.Title        = market.Title;

            var product = ServiceProvider.Instance <IProductService> .Create.GetProduct(market.ProductId);

            var description = ProductManagerApplication.GetProductDescription(product.Id);


            #region 根据运费模板获取发货地址
            var freightTemplateService = ServiceApplication.Create <IFreightTemplateService>();
            var template = freightTemplateService.GetFreightTemplate(product.FreightTemplateId);
            //string productAddress = string.Empty;
            //if (template != null)
            //{
            //    var fullName = ServiceApplication.Create<IRegionService>().GetFullName(template.SourceAddress);
            //    if (fullName != null)
            //    {
            //        var ass = fullName.Split(' ');
            //        if (ass.Length >= 2)
            //        {
            //            productAddress = ass[0] + " " + ass[1];
            //        }
            //        else
            //        {
            //            productAddress = ass[0];
            //        }
            //    }
            //}

            //model.ProductAddress = productAddress;
            model.FreightTemplate = template;
            #endregion

            #region 商品SKU
            Entities.TypeInfo typeInfo = ServiceProvider.Instance <ITypeService> .Create.GetType(product.TypeId);

            string colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;


            List <object> SkuItemList = new List <object>();
            List <object> Skus        = new List <object>();
            var           skus        = ProductManagerApplication.GetSKUs(product.Id);

            if (skus.Count > 0)
            {
                #region 颜色
                long          colorId = 0, sizeId = 0, versionId = 0;
                List <object> colorAttributeValue = new List <object>();
                List <string> listcolor           = new List <string>();
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 0 && !string.IsNullOrEmpty(sku.Color))
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }                                            //相同颜色规格累加对应值
                        if (colorId != 0)
                        {
                            if (!listcolor.Contains(sku.Color))
                            {
                                var c          = skus.Where(s => s.Color.Equals(sku.Color)).Sum(s => s.Stock);
                                var colorvalue = new
                                {
                                    ValueId           = colorId,
                                    UseAttributeImage = "False",
                                    Value             = sku.Color,
                                    ImageUrl          = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listcolor.Add(sku.Color);
                                colorAttributeValue.Add(colorvalue);
                            }
                        }
                    }
                }

                var color = new
                {
                    AttributeName  = !string.IsNullOrWhiteSpace(product.ColorAlias) ? product.ColorAlias : colorAlias,//如果商品有自定义规格名称则用
                    AttributeId    = product.TypeId,
                    AttributeValue = colorAttributeValue,
                    AttributeIndex = 0,
                };
                if (colorId > 0)
                {
                    SkuItemList.Add(color);
                }
                #endregion

                #region 容量
                List <object> sizeAttributeValue = new List <object>();
                List <string> listsize           = new List <string>();
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 1)
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!listsize.Contains(sku.Size))
                            {
                                var ss        = skus.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.Stock);
                                var sizeValue = new
                                {
                                    ValueId           = sizeId,
                                    UseAttributeImage = false,
                                    Value             = sku.Size,
                                    //ImageUrl = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listsize.Add(sku.Size);
                                sizeAttributeValue.Add(sizeValue);
                            }
                        }
                    }
                }

                var size = new
                {
                    AttributeName  = !string.IsNullOrWhiteSpace(product.SizeAlias) ? product.SizeAlias : sizeAlias,
                    AttributeId    = product.TypeId,
                    AttributeValue = sizeAttributeValue,
                    AttributeIndex = 1,
                };
                if (sizeId > 0)
                {
                    SkuItemList.Add(size);
                }

                #endregion

                #region 规格
                List <object> versionAttributeValue = new List <object>();
                List <string> listversion           = new List <string>();
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 2)
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!listversion.Contains(sku.Version))
                            {
                                var v            = skus.Where(s => s.Version.Equals(sku.Version));
                                var versionValue = new
                                {
                                    ValueId           = versionId,
                                    UseAttributeImage = false,
                                    Value             = sku.Version,
                                    //ImageUrl = Himall.Core.HimallIO.GetRomoteImagePath(sku.ShowPic)
                                };
                                listversion.Add(sku.Version);
                                versionAttributeValue.Add(versionValue);
                            }
                        }
                    }
                }

                var version = new
                {
                    AttributeName  = !string.IsNullOrWhiteSpace(product.VersionAlias) ? product.VersionAlias : versionAlias,
                    AttributeId    = product.TypeId,
                    AttributeValue = versionAttributeValue,
                    AttributeIndex = 2,
                };
                if (versionId > 0)
                {
                    SkuItemList.Add(version);
                }
                #endregion

                #region Sku值

                foreach (var sku in skus)
                {
                    FlashSaleDetailInfo detailInfo = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetDetail(sku.Id);

                    var prosku = new
                    {
                        SkuItems        = "",
                        MemberPrices    = "",
                        SkuId           = sku.Id,
                        ProductId       = product.Id,
                        SKU             = sku.Sku,
                        Weight          = 0,
                        Stock           = detailInfo == null? sku.Stock: Math.Min(detailInfo.TotalCount, sku.Stock),
                        WarningStock    = sku.SafeStock,
                        CostPrice       = sku.CostPrice,
                        SalePrice       = sku.SalePrice,//限时抢购价格
                        StoreStock      = 0,
                        StoreSalePrice  = 0,
                        OldSalePrice    = 0,
                        ImageUrl        = "",
                        ThumbnailUrl40  = "",
                        ThumbnailUrl410 = "",
                        MaxStock        = 15,
                        FreezeStock     = 0,
                        ActivityStock   = sku.Stock,                                            //限时抢购库存
                        ActivityPrice   = detailInfo == null ? sku.SalePrice : detailInfo.Price //限时抢购价格
                    };
                    Skus.Add(prosku);
                }

                #endregion
            }
            #endregion

            #region 店铺
            shop = ServiceProvider.Instance <IShopService> .Create.GetShop(product.ShopId);

            var vshopinfo = ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id);

            if (vshopinfo != null)
            {
                model.VShopLog     = vshopinfo.WXLogo;
                model.Shop.VShopId = vshopinfo.Id;
            }
            else
            {
                model.Shop.VShopId = -1;
                model.VShopLog     = string.Empty;
            }
            var mark = Web.Framework.ShopServiceMark.GetShopComprehensiveMark(shop.Id);
            model.Shop.PackMark          = mark.PackMark;
            model.Shop.ServiceMark       = mark.ServiceMark;
            model.Shop.ComprehensiveMark = mark.ComprehensiveMark;

            model.Shop.Name        = shop.ShopName;
            model.Shop.ProductMark = CommentApplication.GetProductAverageMark(product.Id);
            model.Shop.Id          = product.ShopId;
            model.Shop.FreeFreight = shop.FreeFreight;
            model.Shop.ProductNum  = ServiceProvider.Instance <IProductService> .Create.GetShopOnsaleProducts(product.ShopId);

            var shopStatisticOrderComments = ShopApplication.GetStatisticOrderComment(product.ShopId);
            //宝贝与描述
            model.Shop.ProductAndDescription = shopStatisticOrderComments.ProductAndDescription;
            //卖家服务态度
            model.Shop.SellerServiceAttitude = shopStatisticOrderComments.SellerServiceAttitude;
            //卖家发货速度
            model.Shop.SellerDeliverySpeed = shopStatisticOrderComments.SellerDeliverySpeed;

            if (ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id) == null)
            {
                model.Shop.VShopId = -1;
            }
            else
            {
                model.Shop.VShopId = ServiceProvider.Instance <IVShopService> .Create.GetVShopByShopId(shop.Id).Id;
            }

            List <object> coupons = new List <object>();
            //优惠券
            var result = GetCouponList(shop.Id);//取设置的优惠券
            if (result != null)
            {
                var couponCount = result.Count();
                model.Shop.CouponCount = couponCount;
                if (result.ToList().Count > 0)
                {
                    foreach (var item in result.ToList())
                    {
                        if (CurrentUser != null)
                        {//登录才处理已领
                            var Receive = CouponApplication.GetReceiveStatus(CurrentUserId, item.ShopId, item.Id);
                            if (Receive == 2 || Receive == 4)
                            {//不符合领取条件
                                continue;
                            }
                        }
                        var couponInfo = new
                        {
                            CouponId           = item.Id,
                            CouponName         = item.CouponName,
                            Price              = item.Price,
                            SendCount          = item.Num,
                            UserLimitCount     = item.PerMax,
                            OrderUseLimit      = item.OrderAmount,
                            StartTime          = item.StartTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            ClosingTime        = item.EndTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            CanUseProducts     = "",
                            ObtainWay          = item.ReceiveType,
                            NeedPoint          = item.NeedIntegral,
                            UseWithGroup       = false,
                            UseWithPanicBuying = false,
                            UseWithFireGroup   = false,
                            LimitText          = item.CouponName,
                            CanUseProduct      = item.UseArea == 1 ? "部分商品可用" : "全店通用",
                            StartTimeText      = item.StartTime.ToString("yyyy.MM.dd"),
                            ClosingTimeText    = item.EndTime.ToString("yyyy.MM.dd")
                        };
                        coupons.Add(couponInfo);
                    }
                }
            }


            #endregion

            #region 商品
            var consultations = ServiceProvider.Instance <IConsultationService> .Create.GetConsultations(product.Id);

            var  comments   = CommentApplication.GetCommentsByProduct(product.Id);
            var  total      = comments.Count();
            var  niceTotal  = comments.Count(item => item.ReviewMark >= 4);
            bool isFavorite = false;
            if (CurrentUser == null)
            {
                isFavorite = false;
            }
            else
            {
                isFavorite = ServiceProvider.Instance <IProductService> .Create.IsFavorite(product.Id, CurrentUser.Id);
            }
            var limitBuy = ServiceProvider.Instance <ILimitTimeBuyService> .Create.GetLimitTimeMarketItemByProductId(product.Id);

            var productImage = new List <string>();
            for (int i = 1; i < 6; i++)
            {
                if (i == 1 || Himall.Core.HimallIO.ExistFile(product.RelativePath + string.Format("/{0}.png", i)))
                {
                    productImage.Add(Core.HimallIO.GetRomoteImagePath(product.RelativePath + string.Format("/{0}.png", i)));
                }
            }

            model.Product = new ProductInfoModel()
            {
                ProductId          = product.Id,
                CommentCount       = CommentApplication.GetCommentCountByProduct(product.Id),
                Consultations      = consultations.Count(),
                ImagePath          = productImage,
                IsFavorite         = isFavorite,
                MarketPrice        = product.MarketPrice,
                MinSalePrice       = product.MinSalePrice,
                NicePercent        = model.Shop.ProductMark == 0 ? 100 : (int)((niceTotal / total) * 100),
                ProductName        = product.ProductName,
                ProductSaleStatus  = product.SaleStatus,
                AuditStatus        = product.AuditStatus,
                ShortDescription   = product.ShortDescription,
                ProductDescription = description.ShowMobileDescription,
                IsOnLimitBuy       = limitBuy != null,
                MeasureUnit        = product.MeasureUnit
            };

            #endregion

            //LogProduct(market.ProductId);
            //统计商品浏览量、店铺浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);

            TimeSpan end    = new TimeSpan(DateTime.Parse(market.EndDate).Ticks);
            TimeSpan start  = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan ts     = end.Subtract(start);
            var      second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;

            List <object> ProductImgs = new List <object>();
            for (int i = 1; i < 5; i++)
            {
                if (i == 1 || Himall.Core.HimallIO.ExistFile(product.RelativePath + string.Format("/{0}.png", i)))
                {
                    ProductImgs.Add(Core.HimallIO.GetRomoteProductSizeImage(product.ImagePath, i, (int)ImageSize.Size_350));
                }
            }

            var countDownStatus = 0;

            if (market.Status == FlashSaleInfo.FlashSaleStatus.Ended)
            {
                countDownStatus = 4;//"PullOff";  //已下架
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Cancelled || market.Status == FlashSaleInfo.FlashSaleStatus.AuditFailed || market.Status == FlashSaleInfo.FlashSaleStatus.WaitForAuditing)
            {
                countDownStatus = 4;//"NoJoin";  //未参与
            }
            else if (DateTime.Parse(market.BeginDate) > DateTime.Now)
            {
                countDownStatus = 6; // "AboutToBegin";  //即将开始   6
            }
            else if (DateTime.Parse(market.EndDate) < DateTime.Now)
            {
                countDownStatus = 4;// "ActivityEnd";   //已结束  4
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Ended)
            {
                countDownStatus = 6;// "SoldOut";  //已抢完
            }
            else
            {
                countDownStatus = 2;//"Normal";  //正常  2
            }

            long saleCounts = 0;
            if (countDownStatus == 2)
            {
                saleCounts = market.SaleCount;
            }
            else
            {
                saleCounts = product.SaleCounts + Himall.Core.Helper.TypeHelper.ObjectToInt(product.VirtualSaleCounts);
            }
            //Normal:正常
            //PullOff:已下架
            //NoJoin:未参与
            //AboutToBegin:即将开始
            //ActivityEnd:已结束
            //SoldOut:已抢完

            decimal discount  = 1M;//限时购不考虑会员折
            int     addressId = 0;
            if (CurrentUser != null)
            {
                var addressInfo = ShippingAddressApplication.GetDefaultUserShippingAddressByUserId(CurrentUser.Id);
                if (addressInfo != null)
                {
                    addressId = addressInfo.RegionId;
                }
            }


            //商品关联版式
            string DescriptionPrefix = "", DescriptiondSuffix = "";
            var    iprodestempser = ServiceApplication.Create <IProductDescriptionTemplateService>();
            if (description.DescriptionPrefixId != 0)
            {
                var desc = iprodestempser.GetTemplate(description.DescriptionPrefixId, product.ShopId);
                DescriptionPrefix = desc == null ? "" : desc.MobileContent;
            }

            if (description.DescriptiondSuffixId != 0)
            {
                var desc = iprodestempser.GetTemplate(description.DescriptiondSuffixId, product.ShopId);
                DescriptiondSuffix = desc == null ? "" : desc.MobileContent;
            }

            var    productDescription = DescriptionPrefix + model.Product.ProductDescription + DescriptiondSuffix;
            string skuId = skus.FirstOrDefault()?.Id ?? string.Empty;

            return(JsonResult <dynamic>(new
            {
                CountDownId = market.Id,//.CountDownId,
                MaxCount = market.LimitCountOfThePeople,
                CountDownStatus = countDownStatus,
                StartDate = DateTime.Parse(market.BeginDate).ToString("yyyy/MM/dd HH:mm:ss"),
                EndDate = DateTime.Parse(market.EndDate).ToString("yyyy/MM/dd HH:mm:ss"),
                NowTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo),
                ProductId = product.Id,
                ProductName = product.ProductName,
                MetaDescription = productDescription.Replace("\"/Storage/Shop", "\"" + Core.HimallIO.GetRomoteImagePath("/Storage/Shop")),//替换链接  /Storage/Shop,
                ShortDescription = product.ShortDescription,
                ShowSaleCounts = saleCounts,
                IsSaleCountOnOff = SiteSettingApplication.SiteSettings.ProductSaleCountOnOff == 1,
                Weight = product.Weight.ToString(),
                MinSalePrice = market.MinPrice.ToString("0.##"), //限时抢购价格
                MaxSalePrice = market.SkuMaxPrice,
                Stock = market.Quantity,                         //限时抢购库存
                MarketPrice = product.MarketPrice,
                IsfreeShipping = shop.FreeFreight,
                ThumbnailUrl60 = Core.HimallIO.GetRomoteProductSizeImage(product.ImagePath, 1, (int)ImageSize.Size_350),
                ProductImgs = ProductImgs,
                SkuItemList = SkuItemList,
                Skus = Skus,
                Shop = model.Shop,
                VShopLog = Himall.Core.HimallIO.GetRomoteImagePath(model.VShopLog),
                Freight = GetFreightStr(product.Id, discount, skuId, addressId),
                Coupons = coupons,
                IsValidLimitBuy = true,
                CommentsNumber = CommentApplication.GetCommentCountByProduct(product.Id),
                VideoPath = string.IsNullOrWhiteSpace(product.VideoPath) ? string.Empty : Himall.Core.HimallIO.GetRomoteImagePath(product.VideoPath),
                MeasureUnit = string.IsNullOrEmpty(product.MeasureUnit)?"":product.MeasureUnit,                                                                       //单位
                SendTime = (model.FreightTemplate != null && !string.IsNullOrEmpty(model.FreightTemplate.SendTime) ? (model.FreightTemplate.SendTime + "h内发货") : ""), //运费模板发货时间
            }));
        }
        public object GetShopBranchs(long shopId, bool getParent, string skuIds, string counts, int page, int rows, long shippingAddressId, long regionId)
        {
            string[]            strArray            = skuIds.Split(',');
            int[]               _counts             = Enumerable.ToArray <int>(Enumerable.Select <string, int>((IEnumerable <string>)counts.Split(','), (Func <string, int>)(p => TypeHelper.ObjectToInt((object)p))));
            ShippingAddressInfo userShippingAddress = ShippingAddressApplication.GetUserShippingAddress(shippingAddressId);
            int             streetId        = 0;
            int             districtId      = 0;
            ShopBranchQuery shopBranchQuery = new ShopBranchQuery();

            shopBranchQuery.ShopId   = shopId;
            shopBranchQuery.PageNo   = page;
            shopBranchQuery.PageSize = rows;
            shopBranchQuery.Status   = new ShopBranchStatus?(ShopBranchStatus.Normal);
            ShopBranchQuery query = shopBranchQuery;

            if (userShippingAddress != null)
            {
                query.FromLatLng = string.Format("{0},{1}", (object)userShippingAddress.Latitude, (object)userShippingAddress.Longitude);
                streetId         = userShippingAddress.RegionId;
                Region region = RegionApplication.GetRegion((long)userShippingAddress.RegionId, Region.RegionLevel.Town);
                if (region != null && region.ParentId > 0)
                {
                    districtId = region.ParentId;
                }
                else
                {
                    districtId = streetId;
                    streetId   = 0;
                }
            }
            bool hasLatLng = false;

            if (!string.IsNullOrWhiteSpace(query.FromLatLng))
            {
                hasLatLng = (query.FromLatLng.Split(',').Length == 2 ? 1 : 0) != 0;
            }
            Region region1 = RegionApplication.GetRegion(regionId, getParent ? Region.RegionLevel.City : Region.RegionLevel.County);

            if (region1 != null)
            {
                query.AddressPath = region1.GetIdPath(",");
            }
            List <SKU> skuInfos = ProductManagerApplication.GetSKUs((IEnumerable <string>)strArray);

            query.ProductIds = Enumerable.ToArray <long>(Enumerable.Select <SKU, long>((IEnumerable <SKU>)skuInfos, (Func <SKU, long>)(p => p.ProductId)));
            QueryPageModel <ShopBranch> shopBranchsAll = ShopBranchApplication.GetShopBranchsAll(query);
            List <ShopBranchSkusInfo>   shopBranchSkus = ShopBranchApplication.GetSkus(shopId, Enumerable.Select <ShopBranch, long>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, long>)(p => p.Id)));

            shopBranchsAll.Models.ForEach((Action <ShopBranch>)(p => p.Enabled = Enumerable.All <SKU>((IEnumerable <SKU>)skuInfos, (Func <SKU, bool>)(skuInfo => Enumerable.Any <ShopBranchSkusInfo>((IEnumerable <ShopBranchSkusInfo>)shopBranchSkus, (Func <ShopBranchSkusInfo, bool>)(sbSku => sbSku.ShopBranchId == p.Id && sbSku.Stock >= _counts[skuInfos.IndexOf(skuInfo)] && sbSku.SkuId == skuInfo.Id))))));
            List <ShopBranch> list1      = new List <ShopBranch>();
            List <long>       fillterIds = new List <long>();
            List <ShopBranch> list2      = Enumerable.ToList <ShopBranch>((IEnumerable <ShopBranch>)Enumerable.OrderBy <ShopBranch, double>(Enumerable.Where <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, bool>)(p => hasLatLng && p.Enabled && ((double)p.Latitude > 0.0 && (double)p.Longitude > 0.0))), (Func <ShopBranch, double>)(p => p.Distance)));

            if (list2 != null && Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list2) > 0)
            {
                fillterIds.AddRange(Enumerable.Select <ShopBranch, long>((IEnumerable <ShopBranch>)list2, (Func <ShopBranch, long>)(p => p.Id)));
                list1.AddRange((IEnumerable <ShopBranch>)list2);
            }
            List <ShopBranch> list3 = Enumerable.ToList <ShopBranch>(Enumerable.Where <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, bool>)(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains("," + (object)streetId + ","))));

            if (list3 != null && Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list3) > 0)
            {
                fillterIds.AddRange(Enumerable.Select <ShopBranch, long>((IEnumerable <ShopBranch>)list3, (Func <ShopBranch, long>)(p => p.Id)));
                list1.AddRange((IEnumerable <ShopBranch>)list3);
            }
            List <ShopBranch> list4 = Enumerable.ToList <ShopBranch>(Enumerable.Where <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, bool>)(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains("," + (object)districtId + ","))));

            if (list4 != null && Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list4) > 0)
            {
                fillterIds.AddRange(Enumerable.Select <ShopBranch, long>((IEnumerable <ShopBranch>)list4, (Func <ShopBranch, long>)(p => p.Id)));
                list1.AddRange((IEnumerable <ShopBranch>)list4);
            }
            List <ShopBranch> list5 = Enumerable.ToList <ShopBranch>(Enumerable.Where <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, bool>)(p => !fillterIds.Contains(p.Id) && p.Enabled)));

            if (list5 != null && Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list5) > 0)
            {
                fillterIds.AddRange(Enumerable.Select <ShopBranch, long>((IEnumerable <ShopBranch>)list5, (Func <ShopBranch, long>)(p => p.Id)));
                list1.AddRange((IEnumerable <ShopBranch>)list5);
            }
            List <ShopBranch> list6 = Enumerable.ToList <ShopBranch>(Enumerable.Where <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models, (Func <ShopBranch, bool>)(p => !fillterIds.Contains(p.Id))));

            if (list6 != null && Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list6) > 0)
            {
                list1.AddRange((IEnumerable <ShopBranch>)list6);
            }
            if (Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)list1) != Enumerable.Count <ShopBranch>((IEnumerable <ShopBranch>)shopBranchsAll.Models))
            {
                return((object)this.Json(new
                {
                    Success = false
                }));
            }
            var content = new
            {
                Success   = true,
                StoreList = Enumerable.Select((IEnumerable <ShopBranch>)list1, sb =>
                {
                    var fAnonymousType37 = new
                    {
                        ContactUser    = sb.ContactUser,
                        ContactPhone   = sb.ContactPhone,
                        AddressDetail  = sb.AddressDetail,
                        ShopBranchName = sb.ShopBranchName,
                        Id             = sb.Id,
                        Enabled        = sb.Enabled
                    };
                    return(fAnonymousType37);
                })
            };

            return((object)this.Json(content));
        }
Esempio n. 17
0
        public JsonResult GetShopBranchs(long shopId, long regionId, bool getParent, string[] skuIds, int[] counts, int page, int rows, long shippingAddressId)
        {
            ShippingAddressInfo userShippingAddress = ShippingAddressApplication.GetUserShippingAddress(shippingAddressId);
            int             streetId   = 0;
            int             districtId = 0;
            ShopBranchQuery query      = new ShopBranchQuery
            {
                ShopId   = shopId,
                PageNo   = page,
                PageSize = rows,
                Status   = 0
            };

            if (userShippingAddress != null)
            {
                query.FromLatLng = string.Format("{0},{1}", userShippingAddress.Latitude, userShippingAddress.Longitude);
                streetId         = userShippingAddress.RegionId;
                Region region = RegionApplication.GetRegion((long)userShippingAddress.RegionId, Region.RegionLevel.Town);
                if ((region != null) && (region.ParentId > 0))
                {
                    districtId = region.ParentId;
                }
                else
                {
                    districtId = streetId;
                    streetId   = 0;
                }
            }
            bool hasLatLng = false;

            if (!string.IsNullOrWhiteSpace(query.FromLatLng))
            {
                hasLatLng = query.FromLatLng.Split(new char[] { ',' }).Length == 2;
            }
            Region region2 = RegionApplication.GetRegion(regionId, getParent ? Region.RegionLevel.City : Region.RegionLevel.County);

            if (region2 != null)
            {
                query.AddressPath = region2.GetIdPath(",");
            }
            List <SKU> skuInfos = ProductManagerApplication.GetSKUs(skuIds);

            query.ProductIds = (from p in skuInfos select p.ProductId).ToArray <long>();
            QueryPageModel <ShopBranch> shopBranchsAll = ShopBranchApplication.GetShopBranchsAll(query);
            List <ShopBranchSkusInfo>   shopBranchSkus = ShopBranchApplication.GetSkus(shopId, from p in shopBranchsAll.Models select p.Id);

            shopBranchsAll.Models.ForEach(delegate(ShopBranch p)
            {
                p.Enabled = skuInfos.All <SKU>(skuInfo => shopBranchSkus.Any <ShopBranchSkusInfo>(sbSku => ((sbSku.ShopBranchId == p.Id) && (sbSku.Stock >= counts[skuInfos.IndexOf(skuInfo)])) && (sbSku.SkuId == skuInfo.Id)));
            });
            List <ShopBranch> source     = new List <ShopBranch>();
            List <long>       fillterIds = new List <long>();
            List <ShopBranch> list2      = (from p in shopBranchsAll.Models
                                            where (hasLatLng && p.Enabled) && ((p.Latitude > 0f) && (p.Longitude > 0f))
                                            orderby p.Distance
                                            select p).ToList <ShopBranch>();

            if ((list2 != null) && (list2.Count <ShopBranch>() > 0))
            {
                fillterIds.AddRange(from p in list2 select p.Id);
                source.AddRange(list2);
            }
            List <ShopBranch> list3 = (from p in shopBranchsAll.Models
                                       where (!fillterIds.Contains(p.Id) && p.Enabled) && p.AddressPath.Contains("," + streetId + ",")
                                       select p).ToList <ShopBranch>();

            if ((list3 != null) && (list3.Count <ShopBranch>() > 0))
            {
                fillterIds.AddRange(from p in list3 select p.Id);
                source.AddRange(list3);
            }
            List <ShopBranch> list4 = (from p in shopBranchsAll.Models
                                       where (!fillterIds.Contains(p.Id) && p.Enabled) && p.AddressPath.Contains("," + districtId + ",")
                                       select p).ToList <ShopBranch>();

            if ((list4 != null) && (list4.Count <ShopBranch>() > 0))
            {
                fillterIds.AddRange(from p in list4 select p.Id);
                source.AddRange(list4);
            }
            List <ShopBranch> list5 = (from p in shopBranchsAll.Models
                                       where !fillterIds.Contains(p.Id) && p.Enabled
                                       select p).ToList <ShopBranch>();

            if ((list5 != null) && (list5.Count <ShopBranch>() > 0))
            {
                fillterIds.AddRange(from p in list5 select p.Id);
                source.AddRange(list5);
            }
            List <ShopBranch> list6 = (from p in shopBranchsAll.Models
                                       where !fillterIds.Contains(p.Id)
                                       select p).ToList <ShopBranch>();

            if ((list6 != null) && (list6.Count <ShopBranch>() > 0))
            {
                source.AddRange(list6);
            }
            if (source.Count <ShopBranch>() != shopBranchsAll.Models.Count <ShopBranch>())
            {
                return(base.Json(new { Rows = "" }, true));
            }
            var data = new
            {
                Rows  = (from sb in source select new { ContactUser = sb.ContactUser, ContactPhone = sb.ContactPhone, AddressDetail = sb.AddressDetail, ShopBranchName = sb.ShopBranchName, Id = sb.Id, Enabled = sb.Enabled }).ToArray(),
                Total = source.Count
            };

            return(base.Json(data, true));
        }
Esempio n. 18
0
        public ActionResult Detail(string id)
        {
            LimitTimeBuyDetailModel detailModel = new LimitTimeBuyDetailModel();
            string price = "";

            #region 定义Model和变量

            LimitTimeProductDetailModel model = new LimitTimeProductDetailModel
            {
                MainId = long.Parse(id),
                HotAttentionProducts = new List <HotProductInfo>(),
                HotSaleProducts      = new List <HotProductInfo>(),
                Product      = new Entities.ProductInfo(),
                Shop         = new ShopInfoModel(),
                ShopCategory = new List <CategoryJsonModel>(),
                Color        = new CollectionSKU(),
                Size         = new CollectionSKU(),
                Version      = new CollectionSKU()
            };

            FlashSaleModel    market = null;
            Entities.ShopInfo shop   = null;

            long gid = 0, mid = 0;

            #endregion

            #region 商品Id不合法
            if (long.TryParse(id, out mid))
            {
            }
            if (mid == 0)
            {
                //跳转到出错页面
                return(RedirectToAction("Error404", "Error", new { area = "Mobile" }));
            }
            #endregion

            #region 初始化商品和店铺
            //参数是限时购活动ID
            try
            {
                market = _iLimitTimeBuyService.Get(mid);
            }
            catch
            {
                market = null;
            }
            if (market != null)
            {
                switch (market.Status)
                {
                case FlashSaleInfo.FlashSaleStatus.Ended:
                    return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));

                case FlashSaleInfo.FlashSaleStatus.Cancelled:
                    return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));
                }

                model.FlashSale = market;
            }
            if (market == null || market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
            {
                //可能参数是商品ID
                market = market == null?_iLimitTimeBuyService.GetFlaseSaleByProductId(mid) : market;

                if (market == null)
                {
                    //跳转到404页面
                    return(RedirectToAction("Error404", "Error", new { area = "Mobile" }));
                }
                if (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing)
                {
                    return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));
                }
                market = _iLimitTimeBuyService.Get(market.Id);
            }
            model.FlashSale = market;

            if (market != null && (market.Status != FlashSaleInfo.FlashSaleStatus.Ongoing || DateTime.Parse(market.EndDate) < DateTime.Now))
            {
                return(RedirectToAction("Detail", "Product", new { id = market.ProductId }));
            }

            model.MaxSaleCount = market.LimitCountOfThePeople;
            model.Title        = market.Title;

            shop = _iShopService.GetShop(market.ShopId);

            #endregion

            #region  存在的商品
            if (null == market || market.Id == 0)
            {
                //跳转到出错页面
                return(RedirectToAction("Error404", "Error", new { area = "Web" }));
            }
            #endregion

            #region 商品描述
            var product = _iProductService.GetProduct(market.ProductId);
            gid = market.ProductId;

            model.Product = product;
            var description = ProductManagerApplication.GetProductDescription(product.Id);
            model.ProductDescription = description.ShowMobileDescription;
            if (description.DescriptionPrefixId != 0)
            {
                var desc = _iProductDescriptionTemplateService
                           .GetTemplate(description.DescriptionPrefixId, product.ShopId);
                model.DescriptionPrefix = desc == null ? "" : desc.Content;
            }

            if (description.DescriptiondSuffixId != 0)
            {
                var desc = _iProductDescriptionTemplateService
                           .GetTemplate(description.DescriptiondSuffixId, product.ShopId);
                model.DescriptiondSuffix = desc == null ? "" : desc.Content;
            }

            var mark = ShopServiceMark.GetShopComprehensiveMark(shop.Id);
            model.Shop.PackMark          = mark.PackMark;
            model.Shop.ServiceMark       = mark.ServiceMark;
            model.Shop.ComprehensiveMark = mark.ComprehensiveMark;
            model.Shop.Name               = shop.ShopName;
            model.Shop.ProductMark        = CommentApplication.GetProductAverageMark(gid);
            model.Shop.Id                 = product.ShopId;
            model.Shop.FreeFreight        = shop.FreeFreight;
            detailModel.ProductNum        = _iProductService.GetShopOnsaleProducts(product.ShopId);
            detailModel.FavoriteShopCount = _iShopService.GetShopFavoritesCount(product.ShopId);
            if (CurrentUser == null)
            {
                detailModel.IsFavorite     = false;
                detailModel.IsFavoriteShop = false;
            }
            else
            {
                detailModel.IsFavorite = _iProductService.IsFavorite(product.Id, CurrentUser.Id);
                var favoriteShopIds = _iShopService.GetFavoriteShopInfos(CurrentUser.Id).Select(item => item.ShopId).ToArray();//获取已关注店铺
                detailModel.IsFavoriteShop = favoriteShopIds.Contains(product.ShopId);
            }
            #endregion

            #region 店铺分类

            var categories = _iShopCategoryService.GetShopCategory(product.ShopId);
            List <Entities.ShopCategoryInfo> allcate = categories.ToList();
            foreach (var main in allcate.Where(s => s.ParentCategoryId == 0))
            {
                var topC = new CategoryJsonModel()
                {
                    Name        = main.Name,
                    Id          = main.Id.ToString(),
                    SubCategory = new List <SecondLevelCategory>()
                };
                foreach (var secondItem in allcate.Where(s => s.ParentCategoryId == main.Id))
                {
                    var secondC = new SecondLevelCategory()
                    {
                        Name = secondItem.Name,
                        Id   = secondItem.Id.ToString(),
                    };

                    topC.SubCategory.Add(secondC);
                }
                model.ShopCategory.Add(topC);
            }

            #endregion

            #region 热门销售

            var sale = _iProductService.GetHotSaleProduct(shop.Id, 5);
            if (sale != null)
            {
                foreach (var item in sale.ToArray())
                {
                    model.HotSaleProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = item.MinSalePrice,
                        Id        = item.Id,
                        SaleCount = (int)item.SaleCounts + Mall.Core.Helper.TypeHelper.ObjectToInt(item.VirtualSaleCounts)
                    });
                }
            }

            #endregion

            #region 热门关注

            var hot = _iProductService.GetHotConcernedProduct(shop.Id, 5);
            if (hot != null)
            {
                foreach (var item in hot.ToArray())
                {
                    model.HotAttentionProducts.Add(new HotProductInfo
                    {
                        ImgPath   = item.ImagePath,
                        Name      = item.ProductName,
                        Price     = item.MinSalePrice,
                        Id        = item.Id,
                        SaleCount = (int)item.ConcernedCount
                    });
                }
            }
            #endregion

            #region 商品规格

            Entities.TypeInfo typeInfo     = _iTypeService.GetType(product.TypeId);
            string            colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string            sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string            versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;
            if (product != null)
            {
                colorAlias   = !string.IsNullOrWhiteSpace(product.ColorAlias) ? product.ColorAlias : colorAlias;
                sizeAlias    = !string.IsNullOrWhiteSpace(product.SizeAlias) ? product.SizeAlias : sizeAlias;
                versionAlias = !string.IsNullOrWhiteSpace(product.VersionAlias) ? product.VersionAlias : versionAlias;
            }
            model.ColorAlias   = colorAlias;
            model.SizeAlias    = sizeAlias;
            model.VersionAlias = versionAlias;
            var skus = ProductManagerApplication.GetSKUs(product.Id);
            if (skus.Count > 0)
            {
                long colorId = 0, sizeId = 0, versionId = 0;
                foreach (var sku in skus)
                {
                    var specs = sku.Id.Split('_');
                    if (specs.Count() > 0 && !string.IsNullOrEmpty(sku.Color))
                    {
                        if (long.TryParse(specs[1], out colorId))
                        {
                        }
                        if (colorId != 0)
                        {
                            if (!model.Color.Any(v => v.Value.Equals(sku.Color)))
                            {
                                var c = skus.Where(s => s.Color.Equals(sku.Color)).Sum(s => s.Stock);
                                model.Color.Add(new ProductSKU
                                {
                                    //Name = "选择颜色",
                                    Name         = "选择" + colorAlias,
                                    EnabledClass = c != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Color.Any(c1 => c1.SelectedClass.Equals("selected")) && c != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = colorId,
                                    Value         = sku.Color,
                                    Img           = Core.MallIO.GetImagePath(sku.ShowPic)
                                });
                            }
                        }
                    }
                    if (specs.Count() > 1 && !string.IsNullOrEmpty(sku.Size))
                    {
                        if (long.TryParse(specs[2], out sizeId))
                        {
                        }
                        if (sizeId != 0)
                        {
                            if (!model.Size.Any(v => v.Value.Equals(sku.Size)))
                            {
                                var ss = skus.Where(s => s.Size.Equals(sku.Size)).Sum(s1 => s1.Stock);
                                model.Size.Add(new ProductSKU
                                {
                                    //Name = "选择尺码",
                                    Name         = "选择" + sizeAlias,
                                    EnabledClass = ss != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Size.Any(s1 => s1.SelectedClass.Equals("selected")) && ss != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = sizeId,
                                    Value         = sku.Size
                                });
                            }
                        }
                    }

                    if (specs.Count() > 2 && !string.IsNullOrEmpty(sku.Version))
                    {
                        if (long.TryParse(specs[3], out versionId))
                        {
                        }
                        if (versionId != 0)
                        {
                            if (!model.Version.Any(v => v.Value.Equals(sku.Version)))
                            {
                                var v = skus.Where(s => s.Version.Equals(sku.Version)).Sum(s => s.Stock);
                                model.Version.Add(new ProductSKU
                                {
                                    //Name = "选择版本",
                                    Name         = "选择" + versionAlias,
                                    EnabledClass = v != 0 ? "enabled" : "disabled",
                                    //SelectedClass = !model.Version.Any(v1 => v1.SelectedClass.Equals("selected")) && v != 0 ? "selected" : "",
                                    SelectedClass = "",
                                    SkuId         = versionId,
                                    Value         = sku.Version
                                });
                            }
                        }
                    }
                }
                //var min = skus.Where(s => s.Stock >= 0).Min(s => s.SalePrice);
                //var max = skus.Where(s => s.Stock >= 0).Max(s => s.SalePrice);
                //if (min == 0 && max == 0)
                //{
                //    price = product.MinSalePrice.ToString("f2");
                //}
                //else if (max > min)
                //{
                //    price = string.Format("{0}-{1}", min.ToString("f2"), max.ToString("f2"));
                //}
                //else
                //{
                //    price = string.Format("{0}", min.ToString("f2"));
                //}
                price = ProductWebApplication.GetProductPriceStr2(product, skus);//最小价或区间价文本
            }
            detailModel.Price = string.IsNullOrWhiteSpace(price) ? product.MinSalePrice.ToString("f2") : price;
            #endregion

            #region 商品属性
            List <TypeAttributesModel> ProductAttrs = new List <TypeAttributesModel>();
            var prodAttrs = ProductManagerApplication.GetProductAttributes(product.Id);
            foreach (var attr in prodAttrs)
            {
                if (!ProductAttrs.Any(p => p.AttrId == attr.AttributeId))
                {
                    var attribute = _iTypeService.GetAttribute(attr.AttributeId);
                    var values    = _iTypeService.GetAttributeValues(attr.AttributeId);
                    TypeAttributesModel attrModel = new TypeAttributesModel()
                    {
                        AttrId     = attr.AttributeId,
                        AttrValues = new List <TypeAttrValue>(),
                        Name       = attribute.Name
                    };
                    foreach (var attrV in values)
                    {
                        if (prodAttrs.Any(p => p.ValueId == attrV.Id))
                        {
                            attrModel.AttrValues.Add(new TypeAttrValue
                            {
                                Id   = attrV.Id.ToString(),
                                Name = attrV.Value
                            });
                        }
                    }
                    ProductAttrs.Add(attrModel);
                }
                else
                {
                    var attrTemp = ProductAttrs.FirstOrDefault(p => p.AttrId == attr.AttributeId);
                    var values   = _iTypeService.GetAttributeValues(attr.AttributeId);
                    if (!attrTemp.AttrValues.Any(p => p.Id == attr.ValueId.ToString()))
                    {
                        attrTemp.AttrValues.Add(new TypeAttrValue
                        {
                            Id   = attr.ValueId.ToString(),
                            Name = values.FirstOrDefault(a => a.Id == attr.ValueId).Value
                        });
                    }
                }
            }
            detailModel.ProductAttrs = ProductAttrs;
            #endregion

            #region 获取评论、咨询数量

            var comments = CommentApplication.GetCommentsByProduct(product.Id);
            detailModel.CommentCount = comments.Count;

            var consultations = ServiceApplication.Create <IConsultationService>().GetConsultations(gid);

            var total     = comments.Count;
            var niceTotal = comments.Count(item => item.ReviewMark >= 4);
            detailModel.NicePercent   = (int)((niceTotal / (double)total) * 100);
            detailModel.Consultations = consultations.Count();

            if (_iVShopService.GetVShopByShopId(shop.Id) == null)
            {
                detailModel.VShopId = -1;
            }
            else
            {
                detailModel.VShopId = _iVShopService.GetVShopByShopId(shop.Id).Id;
            }
            #endregion

            #region 累加浏览次数、 加入历史记录
            //if (CurrentUser != null)
            //{
            //    BrowseHistrory.AddBrowsingProduct(product.Id, CurrentUser.Id);
            //}
            //else
            //{
            //    BrowseHistrory.AddBrowsingProduct(product.Id);
            //}
            //_iProductService.LogProductVisti(gid);
            #endregion

            #region 获取店铺的评价统计
            var shopStatisticOrderComments = _iShopService.GetShopStatisticOrderComments(product.ShopId);

            var productAndDescription = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescription).FirstOrDefault();
            var sellerServiceAttitude = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitude).FirstOrDefault();
            var sellerDeliverySpeed   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                         Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeed).FirstOrDefault();

            var productAndDescriptionPeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionPeer).FirstOrDefault();
            var sellerServiceAttitudePeer = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudePeer).FirstOrDefault();
            var sellerDeliverySpeedPeer   = shopStatisticOrderComments.Where(c => c.CommentKey ==
                                                                             Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedPeer).FirstOrDefault();

            var productAndDescriptionMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMax).FirstOrDefault();
            var productAndDescriptionMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.ProductAndDescriptionMin).FirstOrDefault();

            var sellerServiceAttitudeMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMax).FirstOrDefault();
            var sellerServiceAttitudeMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerServiceAttitudeMin).FirstOrDefault();

            var sellerDeliverySpeedMax = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMax).FirstOrDefault();
            var sellerDeliverySpeedMin = shopStatisticOrderComments.Where(c => c.CommentKey == Entities.StatisticOrderCommentInfo.EnumCommentKey.SellerDeliverySpeedMin).FirstOrDefault();

            decimal defaultValue = 5;
            //宝贝与描述
            if (productAndDescription != null && productAndDescriptionPeer != null && !shop.IsSelf)
            {
                detailModel.ProductAndDescription     = productAndDescription.CommentValue;
                detailModel.ProductAndDescriptionPeer = productAndDescriptionPeer.CommentValue;
                detailModel.ProductAndDescriptionMin  = productAndDescriptionMin.CommentValue;
                detailModel.ProductAndDescriptionMax  = productAndDescriptionMax.CommentValue;
            }
            else
            {
                detailModel.ProductAndDescription     = defaultValue;
                detailModel.ProductAndDescriptionPeer = defaultValue;
                detailModel.ProductAndDescriptionMin  = defaultValue;
                detailModel.ProductAndDescriptionMax  = defaultValue;
            }
            //卖家服务态度
            if (sellerServiceAttitude != null && sellerServiceAttitudePeer != null && !shop.IsSelf)
            {
                detailModel.SellerServiceAttitude     = sellerServiceAttitude.CommentValue;
                detailModel.SellerServiceAttitudePeer = sellerServiceAttitudePeer.CommentValue;
                detailModel.SellerServiceAttitudeMax  = sellerServiceAttitudeMax.CommentValue;
                detailModel.SellerServiceAttitudeMin  = sellerServiceAttitudeMin.CommentValue;
            }
            else
            {
                detailModel.SellerServiceAttitude     = defaultValue;
                detailModel.SellerServiceAttitudePeer = defaultValue;
                detailModel.SellerServiceAttitudeMax  = defaultValue;
                detailModel.SellerServiceAttitudeMin  = defaultValue;
            }
            //卖家发货速度
            if (sellerDeliverySpeedPeer != null && sellerDeliverySpeed != null && !shop.IsSelf)
            {
                detailModel.SellerDeliverySpeed     = sellerDeliverySpeed.CommentValue;
                detailModel.SellerDeliverySpeedPeer = sellerDeliverySpeedPeer.CommentValue;
                detailModel.SellerDeliverySpeedMax  = sellerDeliverySpeedMax != null ? sellerDeliverySpeedMax.CommentValue : 0;
                detailModel.sellerDeliverySpeedMin  = sellerDeliverySpeedMin != null ? sellerDeliverySpeedMin.CommentValue : 0;
            }
            else
            {
                detailModel.SellerDeliverySpeed     = defaultValue;
                detailModel.SellerDeliverySpeedPeer = defaultValue;
                detailModel.SellerDeliverySpeedMax  = defaultValue;
                detailModel.sellerDeliverySpeedMin  = defaultValue;
            }
            #endregion

            #region 是否收藏此商品
            if (CurrentUser != null && CurrentUser.Id > 0)
            {
                model.IsFavorite = _iProductService.IsFavorite(product.Id, CurrentUser.Id);
            }
            else
            {
                model.IsFavorite = false;
            }
            #endregion

            long vShopId;
            var  vshopinfo = _iVShopService.GetVShopByShopId(shop.Id);
            if (vshopinfo == null)
            {
                vShopId = -1;
            }
            else
            {
                vShopId = vshopinfo.Id;
            }
            detailModel.VShopId = vShopId;
            model.Shop.VShopId  = vShopId;

            model.VShopLog = _iVShopService.GetVShopLog(model.Shop.VShopId);
            if (string.IsNullOrWhiteSpace(model.VShopLog))
            {
                //throw new Mall.Core.MallException("店铺未开通微店功能");
                model.VShopLog = SiteSettings.WXLogo;
            }
            detailModel.Logined = (null != CurrentUser) ? 1 : 0;
            model.EnabledBuy    = product.AuditStatus == Entities.ProductInfo.ProductAuditStatus.Audited && DateTime.Parse(market.BeginDate) <= DateTime.Now && DateTime.Parse(market.EndDate) > DateTime.Now && product.SaleStatus == Entities.ProductInfo.ProductSaleStatus.OnSale;
            int saleCounts = 0;
            saleCounts = market.SaleCount;
            if (market.Status == FlashSaleInfo.FlashSaleStatus.Ongoing && DateTime.Parse(market.BeginDate) < DateTime.Now && DateTime.Parse(market.EndDate) > DateTime.Now)
            {
                TimeSpan end   = new TimeSpan(DateTime.Parse(market.EndDate).Ticks);
                TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts    = end.Subtract(start);
                detailModel.Second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;
            }
            else if (market.Status == FlashSaleInfo.FlashSaleStatus.Ongoing && DateTime.Parse(market.BeginDate) > DateTime.Now)
            {
                TimeSpan end   = new TimeSpan(DateTime.Parse(market.BeginDate).Ticks);
                TimeSpan start = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts    = end.Subtract(start);
                detailModel.Second = ts.TotalSeconds < 0 ? 0 : ts.TotalSeconds;
                saleCounts         = Mall.Core.Helper.TypeHelper.ObjectToInt(product.SaleCounts) + Mall.Core.Helper.TypeHelper.ObjectToInt(product.VirtualSaleCounts);
            }
            ViewBag.DetailModel = detailModel;

            var customerServices = CustomerServiceApplication.GetMobileCustomerServiceAndMQ(market.ShopId);
            ViewBag.CustomerServices = customerServices;

            //统计商品浏览量、店铺浏览人数
            StatisticApplication.StatisticVisitCount(product.Id, product.ShopId);

            model.IsSaleCountOnOff = SiteSettingApplication.SiteSettings.ProductSaleCountOnOff == 1;                                          //是否显示销量
            model.SaleCount        = saleCounts;                                                                                              //销量
            model.FreightTemplate  = FreightTemplateApplication.GetFreightTemplate(product.FreightTemplateId);
            model.Freight          = FreightTemplateApplication.GetFreightStr(market.ProductId, model.FreightTemplate, CurrentUser, product); //运费或免运费
            model.StockAll         = market.Quantity;

            return(View(model));
        }
Esempio n. 19
0
        public object GetShopBranchs(long shopId, bool getParent, string skuIds, string counts, int page, int rows, long shippingAddressId, long regionId)
        {
            string[] _skuIds = skuIds.Split(',');
            int[] _counts = counts.Split(',').Select(p => Mall.Core.Helper.TypeHelper.ObjectToInt(p)).ToArray();

            var shippingAddressInfo = ShippingAddressApplication.GetUserShippingAddress(shippingAddressId);
            int streetId = 0, districtId = 0;//收货地址的街道、区域

            var query = new ShopBranchQuery()
            {
                ShopId = shopId,
                PageNo = page,
                PageSize = rows,
                Status = CommonModel.ShopBranchStatus.Normal,
                ShopBranchProductStatus = ShopBranchSkuStatus.Normal
            };
            if (shippingAddressInfo != null)
            {
                query.FromLatLng = string.Format("{0},{1}", shippingAddressInfo.Latitude, shippingAddressInfo.Longitude);//需要收货地址的经纬度
                streetId = shippingAddressInfo.RegionId;
                var parentAreaInfo = RegionApplication.GetRegion(shippingAddressInfo.RegionId, Region.RegionLevel.Town);//判断当前区域是否为第四级
                if (parentAreaInfo != null && parentAreaInfo.ParentId > 0) districtId = parentAreaInfo.ParentId;
                else { districtId = streetId; streetId = 0; }
            }
            bool hasLatLng = false;
            if (!string.IsNullOrWhiteSpace(query.FromLatLng)) hasLatLng = query.FromLatLng.Split(',').Length == 2;

            var region = RegionApplication.GetRegion(regionId, getParent ? CommonModel.Region.RegionLevel.City : CommonModel.Region.RegionLevel.County);//同城内门店
            if (region != null) query.AddressPath = region.GetIdPath();

            #region 3.0版本排序规则
            var skuInfos = ProductManagerApplication.GetSKUs(_skuIds);
            query.ProductIds = skuInfos.Select(p => p.ProductId).ToArray();
            var data = ShopBranchApplication.GetShopBranchsAll(query);
            var shopBranchSkus = ShopBranchApplication.GetSkus(shopId, data.Models.Select(p => p.Id).ToList());//获取该商家下具有订单内所有商品的门店状态正常数据,不考虑库存
            data.Models.ForEach(p =>
            {
                p.Enabled = skuInfos.All(skuInfo => shopBranchSkus.Any(sbSku => sbSku.ShopBranchId == p.Id && sbSku.Stock >= _counts[skuInfos.IndexOf(skuInfo)] && sbSku.SkuId == skuInfo.Id));
            });

            List<Mall.DTO.ShopBranch> newList = new List<Mall.DTO.ShopBranch>();
            List<long> fillterIds = new List<long>();
            var currentList = data.Models.Where(p => hasLatLng && p.Enabled && (p.Latitude > 0 && p.Longitude > 0)).OrderBy(p => p.Distance).ToList();
            if (currentList != null && currentList.Count() > 0)
            {
                fillterIds.AddRange(currentList.Select(p => p.Id));
                newList.AddRange(currentList);
            }
            var currentList2 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains(CommonConst.ADDRESS_PATH_SPLIT + streetId + CommonConst.ADDRESS_PATH_SPLIT)).ToList();
            if (currentList2 != null && currentList2.Count() > 0)
            {
                fillterIds.AddRange(currentList2.Select(p => p.Id));
                newList.AddRange(currentList2);
            }
            var currentList3 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled && p.AddressPath.Contains(CommonConst.ADDRESS_PATH_SPLIT + districtId + CommonConst.ADDRESS_PATH_SPLIT)).ToList();
            if (currentList3 != null && currentList3.Count() > 0)
            {
                fillterIds.AddRange(currentList3.Select(p => p.Id));
                newList.AddRange(currentList3);
            }
            var currentList4 = data.Models.Where(p => !fillterIds.Contains(p.Id) && p.Enabled).ToList();//非同街、非同区,但一定会同市
            if (currentList4 != null && currentList4.Count() > 0)
            {
                fillterIds.AddRange(currentList4.Select(p => p.Id));
                newList.AddRange(currentList4);
            }
            var currentList5 = data.Models.Where(p => !fillterIds.Contains(p.Id)).ToList();//库存不足的排最后
            if (currentList5 != null && currentList5.Count() > 0)
            {
                newList.AddRange(currentList5);
            }
            if (newList.Count() != data.Models.Count())//如果新组合的数据与原数据数量不一致
            {
                return new
                {
                    success = false
                };
            }
            var needDistance = false;
            if (shippingAddressInfo != null && shippingAddressInfo.Latitude!=0 && shippingAddressInfo.Longitude!=0)
            {
                needDistance = true;
            }
            var storeList = newList.Select(sb =>
            {
                return new
                {
                    ContactUser = sb.ContactUser,
                    ContactPhone = sb.ContactPhone,
                    AddressDetail = sb.AddressDetail,
                    ShopBranchName = sb.ShopBranchName,
                    Id = sb.Id,
                    Enabled = sb.Enabled,
                    Distance = needDistance ? RegionApplication.GetDistance(sb.Latitude, sb.Longitude, shippingAddressInfo.Latitude, shippingAddressInfo.Longitude) : 0
                };
            });

            #endregion

            var result = new
            {
                success = true,
                StoreList = storeList
            };
            return result;
        }
Esempio n. 20
0
        /// <summary>
        /// 商品信息转换
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private product_item_model ProductInfoMapChange(Entities.ProductInfo data)
        {
            var prodata = data;

            if (prodata == null)
            {
                throw new MallApiException(OpenApiErrorCode.Product_Not_Exists, "num_iid");
            }
            product_item_model result = new product_item_model();

            #region 装配信息
            result.num_iid    = (int)prodata.Id;
            result.outer_id   = prodata.ProductCode;
            result.brand_id   = (int)prodata.BrandId;
            result.brand_name = prodata.BrandName;
            result.cid        = (int)prodata.CategoryId;
            result.type_id    = (int)prodata.TypeId;

            var category = CategoryApplication.GetCategory(prodata.CategoryId);
            var desc     = ProductManagerApplication.GetProductDescription(prodata.Id);
            if (category != null)
            {
                result.cat_name = category.Name;
                var type = TypeApplication.GetType(category.TypeId);
                if (type != null)
                {
                    result.type_name = type.Name;
                }
            }
            result.title            = prodata.ProductName.Trim();
            result.list_time        = prodata.AddedDate;
            result.modified         = prodata.AddedDate;
            result.display_sequence = (int)prodata.DisplaySequence;
            result.sold_quantity    = (int)prodata.SaleCounts;
            result.desc             = desc.Description;
            result.wap_desc         = desc.MobileDescription;
            result.pic_url.Add(System.IO.Path.Combine(OpenAPIHelper.HostUrl, prodata.GetImage(ImageSize.Size_350, 1)));
            ProductStatus ps = GetProductStatus(prodata);
            result.approve_status = ps.ToString();

            #region 商品属性填充
            var prodAttrs      = ProductManagerApplication.GetProductAttributes(prodata.Id);
            var prodAttrids    = prodAttrs.Select(d => d.AttributeId).ToList();
            var prodAttrValues = _iTypeService.GetAttributeValues(prodAttrids);
            result.props_name = "";
            if (prodAttrids.Count > 0)
            {
                List <string> propslst    = new List <string>();
                List <string> propsvallst = new List <string>();
                foreach (var curattid in prodAttrids)
                {
                    var item = prodAttrs.FirstOrDefault(d => d.AttributeId == curattid);
                    propsvallst.Clear();
                    var attribute = _iTypeService.GetAttribute(item.AttributeId);
                    var values    = prodAttrValues.Where(p => p.AttributeId == curattid);
                    foreach (var attrV in values)
                    {
                        if (prodAttrs.Any(p => p.ValueId == attrV.Id))
                        {
                            propsvallst.Add(attrV.Value);
                        }
                    }
                    propslst.Add(attribute.Name + "#cln#[" + string.Join(",", propsvallst.ToArray()) + "]");
                }
                result.props_name = string.Join("#scln#", propslst.ToArray());
            }
            #endregion

            #region  发货地区

            var prolocid = FreightTemplateApplication.GetFreightTemplate(prodata.FreightTemplateId).SourceAddress;
            result.location = "";

            var locpath = _iRegionService.GetFullName(prolocid, ",");
            result.location = "{'city':'#c#', 'state':'#p#'}";
            if (!string.IsNullOrWhiteSpace(locpath))
            {
                var _tmparr = locpath.Split(',');
                result.location = result.location.Replace("#p#", _tmparr[0]);
                if (_tmparr.Length > 1)
                {
                    result.location = result.location.Replace("#c#", _tmparr[1]);
                }
                else
                {
                    result.location = result.location.Replace("#c#", "");
                }
            }

            #endregion

            #region SKUS

            Entities.TypeInfo typeInfo     = _iTypeService.GetType(data.TypeId);
            string            colorAlias   = (typeInfo == null || string.IsNullOrEmpty(typeInfo.ColorAlias)) ? SpecificationType.Color.ToDescription() : typeInfo.ColorAlias;
            string            sizeAlias    = (typeInfo == null || string.IsNullOrEmpty(typeInfo.SizeAlias)) ? SpecificationType.Size.ToDescription() : typeInfo.SizeAlias;
            string            versionAlias = (typeInfo == null || string.IsNullOrEmpty(typeInfo.VersionAlias)) ? SpecificationType.Version.ToDescription() : typeInfo.VersionAlias;
            if (prodata != null)
            {
                colorAlias   = !string.IsNullOrWhiteSpace(prodata.ColorAlias) ? prodata.ColorAlias : colorAlias;
                sizeAlias    = !string.IsNullOrWhiteSpace(prodata.SizeAlias) ? prodata.SizeAlias : sizeAlias;
                versionAlias = !string.IsNullOrWhiteSpace(prodata.VersionAlias) ? prodata.VersionAlias : versionAlias;
            }
            result.skus = new List <product_sku_model>();
            var skus = ProductManagerApplication.GetSKUs(prodata.Id);
            foreach (var item in skus)
            {
                product_sku_model skudata = new product_sku_model();
                skudata.sku_id       = item.Id;
                skudata.outer_sku_id = item.Sku;
                skudata.price        = item.SalePrice;
                skudata.quantity     = (int)item.Stock;
                //skudata.sku_properties_name = "颜色:" + item.Color + "尺寸:" + item.Size + "版本:" + item.Version;
                skudata.sku_properties_name = colorAlias + ":" + item.Color + " " + sizeAlias + ":" + item.Size + " " + versionAlias + ":" + item.Version;
                string sku_properties_name = item.Color + " " + item.Size + " " + item.Version;
                if (string.IsNullOrWhiteSpace(sku_properties_name))
                {
                    skudata.sku_properties_name = "";
                }
                if (!string.IsNullOrWhiteSpace(skudata.sku_properties_name))
                {
                    result.skus.Add(skudata);
                }
            }
            #endregion

            #endregion

            return(result);
        }