Exemplo n.º 1
0
        public static void UpdataOldDataInCommodityCategory()
        {
            int            pageIndex      = 1;
            int            pageSize       = 1000;
            ContextSession contextSession = ContextFactory.CurrentThreadContext;
            var            list           = CommodityCategory.ObjectSet().Select(t => t).OrderBy(t => t.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            while (list.Count == pageSize)
            {
                foreach (var item in list)
                {
                    item.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(item.AppId);
                    item.ModifiedOn  = DateTime.Now;
                    item.EntityState = System.Data.EntityState.Modified;
                }
                contextSession.SaveChanges();
                pageIndex++;
                list = CommodityCategory.ObjectSet().Select(t => t).OrderBy(t => t.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            }
            if (list.Count > 0)
            {
                foreach (var item in list)
                {
                    item.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(item.AppId);
                    item.ModifiedOn  = DateTime.Now;
                    item.EntityState = System.Data.EntityState.Modified;
                }
                contextSession.SaveChanges();
            }
        }
Exemplo n.º 2
0
        public CommodityCategoryDTO GetCommodityCategory(Guid appId, Guid commodityId)
        {
            var key = "CommodityCategory:AI_CI:" + appId.ToString() + commodityId.ToString();
            //var data = GlobalCacheWrapper.GetDataCache(key, Consts.CacheSetting) as CommodityCategoryDTO;
            var data = RedisHelper.Get <CommodityCategoryDTO>(key);

            if (data == null)
            {
                var sdata = CommodityCategory.ObjectSet().FirstOrDefault(t => t.CommodityId == commodityId && t.AppId == appId);
                if (sdata == null)
                {
                    data = new CommodityCategoryDTO {
                        Id = Guid.Empty
                    };
                }
                else
                {
                    data = sdata.ToEntityData();
                }
                //GlobalCacheWrapper.AddCache(key, data, TimeSpan.FromMinutes(30), CacheTypeEnum.redis, Consts.CacheSetting);
                RedisHelper.Set(key, data, TimeSpan.FromMinutes(30));
                LogHelper.Info("GetCommodityCategory from DB......");
            }
            if (data.Id == Guid.Empty)
            {
                return(null);
            }
            return(data);
        }
Exemplo n.º 3
0
        public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CategoryDTO> GetCategoryBycommodityId(Guid commodityId)
        {
            //IQueryable<CommodityCategory> commodityCategory = CommodityCategory.ObjectSet().Where(n => n.CommodityId == commodityId);

            var query = from data in CommodityCategory.ObjectSet()
                        join data1 in Category.ObjectSet() on data.CategoryId equals data1.Id
                        where data.CommodityId == commodityId
                        select data1;
            var result = from c in query
                         select new CategoryDTO
            {
                AppId        = c.AppId,
                Code         = c.Code,
                CurrentLevel = c.CurrentLevel,
                Id           = c.Id,
                IsDel        = c.IsDel,
                IsValidate   = c.IsValidate,
                IsValidated  = c.IsValidated,
                Name         = c.Name,
                ParentId     = c.ParentId,
                Sort         = c.Sort
            };

            return(result.ToList());
        }
Exemplo n.º 4
0
        /// <summary>
        /// 查询商品 非电商馆
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ResultDTO <List <ComdtyList4SelCDTO> > SearchCommodity2Ext(ComdtySearch4SelCDTO search)
        {
            string appName    = APPSV.GetAppName(search.AppId ?? Guid.Empty);
            var    comdtyList = from c in Commodity.ObjectSet()
                                where c.IsDel == false && c.State == 0 && c.AppId == search.AppId && c.CommodityType == 0
                                orderby c.Name
                                select new ComdtyList4SelCDTO
            {
                Id      = c.Id,
                Name    = c.Name,
                Pic     = c.PicturesPath,
                Price   = c.Price,
                AppId   = c.AppId,
                Stock   = c.Stock,
                AppName = appName
            };

            if (!string.IsNullOrEmpty(search.CommodityName))
            {
                comdtyList = comdtyList.Where(o => o.Name.Contains(search.CommodityName));
            }

            List <ComdtyList4SelCDTO> comdtyList4SelCdtos = new List <ComdtyList4SelCDTO>();

            foreach (var comdty in comdtyList)
            {
                //获取加入的分类名称
                var temp1 = (from scc in CommodityCategory.ObjectSet()
                             join sc in Category.ObjectSet() on scc.CategoryId equals sc.Id
                             where scc.CommodityId == comdty.Id && scc.IsDel == false && scc.AppId == comdty.AppId
                             orderby scc.MaxSort
                             select sc);
                var cnames = "";
                foreach (var category in temp1)
                {
                    cnames += category.Name + "<br>";
                }
                comdty.CommodityCategory = cnames;

                comdtyList4SelCdtos.Add(comdty);
            }

            ResultDTO <List <ComdtyList4SelCDTO> > retInfo = new ResultDTO <List <ComdtyList4SelCDTO> >
            {
                ResultCode = comdtyList4SelCdtos.Count(),
                Data       = comdtyList4SelCdtos.Skip((search.PageIndex - 1) * search.PageSize)
                             .Take(search.PageSize)
                             .ToList()
            };

            return(retInfo);
        }
Exemplo n.º 5
0
        public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CommodityCategoryDTO> GetCommodityCategoryByCategoryExt(Guid commodityId, int pageSize, int pageIndex)
        {
            var commodityCategory = CommodityCategory.ObjectSet().Where(n => n.CommodityId == commodityId);
            var result            = from c in commodityCategory
                                    select new CommodityCategoryDTO
            {
                CategoryId  = c.CategoryId,
                Code        = c.Code,
                CommodityId = c.CommodityId,
                Id          = c.Id,
                Name        = c.Name
            };

            return(result.ToList());
        }
Exemplo n.º 6
0
        /// <summary>
        /// 查询所有商品分类
        /// </summary>
        /// <param name="appId">APPID</param>
        /// <returns></returns>
        public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CommodityCategoryDTO> GetAllCommodityCategoryExt()
        {
            var commodityCategoryList = CommodityCategory.ObjectSet();
            var result = from c in commodityCategoryList
                         select new CommodityCategoryDTO
            {
                CategoryId  = c.CategoryId,
                Code        = c.Code,
                CommodityId = c.CommodityId,
                Id          = c.Id,
                Name        = c.Name,
                IsValidate  = c.IsValid,
                IsValidated = c.IsValidated
            };

            return(result.ToList());
        }
Exemplo n.º 7
0
        /// <summary>
        /// 根据AppId和CommodityId查询商品分类名称
        /// </summary>
        /// <param name="commodityId"></param>
        /// <param name="appId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public System.Collections.Generic.List <CommodityCategoryDTO> GetAllCommodityCategory(Guid commodityId, Guid appId, int pageSize, int pageIndex)
        {
            var commodityCategory = CommodityCategory.ObjectSet().Where(n => n.CommodityId == commodityId && n.AppId == appId);
            var result            = from c in commodityCategory
                                    join s in Category.ObjectSet() on c.CategoryId equals s.Id
                                    select new CommodityCategoryDTO
            {
                CategoryId  = s.Id,
                Name        = s.Name,
                AppId       = c.AppId,
                Code        = c.Code,
                Id          = c.Id,
                IsDel       = c.IsDel,
                IsValidate  = c.IsValidate,
                IsValidated = c.IsValidated
            };

            return(result.ToList());
        }
Exemplo n.º 8
0
        /// <summary>
        /// 增加商品查询条件---分类、毛利率区间,价格区间
        /// </summary>
        /// <param name="input">输入查询实体</param>
        /// <param name="commodityQuery">查询对象</param>
        /// <returns></returns>
        private static IQueryable <Commodity> AddCommoditySelectWhere(PresentPromotionCommoditySearchDTO input, IQueryable <Commodity> commodityQuery, List <Guid> hasAddCommodityIds)
        {
            try
            {
                //根据分类查询
                if (input.Categorys != null)
                {
                    List <Guid> listId = GetRecursiveCategoryId(input);


                    commodityQuery = (from scc in CommodityCategory.ObjectSet()
                                      join c in Commodity.ObjectSet() on scc.CommodityId equals c.Id
                                      where c.AppId == input.AppId && c.IsDel == false && c.State == 0 && c.CommodityType == 0 &&
                                      listId.Contains(scc.CategoryId) && !hasAddCommodityIds.Contains(c.Id)
                                      orderby scc.MaxSort
                                      select c).Distinct();
                }
                //毛利率区间
                if (!string.IsNullOrWhiteSpace(input.MinInterestRate) && !string.IsNullOrWhiteSpace(input.MaxInterestRate))
                {
                    //4、商品毛利率=(销售价-进货价)/销售价x100%
                    //获取商品信息,循环计算毛利率
                    decimal minInterestRate, maxInterestRate = 0;
                    decimal.TryParse(input.MinInterestRate, out minInterestRate);
                    decimal.TryParse(input.MaxInterestRate, out maxInterestRate);
                    commodityQuery = commodityQuery.Where(p => (((p.Price - p.CostPrice) / p.Price) * 100) >= minInterestRate && (((p.Price - p.CostPrice) / p.Price) * 100) <= maxInterestRate);
                }
                //价格区间
                if (!string.IsNullOrWhiteSpace(input.MinPrice) && !string.IsNullOrWhiteSpace(input.MaxPrice))
                {
                    decimal minPrice, maxPrice = 0;
                    decimal.TryParse(input.MinPrice, out minPrice);
                    decimal.TryParse(input.MaxPrice, out maxPrice);
                    commodityQuery = commodityQuery.Where(p => p.Price >= minPrice && p.Price <= maxPrice);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(string.Format("CommoditySVExt.AddCommoditySelectWhere:{0}", ex.ToString()));
            }
            return(commodityQuery);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 获取商品列表(平台获取平台商品、店铺获取店铺商品)
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public Jinher.AMP.BTP.Deploy.CustomDTO.ComdtyListResultCDTO GetCommodityListV2Ext(CommodityListSearchDTO search)
        {
            Jinher.AMP.BTP.Deploy.CustomDTO.ComdtyListResultCDTO comdtyListResultCDTO = new Jinher.AMP.BTP.Deploy.CustomDTO.ComdtyListResultCDTO();
            try
            {
                if (search == null || search.PageSize <= 0 || search.PageIndex <= 0)
                {
                    comdtyListResultCDTO.isSuccess   = false;
                    comdtyListResultCDTO.Code        = 1;
                    comdtyListResultCDTO.Message     = "参数不能为空";
                    comdtyListResultCDTO.realCount   = 0;
                    comdtyListResultCDTO.comdtyList  = null;
                    comdtyListResultCDTO.appInfoList = null;
                    return(comdtyListResultCDTO);
                }
                if (!search.AppId.HasValue || search.AppId == Guid.Empty)
                {
                    comdtyListResultCDTO.isSuccess   = false;
                    comdtyListResultCDTO.Code        = 1;
                    comdtyListResultCDTO.Message     = "参数不能为空";
                    comdtyListResultCDTO.realCount   = 0;
                    comdtyListResultCDTO.comdtyList  = null;
                    comdtyListResultCDTO.appInfoList = null;
                    return(comdtyListResultCDTO);
                }

                DateTime now = DateTime.Now;

                var appId = search.AppId.Value;

                IQueryable <Commodity> ocommodityList;
                //用于存储临加入真实价格后的Commodity信息
                IQueryable <TempCommodity> tempOcommodityList;
                //根据是否平台区分
                bool isPavilion = Jinher.AMP.BTP.TPS.ZPHSV.Instance.IsAppPavilion(search.AppId.Value);
                if (isPavilion)
                {
                    tempOcommodityList = (from cs in CommodityCategory.ObjectSet()
                                          join cate in Category.ObjectSet() on cs.CategoryId equals cate.Id
                                          join c in Commodity.ObjectSet() on cs.CommodityId equals c.Id
                                          join pro in
                                          (
                                              from query in TodayPromotion.ObjectSet()
                                              where
                                              (query.PromotionType != 3 &&
                                               (query.StartTime <= now || query.PresellStartTime <= now) &&
                                               query.EndTime > now)
                                              select query
                                          ) on c.Id equals pro.CommodityId
                                          into todayPros
                                          from promotion in todayPros.DefaultIfEmpty()
                                          where cs.AppId == appId && c.IsDel == false && c.State == 0 && c.CommodityType == 0 && !cate.IsDel
                                          orderby c.Salesvolume descending, c.SubTime descending
                                          select new TempCommodity
                    {
                        Com = c,
                        newPrice = (promotion.Id == null) ? c.Price : (promotion.DiscountPrice > 0 ? promotion.DiscountPrice : c.Price * promotion.Intensity / 10)
                    });
                }
                else
                {
                    tempOcommodityList = (from c in Commodity.ObjectSet()
                                          join pro in
                                          (
                                              from query in TodayPromotion.ObjectSet()
                                              where (query.PromotionType != 3 && (query.StartTime <= now || query.PresellStartTime <= now) && query.EndTime > now)
                                              select query
                                          ) on c.Id equals pro.CommodityId
                                          into todayPros
                                          from promotion in todayPros.DefaultIfEmpty()

                                          where c.AppId == appId && c.IsDel == false && c.State == 0 && c.CommodityType == 0
                                          select new TempCommodity
                    {
                        Com = c,
                        newPrice = (promotion.Id == null) ? c.Price : (promotion.DiscountPrice > 0 ? promotion.DiscountPrice : c.Price * promotion.Intensity / 10)
                    });
                }

                if (search.MinPrice.HasValue && search.MinPrice != 0)
                {
                    tempOcommodityList = tempOcommodityList.Where(c => c.newPrice >= search.MinPrice);
                }
                if (search.MaxPrice.HasValue && search.MaxPrice != 0)
                {
                    tempOcommodityList = tempOcommodityList.Where(c => c.newPrice <= search.MaxPrice);
                }

                ocommodityList = tempOcommodityList.Select(c => c.Com).Distinct();


                if (search.IsHasStock)
                {
                    ocommodityList = ocommodityList.Where(c => c.Stock > 0);
                }

                if (!ProvinceCityHelper.IsTheWholeCountry(search.areaCode))
                {
                    var province = ProvinceCityHelper.GetProvinceByAreaCode(search.areaCode);
                    var city     = ProvinceCityHelper.GetCityByAreaCode(search.areaCode);
                    if (province != null && city != null)
                    {
                        if (province.AreaCode == city.AreaCode)
                        {
                            ocommodityList = ocommodityList.Where(c => c.SaleAreas == null || c.SaleAreas == "" || c.SaleAreas == ProvinceCityHelper.CountryCode || c.SaleAreas.Contains(province.AreaCode));
                        }
                        else
                        {
                            ocommodityList = ocommodityList.Where(c => c.SaleAreas == null || c.SaleAreas == "" || c.SaleAreas == ProvinceCityHelper.CountryCode || c.SaleAreas.Contains(province.AreaCode) || c.SaleAreas.Contains(city.AreaCode));
                        }
                    }
                }
                var commoditiesQuery         = from c in ocommodityList select c;
                List <Commodity> commodities = null;
                List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityListCDTO> commodityList = null;

                comdtyListResultCDTO.realCount = commoditiesQuery.Count();
                if (isPavilion)
                {
                    commodities = (from c in commoditiesQuery
                                   orderby c.Salesvolume descending, c.SubTime descending
                                   select c).Skip((search.PageIndex - 1) * search.PageSize).Take(search.PageSize).ToList();
                }
                else
                {
                    commodities = (from c in commoditiesQuery
                                   orderby c.SortValue
                                   select c).Skip((search.PageIndex - 1) * search.PageSize).Take(search.PageSize).ToList();
                }

                //commodities = commoditiesQuery.Skip((search.PageIndex - 1) * search.PageSize).Take(search.PageSize).ToList();


                if (!commodities.Any())
                {
                    return(comdtyListResultCDTO);
                }

                commodityList = commodities.Select(c => new Jinher.AMP.BTP.Deploy.CustomDTO.CommodityListCDTO
                {
                    Id               = c.Id,
                    Pic              = c.PicturesPath,
                    Price            = c.Price,
                    State            = c.State,
                    Stock            = c.Stock,
                    Name             = c.Name,
                    MarketPrice      = c.MarketPrice,
                    AppId            = c.AppId,
                    IsEnableSelfTake = c.IsEnableSelfTake,
                    ComAttribute     = c.ComAttribute,
                    ComAttrType      = (c.ComAttribute == "[]" || c.ComAttribute == null) ? 1 : 3
                }).ToList();

                var appList = commodities.Select(c => c.AppId).Distinct().ToList();

                #region 众筹
                if (CustomConfig.CrowdfundingFlag)
                {
                    var crowdFundingApps = Crowdfunding.ObjectSet().Where(c => c.StartTime < now && c.State == 0 && appList.Contains(c.AppId)).Select(c => c.AppId).ToList();
                    if (crowdFundingApps.Any())
                    {
                        for (int i = 0; i < commodityList.Count; i++)
                        {
                            if (crowdFundingApps.Any(c => c == commodityList[i].AppId))
                            {
                                commodityList[i].IsActiveCrowdfunding = true;
                            }
                        }
                    }
                }
                #endregion

                var commodityIds = commodityList.Select(c => c.Id).Distinct().ToList();
                var comStockList = CommodityStock.ObjectSet()
                                   .Where(c => commodityIds.Contains(c.CommodityId))
                                   .Select(
                    c =>
                    new Deploy.CommodityStockDTO
                {
                    Id          = c.Id,
                    CommodityId = c.CommodityId,
                    Price       = c.Price,
                    MarketPrice = c.MarketPrice
                })
                                   .ToList();
                var todayPromotions = TodayPromotion.GetCurrentPromotionsWithPresell(commodityIds);

                foreach (var commodity in commodityList)
                {
                    commodity.IsMultAttribute = Commodity.CheckComMultAttribute(commodity.ComAttribute);
                    List <Deploy.CommodityStockDTO> comStocks = comStockList.Where(c => c.CommodityId == commodity.Id).ToList();

                    var todayPromotion = todayPromotions.FirstOrDefault(c => c.CommodityId == commodity.Id && c.PromotionType != 3);

                    if (todayPromotion != null)
                    {
                        commodity.LimitBuyEach         = todayPromotion.LimitBuyEach ?? -1;
                        commodity.LimitBuyTotal        = todayPromotion.LimitBuyTotal ?? -1;
                        commodity.SurplusLimitBuyTotal = todayPromotion.SurplusLimitBuyTotal ?? 0;
                        commodity.PromotionType        = todayPromotion.PromotionType;
                        if (todayPromotion.DiscountPrice > -1)
                        {
                            commodity.DiscountPrice = Convert.ToDecimal(todayPromotion.DiscountPrice);
                            commodity.Intensity     = 10;
                        }
                        else
                        {
                            commodity.DiscountPrice = -1;
                            commodity.Intensity     = todayPromotion.Intensity;
                        }
                    }
                    else
                    {
                        commodity.DiscountPrice        = -1;
                        commodity.Intensity            = 10;
                        commodity.LimitBuyEach         = -1;
                        commodity.LimitBuyTotal        = -1;
                        commodity.SurplusLimitBuyTotal = -1;
                        commodity.PromotionType        = 9999;
                    }
                    buildShowPrice(commodity, comStocks, todayPromotion);
                }

                try
                {
                    var apps = APPSV.GetAppListByIds(appList);
                    if (apps != null && apps.Any())
                    {
                        comdtyListResultCDTO.appInfoList = new List <ComdtyAppInfoCDTO>();
                        foreach (var appInfo in apps)
                        {
                            comdtyListResultCDTO.appInfoList.Add(new ComdtyAppInfoCDTO
                            {
                                appId   = appInfo.AppId,
                                appName = appInfo.AppName,
                                icon    = appInfo.AppIcon
                            });
                        }

                        foreach (var commodityListCdto in commodityList)
                        {
                            var appInfo = apps.FirstOrDefault(c => c.AppId == commodityListCdto.AppId);
                            if (appInfo != null)
                            {
                                commodityListCdto.AppName = appInfo.AppName;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(string.Format("AppSetSV.GetCommodityListExt,获取app名称错误。appId:{0}", appId), ex);
                }

                comdtyListResultCDTO.comdtyList = commodityList;
            }
            catch (Exception ex)
            {
                LogHelper.Error(string.Format("商品列表查询错误,CommoditySV.GetCommodityListV2Ext。search:{0}", JsonHelper.JsonSerializer(search)), ex);
                comdtyListResultCDTO.isSuccess   = false;
                comdtyListResultCDTO.Code        = -1;
                comdtyListResultCDTO.Message     = "Error";
                comdtyListResultCDTO.realCount   = 0;
                comdtyListResultCDTO.comdtyList  = null;
                comdtyListResultCDTO.appInfoList = null;
                return(comdtyListResultCDTO);
            }
            comdtyListResultCDTO.isSuccess = true;
            comdtyListResultCDTO.Code      = 0;
            comdtyListResultCDTO.Message   = "Success";
            return(comdtyListResultCDTO);
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取当前商品结算列表
        /// </summary>
        /// <param name="id">商品结算价检索类</param>
        /// <returns>结果</returns>
        public List <Jinher.AMP.BTP.Deploy.CustomDTO.SettlingAccountVM> GetNowSettlingAccountExt(SettlingAccountSearchDTO search, out int rowCount)
        {
            List <Jinher.AMP.BTP.Deploy.CustomDTO.SettlingAccountVM> comcalist = new List <Jinher.AMP.BTP.Deploy.CustomDTO.SettlingAccountVM>();

            if (search == null || search.appId == Guid.Empty || search.pageIndex < 1 || search.pageSize < 1)
            {
                rowCount = 0;
                return(comcalist);
            }

            DateTime now = DateTime.Now;

            //appid
            var query = Commodity.ObjectSet().Where(n => n.IsDel.Equals(false) && n.AppId.Equals(search.appId) && n.State == 0 && n.CommodityType == 0);


            //commodityName
            if (!string.IsNullOrWhiteSpace(search.commodityName))
            {
                query = query.Where(n => n.Name.Contains(search.commodityName));
            }

            //commodityCategory
            if (!string.IsNullOrWhiteSpace(search.commodityCategory))
            {
                string[]    commodityCategoryID = search.commodityCategory.Split(',');
                List <Guid> idlist = new List <Guid>();
                foreach (string commodityCategoryid in commodityCategoryID)
                {
                    if (!string.IsNullOrEmpty(commodityCategoryid))
                    {
                        idlist.Add(new Guid(commodityCategoryid));
                    }
                }
                query = from n in query
                        join m in CommodityCategory.ObjectSet() on n.Id equals m.CommodityId
                        where idlist.Contains(m.CategoryId)
                        select n;
            }

            query    = query.Distinct();
            rowCount = query.Count();
            query    = query.OrderBy(n => n.SortValue).ThenByDescending(n => n.SubTime).Skip((search.pageIndex - 1) * search.pageSize).Take(search.pageSize);

            var commodityIds = query.Select(t => t.Id).ToList();

            //取出厂家结算价
            var settlingAccountQuery = (
                from s in SettlingAccount.ObjectSet()
                where commodityIds.Contains(s.CommodityId) && s.EffectiveTime < now
                select new
            {
                Id = s.Id,
                CommodityId = s.CommodityId,
                ManufacturerClearingPrice = s.ManufacturerClearingPrice,
                AppId = s.AppId,
                Effectable = s.Effectable,
                EffectiveTime = s.EffectiveTime,
                SubId = s.SubId,
                SubName = s.SubName,
                SubTime = s.SubTime,
                ModifiedOn = s.ModifiedOn,
                UserCode = s.UserCode
            })
                                       .GroupBy(t => t.CommodityId).ToDictionary(x => x.Key, y => y.OrderByDescending(c => c.EffectiveTime).First());


            //取出商品的销售价
            var compromoList = (from t in TodayPromotion.ObjectSet()
                                where commodityIds.Contains(t.CommodityId) && t.EndTime > now && t.StartTime < now
                                select new
            {
                SurplusLimitBuyTotal = t.SurplusLimitBuyTotal,
                ComdityID = t.CommodityId,
                LimitBuyEach = t.LimitBuyEach,
                PromotionId = t.PromotionId,
                ID = t.Id,
                LimitBuyTotal = t.LimitBuyTotal,
                Intensity = t.Intensity,
                DiscountPrice = t.DiscountPrice,
                PromotionType = t.PromotionType,
                ChannelId = t.ChannelId,
                OutsideId = t.OutsideId
            }).GroupBy(c => c.ComdityID).ToDictionary(x => x.Key, y => y.OrderByDescending(c => c.PromotionType).First());

            var comList = query.ToList();

            int?     intNull      = null;
            DateTime?dateTimeNull = null;
            Guid?    guidNull     = null;
            Decimal? decimalNull  = null;

            foreach (var com in comList)
            {
                var settlingAccountTmp = settlingAccountQuery.ContainsKey(com.Id) ? settlingAccountQuery[com.Id] : null;

                decimal Intensity     = 10;
                decimal?DiscountPrice = -1;
                decimal realPrice     = com.Price;
                if (compromoList.ContainsKey(com.Id))
                {
                    if (compromoList[com.Id].DiscountPrice > -1)
                    {
                        Intensity     = 10;
                        DiscountPrice = compromoList[com.Id].DiscountPrice == null?-1:compromoList[com.Id].DiscountPrice;
                    }
                    else
                    {
                        Intensity     = compromoList[com.Id].Intensity == null ? 10 : compromoList[com.Id].Intensity;
                        DiscountPrice = -1;
                    }

                    realPrice = (DiscountPrice > -1)
                                     ? DiscountPrice.Value
                                     : decimal.Round((com.Price * Intensity / 10), 2, MidpointRounding.AwayFromZero);
                }

                Jinher.AMP.BTP.Deploy.CustomDTO.SettlingAccountVM settingAccount = new Jinher.AMP.BTP.Deploy.CustomDTO.SettlingAccountVM()
                {
                    AppId                     = com.AppId,
                    CommodityCode             = com.No_Code,
                    CommodityId               = com.Id,
                    CommodityName             = com.Name,
                    Effectable                = settlingAccountTmp == null ? intNull : settlingAccountTmp.Effectable,
                    EffectiveTime             = settlingAccountTmp == null ? dateTimeNull : settlingAccountTmp.EffectiveTime,
                    Id                        = settlingAccountTmp == null ? guidNull : settlingAccountTmp.Id,
                    IsEnableSelfTake          = com.IsEnableSelfTake,
                    UserCode                  = settlingAccountTmp == null ? null : settlingAccountTmp.UserCode,
                    ManufacturerClearingPrice = settlingAccountTmp == null ? decimalNull : settlingAccountTmp.ManufacturerClearingPrice,
                    ModifiedOn                = settlingAccountTmp == null ? dateTimeNull : settlingAccountTmp.ModifiedOn,
                    PicturesPath              = com.PicturesPath,
                    SalePrice                 = realPrice,
                    SubId                     = settlingAccountTmp == null ? guidNull : settlingAccountTmp.SubId,
                    SubName                   = settlingAccountTmp == null ? null : settlingAccountTmp.SubName,
                    SubTime                   = settlingAccountTmp == null ? dateTimeNull : settlingAccountTmp.SubTime,
                };
                comcalist.Add(settingAccount);
            }

            return(comcalist);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 根据订单生成待结算项
        /// </summary>
        public static SettleAccountsDetails CreateSettleAccountDetails(ContextSession contextSession, CommodityOrder commodityOrder, MallApply mall, int?orderServiceState = null)
        {
            //LogHelper.Info("开始生成结算项,订单ID:" + commodityOrder.Id);

            var currentDate = DateTime.Now;

            // 1:商家,2:金和众销(给金和分的钱),3:商贸众销(给分享者分的钱),4:商贸众筹,5:推广主分成,6:应用主分成,7金和分润,8买家,9一级分销,10二级分销,11三级分销,12渠道推广,20:一级代理,21:二级代理
            //var payeeType = new List<int> { 3, 5, 9, 10, 11, 20, 21 };
            //var orderitemlist = OrderItem.ObjectSet().Where(n => n.CommodityOrderId == commodityOrder.Id).
            //    GroupJoin(OrderItemShare.ObjectSet().Where(s => payeeType.Contains(s.PayeeType)), o => o.Id, s => s.OrderItemId, (o, s) =>
            //        new { o.Id, o.Name, o.Number, o.RealPrice, o.CommodityId, o.ComCategoryId, Commission = s.Sum(_ => (decimal?)_.Commission) }).ToList();

            // 暂不计算推广佣金
            var orderitemlist = OrderItem.ObjectSet().Where(n => n.CommodityOrderId == commodityOrder.Id).Select(o =>
                                                                                                                 new { o.Id, o.Name, o.Number, o.RealPrice, o.CommodityId, o.ComCategoryId, o.CommodityAttributes }).ToList();
            bool isSetSettleAmount = true;
            List <SettleAccountsOrderItem> items = new List <SettleAccountsOrderItem>();
            var payTime = commodityOrder.PaymentTime.Value;

            foreach (var orderItem in orderitemlist)
            {
                // 结算单订单项
                SettleAccountsOrderItem saItem = new SettleAccountsOrderItem();
                saItem.Id                    = saItem.OrderItemId = orderItem.Id;
                saItem.ModifiedOn            = saItem.SubTime = currentDate;
                saItem.OrderId               = commodityOrder.Id;
                saItem.OrderItemRefundAmount = 0;               // 暂无单品退货
                saItem.OrderItemPromotionCommissionAmount = 0M; // orderItem.Commission ?? 0M;
                saItem.OrderItemName   = orderItem.Name;
                saItem.OrderItemNumber = orderItem.Number;
                saItem.OrderItemPrice  = orderItem.RealPrice.Value;
                // 自营他配
                if (mall.Type == 0)
                {
                    var commoditySettleAmount = CommoditySettleAmount.ObjectSet()
                                                .Where(c => c.CommodityId == orderItem.CommodityId && c.EffectiveTime < payTime)
                                                .OrderByDescending(c => c.SubTime)
                                                .ThenByDescending(c => c.EffectiveTime)
                                                .FirstOrDefault();
                    if (commoditySettleAmount == null)
                    {
                        // 未设置结算价,暂不结算
                        //LogHelper.Info("开始生成结算项,订单ID:" + commodityOrder.Id + ",自营商家,未设置结算价,商品ID:" + orderItem.CommodityId);
                        return(null);
                    }
                    //LogHelper.Info("开始生成结算项,订单ID:" + commodityOrder.Id + ",自营商家,商品ID:" + orderItem.CommodityId + ",商品属性:" + orderItem.CommodityAttributes + ",结算价:" + commoditySettleAmount.CommodityAttrJson);

                    var saAttrs = JsonHelper.JsonDeserialize <List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityAttributePrice> >(commoditySettleAmount.CommodityAttrJson);
                    var attrs   = (orderItem.CommodityAttributes ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (attrs.Length == 0)
                    {
                        // 无属性
                        saItem.SettleAmount = saAttrs[0].SettlePrice.Value;
                    }
                    else if (attrs.Length == 1)
                    {
                        // 单属性
                        var settlePrice = saAttrs.Where(a => a.AttributeValue == attrs[0]).FirstOrDefault();
                        if (settlePrice == null)
                        {
                            LogHelper.Error("SettleAccountHelper.CreateSettleAccountDetails 生成结算单失败,结算价设置异常,商品ID:" + orderItem.CommodityId + ",商品属性:" + orderItem.CommodityAttributes + ",结算价ID:" + commoditySettleAmount.Id + ",结算价属性:" + commoditySettleAmount.CommodityAttrJson);
                            return(null);
                        }
                        saItem.SettleAmount = settlePrice.SettlePrice.Value;
                    }
                    else if (attrs.Length == 2)
                    {
                        // 双属性
                        var settlePrice = saAttrs.Where(a =>
                                                        (a.AttributeValue == attrs[0] && a.SecAttributeValue == attrs[1]) ||
                                                        (a.AttributeValue == attrs[1] && a.SecAttributeValue == attrs[0]))
                                          .FirstOrDefault();
                        if (settlePrice == null)
                        {
                            LogHelper.Error("SettleAccountHelper.CreateSettleAccountDetails 生成结算单失败,结算价设置异常,商品ID:" + orderItem.CommodityId + ",商品属性:" + orderItem.CommodityAttributes + ",结算价ID:" + commoditySettleAmount.Id + ",结算价属性:" + commoditySettleAmount.CommodityAttrJson);
                            return(null);
                        }
                        saItem.SettleAmount = settlePrice.SettlePrice.Value;
                    }
                    else
                    {
                        LogHelper.Error("SettleAccountHelper.CreateSettleAccountDetails 生成结算单失败,商品属性异常,商品ID:" + orderItem.CommodityId + ",商品属性:" + orderItem.CommodityAttributes);
                        return(null);
                    }
                    //orderItem.com
                }
                // 第三方
                else if (mall.Type == 1)
                {
                    // 查询商品易捷币抵用数量
                    var yjbInfo = YJBSV.GetOrderItemYJBInfo(commodityOrder.EsAppId.Value, commodityOrder.Id);
                    if (!yjbInfo.IsSuccess)
                    {
                        saItem.OrderItemYJBAmount = 0;
                    }
                    else
                    {
                        var currentCommodityYJBInfo = yjbInfo.Data.Items.Where(c => c.CommodityId == orderItem.CommodityId).FirstOrDefault();
                        if (currentCommodityYJBInfo != null && currentCommodityYJBInfo.IsMallYJB)
                        {
                            saItem.OrderItemYJBAmount = currentCommodityYJBInfo.InsteadCashAmount;
                        }
                    }

                    // 计算实际成交价



                    #region 计算商品佣金比例
                    // 获取佣金比例:按结算日期获取有效的(启用日期小于等于结算日期的最近一次设置的佣金比例)佣金比例【基础、类目、商品】;
                    saItem.BaseCommission = BaseCommission.ObjectSet().Join(MallApply.ObjectSet(),
                                                                            b => b.MallApplyId, m => m.Id, (b, m) => new { b.Commission, b.EffectiveTime, b.SubTime, m.AppId, m.EsAppId }).
                                            Where(t => t.EsAppId == commodityOrder.EsAppId && t.AppId == commodityOrder.AppId && t.EffectiveTime < payTime).
                                            OrderByDescending(t => t.SubTime).Select(t => (decimal?)t.Commission).FirstOrDefault();

                    // 查询当前商品的类目
                    List <Guid> categoryIds    = new List <Guid>();
                    var         tempCategories = CommodityCategory.ObjectSet().Where(c => c.AppId == commodityOrder.EsAppId && c.CommodityId == orderItem.CommodityId).Join(Category.ObjectSet(), cc => cc.CategoryId, c => c.Id, (cc, c) => new { c.Id, c.CurrentLevel, c.ParentId, cc.IsDel }).ToList();
                    foreach (var item in tempCategories)
                    {
                        if (item.IsDel.HasValue && item.IsDel.Value)
                        {
                            continue;
                        }
                        if (item.CurrentLevel == 3 || item.CurrentLevel == 4 || item.CurrentLevel == 5)
                        {
                            var lv2 = Category.FindByID(item.ParentId.Value);
                            if (item.CurrentLevel == 3)
                            {
                                categoryIds.Add(lv2.ParentId.Value);
                                continue;
                            }
                            var lv3 = Category.FindByID(lv2.ParentId.Value);
                            if (item.CurrentLevel == 4)
                            {
                                categoryIds.Add(lv3.ParentId.Value);
                                continue;
                            }
                            var lv4 = Category.FindByID(lv3.ParentId.Value);
                            categoryIds.Add(lv4.ParentId.Value);
                        }
                        else if (item.CurrentLevel == 2)
                        {
                            categoryIds.Add(item.ParentId.Value);
                        }
                        else if (item.CurrentLevel == 1)
                        {
                            categoryIds.Add(item.Id);
                        }
                    }

                    var commissions = CategoryCommission.ObjectSet().
                                      Join(MallApply.ObjectSet(), b => b.MallApplyId, m => m.Id,
                                           (b, m) => new { b.CategoryId, b.Commission, b.EffectiveTime, b.SubTime, m.AppId, m.EsAppId }).
                                      Where(t =>
                                            t.EsAppId == commodityOrder.EsAppId &&
                                            t.AppId == commodityOrder.AppId &&
                                            categoryIds.Contains(t.CategoryId) &&
                                            t.EffectiveTime < payTime).
                                      GroupBy(t => t.CategoryId).
                                      Select(group => group.OrderByDescending(g => g.SubTime).Select(g => g.Commission).FirstOrDefault()).
                                      ToList();
                    if (commissions.Count > 0)
                    {
                        saItem.CategoryCommission = commissions.Min();
                    }
                    saItem.CommodityCommission = CommodityCommission.ObjectSet().Join(MallApply.ObjectSet(),
                                                                                      b => b.MallApplyId, m => m.Id, (b, m) => new { b.CommodityId, b.Commission, b.EffectiveTime, b.SubTime, m.AppId, m.EsAppId }).
                                                 Where(t => t.EsAppId == commodityOrder.EsAppId && t.AppId == commodityOrder.AppId &&
                                                       t.CommodityId == orderItem.CommodityId && t.EffectiveTime < payTime).
                                                 OrderByDescending(t => t.SubTime).Select(t => (decimal?)t.Commission).FirstOrDefault();
                    #endregion

                    // 商城佣金计算公式:商品销售价*佣金比例【商品佣金优先,类目佣金其次、基础佣金最后,三选一计算】* 购买数量;
                    saItem.PromotionAmount = Math.Truncate(
                        (saItem.CommodityCommission.HasValue ? saItem.CommodityCommission.Value :
                         (saItem.CategoryCommission.HasValue ? saItem.CategoryCommission.Value :
                          (saItem.BaseCommission.HasValue ? saItem.BaseCommission.Value : 0)
                         )) * saItem.OrderItemPrice * saItem.OrderItemNumber) / 100;
                }

                saItem.EntityState = EntityState.Added;
                items.Add(saItem);
            }

            // 结算单订单详情
            SettleAccountsDetails sad = new SettleAccountsDetails();
            sad.Id                = sad.OrderId = commodityOrder.Id;
            sad.EntityState       = EntityState.Added;
            sad.ModifiedOn        = sad.SubTime = currentDate;
            sad.IsSettled         = false;
            sad.AppId             = commodityOrder.AppId;
            sad.EsAppId           = commodityOrder.EsAppId.Value;
            sad.OrderCode         = commodityOrder.Code;
            sad.OrderSubTime      = payTime;
            sad.OrderAmount       = commodityOrder.Price;
            sad.OrderRealAmount   = commodityOrder.RealPrice.Value;
            sad.OrderFreight      = commodityOrder.Freight;
            sad.IsSetSettleAmount = isSetSettleAmount;

            // 导入订单时,记录退款金额
            if (commodityOrder.State == 7 || orderServiceState == 7)
            {
                var refund = OrderRefundAfterSales.ObjectSet().Where(o => o.OrderId == commodityOrder.Id).FirstOrDefault();
                // 全额退款 不计入结算单
                if (refund.IsFullRefund == 1)
                {
                    sad.IsSettled = true;
                    if (contextSession != null)
                    {
                        foreach (var item in items)
                        {
                            contextSession.SaveObject(item);
                        }
                        contextSession.SaveObject(sad);
                    }
                    return(sad);
                }
                else
                {
                    sad.OrderRefundAmount = refund.RefundMoney;
                }
            }
            else
            {
                sad.OrderRefundAmount = 0; // 暂无单品退货
            }

            //// 计算商城优惠券金额
            //var orderP ayDetailId = OrderPayDetail.ObjectSet().Where(c => c.OrderId == commodityOrder.Id && c.ObjectType == 1).Select(c => c.ObjectId).FirstOrDefault();
            //if (orderPayDetailId != Guid.Empty)
            //{
            //    var request = new Coupon.Deploy.CustomDTO.ListCouponNewRequestDTO
            //    {
            //        CouponIds = new List<Guid> { orderPayDetailId },
            //        UserId = commodityOrder.UserId
            //    };
            //    var coupons = CouponSV.Instance.GetUserCouponsByIds(request);
            //    if (coupons.IsSuccess)
            //    {
            //        var firstCoupon = coupons.Data[0];

            //        sad.OrderCouponAmount = firstCoupon.Cash;
            //        // 判断是否为电商馆
            //        sad.IsMallCoupon = ZPHSV.Instance.IsAppPavilion(firstCoupon.ShopId);
            //    }
            //    else
            //    {
            //        LogHelper.Error(string.Format("CouponSV.GetUserCouponsByIds返回结果不成功,入参 CouponIds: {0} UserId: {1},出参 Code: {2} Info: {3}。", orderPayDetailId, commodityOrder.UserId, coupons.Code, coupons.Info));
            //    }
            //}

            // 计算商家结算金额

            decimal spreadMoney = 0;
            if (commodityOrder.SpreadGold > 0)
            {
                spreadMoney = commodityOrder.SpreadGold.ToMoney();
            }
            sad.OrderSpreadAmount = spreadMoney;

            // 1.第三方
            if (mall.Type == 1)
            {
                sad.OrderYJBAmount = items.Sum(i => i.OrderItemYJBAmount);

                // 商城佣金
                sad.PromotionAmount = items.Sum(i => i.PromotionAmount);

                // 优先级:1推广主、2三级分销、 3众销
                //sad.OrderPromotionCommissionAmount = commodityOrder.SpreadGold > 0 ? commodityOrder.SpreadGold.ToMoney() :
                //    commodityOrder.DistributeMoney > 0 ? commodityOrder.DistributeMoney : commodityOrder.Commission;
                // 老版本,已弃 商家结算金额 = 订单总额 + 商城优惠券总金额 - 退款总金额 - 推广佣金总额 - 商城佣金总额
                // 版本1:商家结算金额 =  实收款 +  商城易捷币抵用金额 - 退款金额  - 商城佣金
                // 版本2:商家结算金额 =  实收款 +  商城易捷币抵用金额 - 退款金额  - 商城佣金 - 推广佣金总额
                // 商家结算金额
                sad.SellerAmount = Math.Truncate((sad.OrderRealAmount + sad.OrderYJBAmount - sad.OrderRefundAmount - sad.PromotionAmount - sad.OrderSpreadAmount.Value) * 100) / 100;
            }
            // 0.自营他配
            else if (mall.Type == 0)
            {
                // 商品结算价
                decimal totalsSettlePrice = 0;
                foreach (var item in items)
                {
                    totalsSettlePrice += item.SettleAmount * item.OrderItemNumber;
                }
                sad.SettleAmount = totalsSettlePrice;
                // 商家结算金额 = 商品结算价*数量 + 运费 - 退款金额
                sad.SellerAmount = Math.Truncate((sad.SettleAmount + sad.OrderFreight - sad.OrderRefundAmount) * 100) / 100;
                // 商城佣金
                sad.PromotionAmount = Math.Truncate((sad.OrderRealAmount - sad.SellerAmount - sad.OrderSpreadAmount.Value) * 100) / 100;
            }
            // 2.自营自配自采
            // 3.自营自配统采
            if (contextSession != null)
            {
                foreach (var item in items)
                {
                    contextSession.SaveObject(item);
                }
                contextSession.SaveObject(sad);
            }
            return(sad);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 根据商品ID得到商品分类
        /// </summary>
        /// <param name="commodityId">商品ID</param>
        /// <returns></returns>
        public List <CommodityCategory> GetCommodityCategoryByCommodityId(Guid commodityId)
        {
            List <CommodityCategory> commodityCategory = CommodityCategory.ObjectSet().Where(n => n.CommodityId == commodityId).ToList();

            return(commodityCategory);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 自动同步严选商品信息
        /// </summary>
        /// <param name="AppId"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> AutoSyncYXCommodityInfoExt(System.Guid AppId, System.Collections.Generic.List <System.Guid> Ids)
        {
            try
            {
                Jinher.AMP.App.Deploy.CustomDTO.AppIdOwnerIdTypeDTO appModel = APPSV.Instance.GetAppOwnerInfo(AppId);
                bool isFnull = true;
                if (appModel.OwnerType == 0)
                {
                    CBC.Deploy.CustomDTO.OrgInfoNewDTO orgInfoDTO = CBCSV.Instance.GetOrgInfoNewBySubId(appModel.OwnerId);
                    if (orgInfoDTO == null || string.IsNullOrEmpty(orgInfoDTO.CompanyPhone))
                    {
                        isFnull = false;
                    }
                }
                JdCommoditySearchDTO JdComDTO = new JdCommoditySearchDTO();
                Guid           userId         = this.ContextDTO.LoginUserID;
                ContextSession contextSession = ContextFactory.CurrentThreadContext;
                if (isFnull)
                {
                    //取出补全的商品信息
                    var                   YXComList       = JdCommodity.ObjectSet().Where(p => p.AppId == AppId && Ids.Contains(p.Id)).ToList();
                    List <string>         skuIds          = YXComList.Select(s => s.JDCode).ToList();
                    List <YXComDetailDTO> YXComDetailList = new List <YXComDetailDTO>();

                    for (int i = 0; i < skuIds.Count; i += 30)
                    {
                        YXComDetailList.AddRange(YXSV.GetComDetailList(skuIds.Skip(i).Take(30).ToList()));
                    }
                    if (!YXComDetailList.Any())
                    {
                        return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> {
                            Data = JdComDTO, ResultCode = 1, isSuccess = false, Message = "未获取到严选商品信息"
                        });
                    }
                    #region 获取所有skuid库存 处理严选商品属性

                    List <StockDTO>             YXstockNumList = new List <StockDTO>();             //库存信息
                    List <itemSkuSpecValueList> skuAttr        = new List <itemSkuSpecValueList>(); //商品属性

                    if (YXComDetailList.Any())
                    {
                        List <string> Sku = new List <string>();
                        foreach (var item in YXComDetailList)
                        {
                            Sku.AddRange(item.skuList.Select(s => s.id).ToList());
                            foreach (var it in item.skuList)
                            {
                                skuAttr.AddRange(it.itemSkuSpecValueList);
                            }
                        }
                        //批量获取严选库存信息
                        for (int i = 0; i < Sku.Count; i += 90)
                        {
                            YXstockNumList.AddRange(YXSV.GetStockNum(Sku.Skip(i).Take(90).ToList()));
                            //Thread.Sleep(1000);
                        }
                        //写入严选商品属性
                        List <ComAttribute> ComAttr = new List <ComAttribute>();
                        foreach (var item in skuAttr)
                        {
                            ComAttribute Com = new ComAttribute();
                            Com.AttrName  = item.skuSpec.name;
                            Com.Attrvalue = item.skuSpecValue.value;
                            ComAttr.Add(Com);
                        }
                        var firstAttributeName = ComAttr.Select(s => s.AttrName).ToList();
                        //写入不存在的商品属性
                        List <string> colorAndSize = new List <string>()
                        {
                            "颜色", "尺寸"
                        };
                        var NoExistAttr = firstAttributeName.Except(Jinher.AMP.BTP.BE.Attribute.ObjectSet().Where(p => p.AppId == AppId && p.IsDel == false).Select(s => s.Name).ToList().Union(colorAndSize)).ToList();
                        if (NoExistAttr.Any())
                        {
                            foreach (var item in NoExistAttr)
                            {
                                AttributeDTO attrDTO = new AttributeDTO();
                                attrDTO.Id          = Guid.NewGuid();
                                attrDTO.Name        = item;
                                attrDTO.AppId       = AppId;
                                attrDTO.EntityState = System.Data.EntityState.Added;
                                Jinher.AMP.BTP.BE.Attribute attribute = new Jinher.AMP.BTP.BE.Attribute().FromEntityData(attrDTO);
                                attribute.SubId   = userId;
                                attribute.SubTime = DateTime.Now;
                                contextSession.SaveObject(attribute);
                            }
                        }
                    }
                    #endregion
                    #region 获取所有的商城分类  商品类目
                    //获取商城品类
                    var InnerCategoryNameList = YXComList.Select(s => s.VideoName.Trim()).ToList();

                    //获取商品分类
                    var           CategoryNameList = YXComList.Select(s => s.CategoryName).ToList();//获取所有的商品分类
                    string        ggg  = string.Join(",", CategoryNameList.ToArray());
                    List <string> list = new List <string>(ggg.Split(','));
                    //易捷北京
                    var CategoryList = Category.ObjectSet().Where(p => p.AppId == new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6") && !p.IsDel && CategoryNameList.Contains(p.Name)).ToList();
                    var categoryList = InnerCategory.ObjectSet().Where(p => InnerCategoryNameList.Contains(p.Name) && p.AppId == new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6") && !p.IsDel).ToList();
                    //本地调试
                    //var categoryList = InnerCategory.ObjectSet().Where(p => InnerCategoryNameList.Contains(p.Name) && p.AppId == AppId && !p.IsDel).ToList();
                    //var CategoryList = Category.ObjectSet().Where(p => p.AppId == AppId && !p.IsDel && list.Distinct().Contains(p.Name)).ToList();
                    #endregion

                    //获取不到商品类目的
                    List <string> NoCategoryData = new List <string>();
                    //店铺中存在的备注编码进行更新  不存在则插入
                    var ExistCommodity = Commodity.ObjectSet().Where(p => skuIds.Contains(p.Barcode) && !p.IsDel && p.AppId == AppId).ToList();
                    JdComDTO.RepeatData = ExistCommodity.Select(s => s.Barcode).ToList();

                    foreach (var item in ExistCommodity)
                    {
                        var YXCom           = YXComList.FirstOrDefault(p => p.JDCode == item.Barcode);
                        var YXComDetailInfo = YXComDetailList.Where(p => p.id == item.Barcode).FirstOrDefault();

                        var minSortValueQuery = (from m in Commodity.ObjectSet()
                                                 where m.AppId == AppId && m.CommodityType == 0
                                                 select m);
                        int?minSort      = minSortValueQuery.Min(m => (int?)m.SortValue);
                        int minSortValue = 2;
                        if (minSort.HasValue)
                        {
                            minSortValue = minSort.Value;
                        }
                        item.Name         = "网易严选 " + YXComDetailInfo.name;
                        item.SubId        = userId;
                        item.No_Number    = YXCom.No_Number ?? 0;
                        item.Price        = YXComDetailInfo.skuList.Min(p => p.channelPrice);
                        item.Stock        = YXCom.Stock;
                        item.PicturesPath = YXComDetailInfo.listPicUrl;
                        item.Description  = "<div class=\"JD-goods\">" + YXComDetailInfo.itemDetail.detailHtml + "</div>";

                        //Com.State = 1; 只更新商品信息,不更新商品上下架状态
                        item.IsDel             = false;
                        item.AppId             = YXCom.AppId;
                        item.TotalCollection   = 0;
                        item.TotalReview       = 0;
                        item.Salesvolume       = 0;
                        item.ModifiedOn        = DateTime.Now;
                        item.ComAttribute      = YXCom.ComAttribute;
                        item.CategoryName      = YXCom.CategoryName;
                        item.SortValue         = minSortValue - 1;
                        item.FreightTemplateId = YXCom.FreightTemplateId;  //99元以下商品8元运费
                        item.MarketPrice       = YXCom.MarketPrice;
                        //Com.Weight = YXComDetailInfo.;
                        //Com.SaleService = JdComDetailInfo.wareQD + "<br>" + JdComDetailInfo.shouhou;
                        item.SaleAreas     = YXCom.SaleAreas;
                        item.SharePercent  = YXCom.SharePercent;
                        item.CommodityType = 0;
                        item.Duty          = YXCom.Duty;
                        item.TaxRate       = YXCom.TaxRate;
                        item.TaxClassCode  = YXCom.TaxClassCode;
                        item.Unit          = "件";
                        item.InputRax      = YXCom.InputRax;

                        if (YXComDetailInfo.skuList.Count() == 1)
                        {
                            //单条属性与库存表保持一致
                            item.JDCode  = YXComDetailInfo.skuList.FirstOrDefault().id;
                            item.Code    = item.JDCode;
                            item.Barcode = YXComDetailInfo.id;
                            item.No_Code = item.JDCode;
                        }
                        else
                        {
                            //多条属性存储SPU
                            item.JDCode  = YXComDetailInfo.skuList.OrderBy(p => p.channelPrice).FirstOrDefault().id;
                            item.Code    = item.JDCode;
                            item.Barcode = YXComDetailInfo.id; //存严选商品的SPU
                            item.No_Code = item.JDCode;
                        }

                        item.CostPrice        = item.Price * Convert.ToDecimal(0.8);
                        item.ServiceSettingId = YXCom.ServiceSettingId;
                        //Com.TechSpecs = JdComDetailInfo.param;
                        item.SaleService        = YXCom.SaleService;
                        item.Type               = 0;
                        item.YJCouponActivityId = "";
                        item.YJCouponType       = "";
                        item.ModifieId          = userId;
                        List <ComAttributeDTO> ComAttr = new List <ComAttributeDTO>();
                        foreach (var skuitem in YXComDetailInfo.skuList)
                        {
                            foreach (var it in skuitem.itemSkuSpecValueList)
                            {
                                ComAttributeDTO ComAtt = new ComAttributeDTO();
                                ComAtt.Attribute       = it.skuSpec.name;
                                ComAtt.SecondAttribute = it.skuSpecValue.value;
                                ComAttr.Add(ComAtt);
                            }
                        }
                        item.ComAttribute = JsonHelper.JsonSerializer <List <ComAttributeDTO> >(ComAttr);
                        item.RefreshCache(EntityState.Modified);
                        //更新库存表
                        UpdateCommodityStock(item, YXComDetailInfo, YXstockNumList, contextSession);
                        int count1 = contextSession.SaveChanges();
                        //更新JdCommodity表中状态
                        YXCom.State = 1;
                        #region 商品图片
                        //删除图片
                        ProductDetailsPictureBP pdpbp = new ProductDetailsPictureBP();
                        pdpbp.DeletePictures(item.Id);

                        List <string> PicList = new List <string>();
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl1);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl2);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl3);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl4);
                        //添加图片
                        int sort = 1;
                        foreach (var itempic in PicList)
                        {
                            if (!string.IsNullOrWhiteSpace(itempic) && itempic.Length >= 50)
                            {
                                ProductDetailsPicture pic = ProductDetailsPicture.CreateProductDetailsPicture();
                                pic.Name         = "商品图片";
                                pic.SubId        = userId;
                                pic.SubTime      = DateTime.Now;
                                pic.PicturesPath = itempic;
                                pic.CommodityId  = item.Id;
                                pic.Sort         = sort;
                                contextSession.SaveObject(pic);
                                sort++;
                            }
                        }
                        #endregion
                        #region 商品分类
                        //删除商品分类
                        var catList = CommodityCategory.ObjectSet().Where(c => c.CommodityId == item.Id).ToList();
                        foreach (var commodityCategory in catList)
                        {
                            contextSession.Delete(commodityCategory);
                        }
                        //添加商品分类
                        var ComCategory = CategoryList.Where(p => YXCom.CategoryName.Contains(p.Name)).ToList();
                        if (ComCategory.Any())
                        {
                            foreach (var itemcate in ComCategory)
                            {
                                CommodityCategory comcate = CommodityCategory.CreateCommodityCategory();
                                comcate.CategoryId  = itemcate.Id;
                                comcate.CommodityId = item.Id;
                                comcate.SubId       = userId;
                                comcate.SubTime     = DateTime.Now;
                                comcate.Name        = "商品分类";
                                comcate.IsDel       = false;
                                #region 本地测试
                                //comcate.SubId = AppId;
                                //comcate.AppId = AppId;
                                //comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                                #endregion
                                //正式环境
                                comcate.SubId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.AppId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6"));
                                contextSession.SaveObject(comcate);
                            }
                        }
                        else
                        {
                            NoCategoryData.Add(YXCom.JDCode);
                        }
                        #endregion
                        #region 商城分类
                        //删除商城分类
                        var oldCCs = CommodityInnerCategory.ObjectSet().Where(c => c.CommodityId == item.Id).ToList();
                        foreach (var commodityCategory in oldCCs)
                        {
                            contextSession.Delete(commodityCategory);
                        }
                        //添加商城分类
                        var innerCateid = categoryList.Where(p => p.Name == YXCom.VideoName.Trim()).FirstOrDefault();
                        if (innerCateid != null)
                        {
                            CommodityInnerCategory comInnerCate = CommodityInnerCategory.CreateCommodityInnerCategory();
                            comInnerCate.CategoryId  = innerCateid.Id;
                            comInnerCate.CommodityId = item.Id;
                            comInnerCate.SubId       = userId;
                            comInnerCate.SubTime     = DateTime.Now;
                            comInnerCate.Name        = "商品分类";
                            comInnerCate.IsDel       = false;
                            comInnerCate.SubId       = AppId;
                            comInnerCate.AppId       = AppId;
                            comInnerCate.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                            contextSession.SaveObject(comInnerCate);
                        }
                        #endregion
                    }
                    #region 商品中不存在的插入
                    var NoExist = YXComList.Where(p => !JdComDTO.RepeatData.Contains(p.Barcode)).ToList();
                    foreach (var item in NoExist)
                    {
                        var YXComDetailInfo = YXComDetailList.Where(p => p.id == item.JDCode).FirstOrDefault();

                        var minSortValueQuery = (from m in Commodity.ObjectSet()
                                                 where m.AppId == AppId && m.CommodityType == 0
                                                 select m);
                        int?minSort      = minSortValueQuery.Min(m => (int?)m.SortValue);
                        int minSortValue = 2;
                        if (minSort.HasValue)
                        {
                            minSortValue = minSort.Value;
                        }
                        Commodity Com = Commodity.CreateCommodity();
                        Com.Id                = Guid.NewGuid();
                        Com.Name              = "网易严选 " + YXComDetailInfo.name;
                        Com.SubTime           = DateTime.Now;
                        Com.SubId             = userId;
                        Com.No_Number         = item.No_Number ?? 0;
                        Com.Price             = YXComDetailInfo.skuList.Min(p => p.channelPrice);
                        Com.Stock             = item.Stock;
                        Com.PicturesPath      = YXComDetailInfo.listPicUrl;
                        Com.Description       = "<div class=\"JD-goods\">" + YXComDetailInfo.itemDetail.detailHtml + "</div>";
                        Com.State             = 1; //只更新商品信息,不更新商品上下架状态
                        Com.IsDel             = false;
                        Com.AppId             = item.AppId;
                        Com.TotalCollection   = 0;
                        Com.TotalReview       = 0;
                        Com.Salesvolume       = 0;
                        Com.ModifiedOn        = DateTime.Now;
                        Com.ComAttribute      = item.ComAttribute;
                        Com.CategoryName      = item.CategoryName;
                        Com.SortValue         = minSortValue - 1;
                        Com.FreightTemplateId = item.FreightTemplateId;  //99元以下商品8元运费
                        Com.MarketPrice       = item.MarketPrice;
                        //Com.Weight = YXComDetailInfo.;
                        //Com.SaleService = JdComDetailInfo.wareQD + "<br>" + JdComDetailInfo.shouhou;
                        Com.SaleAreas     = item.SaleAreas;
                        Com.SharePercent  = item.SharePercent;
                        Com.CommodityType = 0;
                        Com.Duty          = item.Duty;
                        Com.TaxRate       = item.TaxRate;
                        Com.TaxClassCode  = item.TaxClassCode;
                        Com.Unit          = "件";
                        Com.InputRax      = item.InputRax;

                        if (YXComDetailInfo.skuList.Count() == 1)
                        {
                            //单条属性与库存表保持一致
                            Com.JDCode  = YXComDetailInfo.skuList.FirstOrDefault().id;
                            Com.Code    = Com.JDCode;
                            Com.Barcode = YXComDetailInfo.id;
                            Com.No_Code = Com.JDCode;
                        }
                        else
                        {
                            //多条属性存储SPU
                            Com.JDCode  = YXComDetailInfo.skuList.OrderBy(p => p.channelPrice).FirstOrDefault().id;
                            Com.Code    = Com.JDCode;
                            Com.Barcode = YXComDetailInfo.id; //存严选商品的SPU
                            Com.No_Code = Com.JDCode;
                        }

                        Com.CostPrice        = Com.Price * Convert.ToDecimal(0.8);
                        Com.ServiceSettingId = item.ServiceSettingId;
                        //Com.TechSpecs = JdComDetailInfo.param;
                        Com.SaleService        = item.SaleService;
                        Com.Type               = 0;
                        Com.YJCouponActivityId = "";
                        Com.YJCouponType       = "";
                        Com.ModifieId          = userId;
                        List <ComAttributeDTO> ComAttr = new List <ComAttributeDTO>();
                        foreach (var skuitem in YXComDetailInfo.skuList)
                        {
                            foreach (var it in skuitem.itemSkuSpecValueList)
                            {
                                ComAttributeDTO ComAtt = new ComAttributeDTO();
                                ComAtt.Attribute       = it.skuSpec.name;
                                ComAtt.SecondAttribute = it.skuSpecValue.value;
                                ComAttr.Add(ComAtt);
                            }
                        }
                        Com.ComAttribute = JsonHelper.JsonSerializer <List <ComAttributeDTO> >(ComAttr);
                        contextSession.SaveObject(Com);
                        SaveCommodityStock(Com, YXComDetailInfo, YXstockNumList, contextSession);

                        //更新JdCommodity表中状态
                        item.State = 1;
                        #region 商品图片
                        List <string> PicList = new List <string>();
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl1);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl2);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl3);
                        PicList.Add(YXComDetailInfo.itemDetail.picUrl4);
                        //添加图片
                        int sort = 1;
                        foreach (var itempic in PicList)
                        {
                            if (!string.IsNullOrEmpty(itempic))
                            {
                                ProductDetailsPicture pic = ProductDetailsPicture.CreateProductDetailsPicture();
                                pic.Name         = "商品图片";
                                pic.SubId        = userId;
                                pic.SubTime      = DateTime.Now;
                                pic.PicturesPath = itempic;
                                pic.CommodityId  = Com.Id;
                                pic.Sort         = sort;
                                contextSession.SaveObject(pic);
                                sort++;
                            }
                        }
                        #endregion
                        #region 商品分类
                        var ComCategory = CategoryList.Where(p => item.CategoryName.Contains(p.Name)).ToList();
                        if (ComCategory.Any())
                        {
                            foreach (var itemcate in ComCategory)
                            {
                                CommodityCategory comcate = CommodityCategory.CreateCommodityCategory();
                                comcate.CategoryId  = itemcate.Id;
                                comcate.CommodityId = Com.Id;
                                comcate.SubId       = userId;
                                comcate.SubTime     = DateTime.Now;
                                comcate.Name        = "商品分类";
                                comcate.IsDel       = false;
                                #region 本地测试
                                //comcate.SubId = AppId;
                                //comcate.AppId = AppId;
                                //comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                                #endregion
                                comcate.SubId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.AppId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6"));
                                contextSession.SaveObject(comcate);
                            }
                        }
                        else
                        {
                            NoCategoryData.Add(item.JDCode);
                        }
                        #endregion
                        #region 商城分类
                        var innerCateid = categoryList.Where(p => p.Name == item.VideoName.Trim()).FirstOrDefault();
                        if (innerCateid != null)
                        {
                            CommodityInnerCategory comInnerCate = CommodityInnerCategory.CreateCommodityInnerCategory();
                            comInnerCate.CategoryId  = innerCateid.Id;
                            comInnerCate.CommodityId = Com.Id;
                            comInnerCate.SubId       = userId;
                            comInnerCate.SubTime     = DateTime.Now;
                            comInnerCate.Name        = "商品分类";
                            comInnerCate.IsDel       = false;
                            comInnerCate.SubId       = AppId;
                            comInnerCate.AppId       = AppId;
                            comInnerCate.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                            contextSession.SaveObject(comInnerCate);
                        }
                        #endregion
                    }
                    #endregion

                    int count = contextSession.SaveChanges();
                    JdComDTO.NoCategoryData = NoCategoryData;
                }
                return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> {
                    Data = JdComDTO, ResultCode = 0, isSuccess = true, Message = "自动同步成功"
                });
            }
            catch (Exception ex)
            {
                LogHelper.Error("YJEmployeeBP.AutoSyncCommodityInfoExt 异常", ex);
                return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> {
                    ResultCode = 1, isSuccess = false, Message = ex.Message
                });
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 查询商品 电商馆
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ResultDTO <List <ComdtyList4SelCDTO> > SearchCommodityExt(ComdtySearch4SelCDTO search)
        {
            QueryPavilionAppParam query = new QueryPavilionAppParam
            {
                Id        = search.belongTo,
                pageIndex = 1,
                pageSize  = int.MaxValue
            };
            var eReturnInfo = ZPHSV.Instance.GetPavilionApp(query);

            JAP.Common.Loging.LogHelper.Debug("SearchCommodityExt eReturnInfo belongTo:" + query.Id);

            List <Guid> appIds = new List <Guid>();

            if (search.AppId != null && search.AppId != Guid.Empty)
            {
                appIds.Add(search.AppId.Value);
            }
            else
            {
                appIds.AddRange(eReturnInfo.Data.Select(t => t.appId));
            }
            if (!string.IsNullOrEmpty(search.AppName))
            {
                var matchAppNameAppIds = eReturnInfo.Data.Where(_ => _.appName.Contains(search.AppName)).Select(t => t.appId).ToList();
                appIds = appIds.Intersect(matchAppNameAppIds).ToList();
            }

            var commodityQuery = Commodity.ObjectSet().Where(c => !c.IsDel && c.State == 0);

            #region 增加商品查询条件---分类、毛利率区间,价格区间
            commodityQuery = AddCommoditySelectWhere(search, commodityQuery);

            #endregion


            if (appIds.Count == 1)
            {
                var appId = appIds[0];
                commodityQuery = commodityQuery.Where(c => c.AppId == appId);
            }
            else
            {
                commodityQuery = commodityQuery.Where(c => appIds.Contains(c.AppId));
            }
            if (!string.IsNullOrEmpty(search.CommodityName))
            {
                commodityQuery = commodityQuery.Where(c => c.Name.Contains(search.CommodityName));
            }
            var commodityList = commodityQuery
                                .OrderBy(_ => _.Name)
                                .Select(c => new ComdtyList4SelCDTO
            {
                Id    = c.Id,
                Name  = c.Name,
                Pic   = c.PicturesPath,
                Price = c.Price,
                AppId = c.AppId,
                Stock = c.Stock
            }).Skip((search.PageIndex - 1) * search.PageSize).Take(search.PageSize).ToList();

            var commodityIds = commodityList.Select(_ => _.Id).ToList();
            //var comCategories = CommodityCategory.ObjectSet().Where(_ => _.IsDel == false && commodityIds.Contains(_.CommodityId))
            //    .OrderBy(_ => _.MaxSort).ToList();
            var comCategories = (from comCategory in CommodityCategory.ObjectSet()
                                 join category in Category.ObjectSet() on comCategory.CategoryId equals category.Id
                                 where commodityIds.Contains(comCategory.CommodityId) && comCategory.IsDel == false && !category.IsDel
                                 orderby comCategory.MaxSort
                                 select new { category.Name, comCategory.AppId, comCategory.CommodityId });

            foreach (var comdty in commodityList)
            {
                // 获取AppName
                var a = eReturnInfo.Data.Where(t => t.appId == comdty.AppId).ToList();
                if (a.Count > 0)
                {
                    comdty.AppName = a[0].appName;
                }

                //获取加入的分类名称
                var currentComCategories = comCategories.Where(_ => /*_.AppId == comdty.AppId &&*/ _.CommodityId == comdty.Id).ToList();
                var cnames = "";
                foreach (var category in currentComCategories)
                {
                    cnames += category.Name + "<br>";
                }
                if (string.IsNullOrEmpty(cnames))
                {
                    cnames = "无分类";
                }
                comdty.CommodityCategory = cnames;
            }

            return(new ResultDTO <List <ComdtyList4SelCDTO> >
            {
                ResultCode = commodityQuery.Count(),
                Data = commodityList.OrderBy(_ => _.AppName).ToList()
            });


            /************************************************Old Code************************************************/
            //var comdtyList = from c in Commodity.ObjectSet()
            //                 where c.IsDel == false && c.State == 0 && ab.Contains(c.AppId)
            //                 orderby c.Name
            //                 select new ComdtyList4SelCDTO
            //                 {
            //                     Id = c.Id,
            //                     Name = c.Name,
            //                     Pic = c.PicturesPath,
            //                     Price = c.Price,
            //                     AppId = c.AppId,
            //                     Stock = c.Stock
            //                 };



            //List<ComdtyList4SelCDTO> comdtyList4SelCdtos = new List<ComdtyList4SelCDTO>();
            //foreach (var comdty in comdtyList)
            //{
            //    var a = eReturnInfo.Data.Where(t => t.appId == comdty.AppId).ToList();
            //    if (a.Count > 0)
            //    {
            //        comdty.AppName = a[0].appName;
            //    }
            //    //获取加入的分类名称
            //    var temp1 = (from scc in CommodityCategory.ObjectSet()
            //                 join sc in Category.ObjectSet() on scc.CategoryId equals sc.Id
            //                 where scc.CommodityId == comdty.Id && scc.IsDel == false && scc.AppId == comdty.AppId
            //                 orderby scc.MaxSort
            //                 select sc);
            //    var cnames = "";
            //    foreach (var category in temp1)
            //    {
            //        cnames += category.Name + "<br>";
            //    }
            //    comdty.CommodityCategory = cnames;

            //    comdtyList4SelCdtos.Add(comdty);
            //}
            //if (search.AppId != null)
            //{
            //    comdtyList4SelCdtos = comdtyList4SelCdtos.Where(o => o.AppId == search.AppId).ToList();
            //}
            //if (!string.IsNullOrEmpty(search.AppName))
            //{
            //    comdtyList4SelCdtos = comdtyList4SelCdtos.Where(o => o.AppName.Contains(search.AppName)).ToList();
            //}
            //if (!string.IsNullOrEmpty(search.CommodityName))
            //{
            //    comdtyList4SelCdtos = comdtyList4SelCdtos.Where(o => o.Name.Contains(search.CommodityName)).ToList();
            //}

            //ResultDTO<List<ComdtyList4SelCDTO>> retInfo = new ResultDTO<List<ComdtyList4SelCDTO>>
            //{
            //    ResultCode = comdtyList4SelCdtos.Count(),
            //    Data = comdtyList4SelCdtos.OrderBy(o => o.AppName)
            //            .Skip((search.PageIndex - 1) * search.PageSize)
            //            .Take(search.PageSize)
            //            .ToList()
            //};
            //return retInfo;
        }
Exemplo n.º 15
0
        /// <summary>
        /// 自动同步商品信息
        /// </summary>
        /// <param name="AppId"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> AutoSyncCommodityInfoExt(System.Guid AppId, System.Collections.Generic.List <System.Guid> Ids)
        {
            try
            {
                Jinher.AMP.App.Deploy.CustomDTO.AppIdOwnerIdTypeDTO appModel =
                    APPSV.Instance.GetAppOwnerInfo(AppId);
                bool isFnull = true;
                if (appModel.OwnerType == 0)
                {
                    CBC.Deploy.CustomDTO.OrgInfoNewDTO orgInfoDTO = CBCSV.Instance.GetOrgInfoNewBySubId(appModel.OwnerId);
                    if (orgInfoDTO == null || string.IsNullOrEmpty(orgInfoDTO.CompanyPhone))
                    {
                        isFnull = false;
                    }
                }
                JdCommoditySearchDTO JdComDTO = new JdCommoditySearchDTO();
                Guid           userId         = this.ContextDTO.LoginUserID;
                ContextSession contextSession = ContextFactory.CurrentThreadContext;
                if (isFnull)
                {
                    //取出补全的商品信息
                    var                     JdComList = JdCommodity.ObjectSet().Where(p => p.AppId == AppId && Ids.Contains(p.Id)).ToList();
                    List <string>           skuIds    = JdComList.Select(s => s.JDCode).ToList();
                    List <JdComPicturesDto> JdComPics = new List <JdComPicturesDto>();
                    for (int i = 0; i < skuIds.Count; i += 99)
                    {
                        JdComPics.AddRange(JDSV.GetComPictures(skuIds.Skip(i).Take(99).ToList()));
                    }
                    //获取京东商品详情
                    List <JdComDetailDto> JdComDetailList = new List <JdComDetailDto>();
                    foreach (var item in skuIds)
                    {
                        var JdComDetailInfo = JDSV.GetJdDetail(item);
                        JdComDetailList.Add(JdComDetailInfo);
                    }
                    //获取商城品类
                    var InnerCategoryNameList = JdComList.Select(s => s.VideoName.Trim()).ToList();
                    //获取运费模板
                    var FreightTemplateInfo = FreightTemplate.ObjectSet().FirstOrDefault(p => p.AppId == AppId && p.IsDefault == 1);
                    //获取商品分类
                    var           CategoryNameList = JdComList.Select(s => s.CategoryName).ToList();//获取所有的商品分类
                    string        ggg  = string.Join(",", CategoryNameList.ToArray());
                    List <string> list = new List <string>(ggg.Split(','));
                    //易捷北京
                    var CategoryList = Category.ObjectSet().Where(p => p.AppId == new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6") && !p.IsDel && CategoryNameList.Contains(p.Name)).ToList();
                    var categoryList = InnerCategory.ObjectSet().Where(p => InnerCategoryNameList.Contains(p.Name) && p.AppId == new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6") && !p.IsDel).ToList();
                    //本地调试
                    //var categoryList = InnerCategory.ObjectSet().Where(p => InnerCategoryNameList.Contains(p.Name) && p.AppId == AppId && !p.IsDel).ToList();
                    //var CategoryList = Category.ObjectSet().Where(p => p.AppId == AppId && !p.IsDel && list.Distinct().Contains(p.Name)).ToList();

                    //获取不到商品类目的
                    List <string> NoCategoryData = new List <string>();
                    //店铺中存在的备注编码进行更新  不存在则插入
                    var ExistCommodity = Commodity.ObjectSet().Where(p => skuIds.Contains(p.JDCode) && !p.IsDel && p.AppId == AppId).ToList();
                    JdComDTO.RepeatData = ExistCommodity.Select(s => s.JDCode).ToList();

                    foreach (var item in ExistCommodity)
                    {
                        var JdCom           = JdComList.FirstOrDefault(p => p.JDCode == item.JDCode);
                        var JdComPic        = JdComPics.Where(p => p.skuId == item.JDCode);
                        var JdComDetailInfo = JdComDetailList.Where(p => p.sku == item.JDCode).FirstOrDefault();

                        var minSortValueQuery = (from m in Commodity.ObjectSet()
                                                 where m.AppId == AppId && m.CommodityType == 0
                                                 select m);
                        int?minSort      = minSortValueQuery.Min(m => (int?)m.SortValue);
                        int minSortValue = 2;
                        if (minSort.HasValue)
                        {
                            minSortValue = minSort.Value;
                        }
                        Commodity Com = new Commodity();
                        Com.Id           = item.Id;
                        Com.Name         = JdComDetailInfo.name;
                        Com.Code         = JdCom.Code;
                        Com.SubTime      = DateTime.Now;
                        Com.SubId        = userId;
                        Com.No_Number    = JdCom.No_Number ?? 0;
                        Com.Price        = JdCom.Price ?? 0;
                        Com.Stock        = JdCom.Stock;
                        Com.PicturesPath = "http://img13.360buyimg.com/n1/" + JdComPic.FirstOrDefault(p => p.isPrimary == "1").path;
                        if (JdComDetailInfo.appintroduce != null && JdComDetailInfo.appintroduce != "")
                        {
                            string Div = JdComDetailInfo.appintroduce.Substring(0, 10);
                            if (Div.Contains("<div"))
                            {
                                Com.Description = "<div class=\"JD-goods\">" + JdComDetailInfo.appintroduce.Replace("\'", "\"").Replace("\'", "\"") + "</div>";
                            }
                            else
                            {
                                Com.Description = JdComDetailInfo.appintroduce.Replace("\'", "\"").Replace("\'", "\"");
                            }
                        }
                        else
                        {
                            string Div = JdComDetailInfo.introduction.Substring(0, 10);
                            if (Div.Contains("<div"))
                            {
                                Com.Description = "<div class=\"JD-goods\">" + JdComDetailInfo.introduction.Replace("\'", "\"").Replace("\'", "\"") + "</div>";
                            }
                            else
                            {
                                Com.Description = JdComDetailInfo.introduction.Replace("\'", "\"").Replace("\'", "\"");
                            }
                        }
                        //Com.State = 1; 只更新商品信息,不更新商品上下架状态
                        Com.IsDel             = false;
                        Com.AppId             = JdCom.AppId;
                        Com.No_Code           = JdCom.No_Code;
                        Com.TotalCollection   = 0;
                        Com.TotalReview       = 0;
                        Com.Salesvolume       = 0;
                        Com.ModifiedOn        = DateTime.Now;
                        Com.ComAttribute      = JdCom.ComAttribute;
                        Com.CategoryName      = JdCom.CategoryName;
                        Com.SortValue         = minSortValue - 1;
                        Com.FreightTemplateId = FreightTemplateInfo.Id;  //99元以下商品8元运费
                        Com.MarketPrice       = JdCom.MarketPrice;
                        Com.Weight            = JdComDetailInfo.weight;
                        Com.SaleService       = JdComDetailInfo.wareQD + "<br>" + JdComDetailInfo.shouhou;
                        Com.SaleAreas         = JdCom.SaleAreas;
                        Com.SharePercent      = JdCom.SharePercent;
                        Com.CommodityType     = 0;
                        Com.Duty               = JdCom.Duty;
                        Com.TaxRate            = JdCom.TaxRate;
                        Com.TaxClassCode       = JdCom.TaxClassCode;
                        Com.Unit               = string.IsNullOrEmpty(JdComDetailInfo.saleUnit) ? "件" : JdComDetailInfo.saleUnit;
                        Com.InputRax           = JdCom.InputRax;
                        Com.Barcode            = JdComDetailInfo.upc;
                        Com.JDCode             = JdCom.JDCode;
                        Com.CostPrice          = JdCom.CostPrice;
                        Com.ServiceSettingId   = JdCom.ServiceSettingId;
                        Com.TechSpecs          = JdComDetailInfo.param;
                        Com.SaleService        = JdCom.SaleService;
                        Com.Type               = 0;
                        Com.YJCouponActivityId = "";
                        Com.YJCouponType       = "";
                        Com.ModifieId          = userId;
                        Com.EntityState        = EntityState.Modified;
                        contextSession.SaveObject(Com);
                        Com.RefreshCache(EntityState.Modified);
                        //更新库存表
                        UpdateCommodityStock(Com, contextSession);
                        int count1 = contextSession.SaveChanges();
                        //更新JdCommodity表中状态
                        JdCom.State = 1;
                        #region 商品图片
                        //删除图片
                        ProductDetailsPictureBP pdpbp = new ProductDetailsPictureBP();
                        pdpbp.DeletePictures(item.Id);
                        //添加图片
                        foreach (var itempic in JdComPic)
                        {
                            ProductDetailsPicture pic = ProductDetailsPicture.CreateProductDetailsPicture();
                            pic.Name         = "商品图片";
                            pic.SubId        = userId;
                            pic.SubTime      = DateTime.Now;
                            pic.PicturesPath = "http://img13.360buyimg.com/n1/" + itempic.path;
                            pic.CommodityId  = Com.Id;
                            pic.Sort         = Convert.ToInt32(itempic.orderSort);
                            contextSession.SaveObject(pic);
                        }
                        #endregion
                        #region 商品分类
                        //删除商品分类
                        var catList = CommodityCategory.ObjectSet().Where(c => c.CommodityId == item.Id).ToList();
                        foreach (var commodityCategory in catList)
                        {
                            contextSession.Delete(commodityCategory);
                        }
                        //添加商品分类
                        var ComCategory = CategoryList.Where(p => JdCom.CategoryName.Contains(p.Name)).ToList();
                        if (ComCategory.Any())
                        {
                            foreach (var itemcate in ComCategory)
                            {
                                CommodityCategory comcate = CommodityCategory.CreateCommodityCategory();
                                comcate.CategoryId  = itemcate.Id;
                                comcate.CommodityId = Com.Id;
                                comcate.SubId       = userId;
                                comcate.SubTime     = DateTime.Now;
                                comcate.Name        = "商品分类";
                                comcate.IsDel       = false;
                                #region 本地测试
                                //comcate.SubId = AppId;
                                //comcate.AppId = AppId;
                                //comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                                #endregion
                                comcate.SubId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.AppId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6"));
                                contextSession.SaveObject(comcate);
                            }
                        }
                        else
                        {
                            NoCategoryData.Add(JdCom.JDCode);
                        }
                        #endregion
                        #region 商城分类
                        //删除商城分类
                        var oldCCs = CommodityInnerCategory.ObjectSet().Where(c => c.CommodityId == item.Id).ToList();
                        foreach (var commodityCategory in oldCCs)
                        {
                            contextSession.Delete(commodityCategory);
                        }
                        //添加商城分类
                        var innerCateid = categoryList.Where(p => p.Name == JdCom.VideoName.Trim()).FirstOrDefault();
                        if (innerCateid != null)
                        {
                            CommodityInnerCategory comInnerCate = CommodityInnerCategory.CreateCommodityInnerCategory();
                            comInnerCate.CategoryId  = innerCateid.Id;
                            comInnerCate.CommodityId = Com.Id;
                            comInnerCate.SubId       = userId;
                            comInnerCate.SubTime     = DateTime.Now;
                            comInnerCate.Name        = "商品分类";
                            comInnerCate.IsDel       = false;
                            comInnerCate.SubId       = AppId;
                            comInnerCate.AppId       = AppId;
                            comInnerCate.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                            contextSession.SaveObject(comInnerCate);
                        }
                        #endregion
                    }
                    #region 商品中不存在的插入
                    var NoExist = JdComList.Where(p => !JdComDTO.RepeatData.Contains(p.JDCode)).ToList();
                    foreach (var item in NoExist)
                    {
                        var JdComPic        = JdComPics.Where(p => p.skuId == item.JDCode);
                        var JdComDetailInfo = JdComDetailList.Where(p => p.sku == item.JDCode).FirstOrDefault();

                        var minSortValueQuery = (from m in Commodity.ObjectSet()
                                                 where m.AppId == AppId && m.CommodityType == 0
                                                 select m);
                        int?minSort      = minSortValueQuery.Min(m => (int?)m.SortValue);
                        int minSortValue = 2;
                        if (minSort.HasValue)
                        {
                            minSortValue = minSort.Value;
                        }
                        Commodity Com = Commodity.CreateCommodity();
                        Com.Id           = item.Id;
                        Com.Name         = JdComDetailInfo.name;
                        Com.Code         = item.Code;
                        Com.SubTime      = DateTime.Now;
                        Com.SubId        = userId;
                        Com.No_Number    = item.No_Number ?? 0;
                        Com.Price        = item.Price ?? 0;
                        Com.Stock        = item.Stock;
                        Com.PicturesPath = "http://img13.360buyimg.com/n1/" + JdComPic.FirstOrDefault(p => p.isPrimary == "1").path;
                        if (JdComDetailInfo.appintroduce != null && JdComDetailInfo.appintroduce != "")
                        {
                            string Div = JdComDetailInfo.appintroduce.Substring(0, 10);
                            if (Div.Contains("<div"))
                            {
                                Com.Description = "<div class=\"JD-goods\">" + JdComDetailInfo.appintroduce.Replace("\'", "\"").Replace("\'", "\"") + "</div>";
                            }
                            else
                            {
                                Com.Description = JdComDetailInfo.appintroduce.Replace("\'", "\"").Replace("\'", "\"");
                            }
                        }
                        else
                        {
                            string Div = JdComDetailInfo.introduction.Substring(0, 10);
                            if (Div.Contains("<div"))
                            {
                                Com.Description = "<div class=\"JD-goods\">" + JdComDetailInfo.introduction.Replace("\'", "\"").Replace("\'", "\"") + "</div>";
                            }
                            else
                            {
                                Com.Description = JdComDetailInfo.introduction.Replace("\'", "\"").Replace("\'", "\"");
                            }
                        }
                        Com.State             = 1;
                        Com.IsDel             = false;
                        Com.AppId             = AppId;
                        Com.No_Code           = item.No_Code;
                        Com.TotalCollection   = 0;
                        Com.TotalReview       = 0;
                        Com.Salesvolume       = 0;
                        Com.ModifiedOn        = DateTime.Now;
                        Com.ComAttribute      = item.ComAttribute;
                        Com.CategoryName      = item.CategoryName;
                        Com.SortValue         = minSortValue - 1;
                        Com.FreightTemplateId = FreightTemplateInfo.Id;  //99元以下商品8元运费
                        Com.MarketPrice       = item.MarketPrice;
                        Com.Weight            = JdComDetailInfo.weight;
                        Com.SaleService       = JdComDetailInfo.wareQD + "<br>" + JdComDetailInfo.shouhou;
                        Com.SaleAreas         = item.SaleAreas;
                        Com.SharePercent      = item.SharePercent;
                        Com.CommodityType     = 0;
                        Com.Duty               = item.Duty;
                        Com.TaxRate            = item.TaxRate;
                        Com.TaxClassCode       = item.TaxClassCode;
                        Com.Unit               = string.IsNullOrEmpty(JdComDetailInfo.saleUnit)? "件" : JdComDetailInfo.saleUnit;
                        Com.InputRax           = item.InputRax;
                        Com.Barcode            = JdComDetailInfo.upc;
                        Com.JDCode             = item.JDCode;
                        Com.CostPrice          = item.CostPrice;
                        Com.ServiceSettingId   = item.ServiceSettingId;
                        Com.TechSpecs          = JdComDetailInfo.param;
                        Com.SaleService        = item.SaleService;
                        Com.Type               = 0;
                        Com.YJCouponActivityId = "";
                        Com.YJCouponType       = "";
                        Com.ModifieId          = userId;
                        contextSession.SaveObject(Com);
                        SaveCommodityStock(Com, contextSession);

                        //更新JdCommodity表中状态
                        item.State = 1;
                        #region 商品图片
                        foreach (var itempic in JdComPic)
                        {
                            ProductDetailsPicture pic = ProductDetailsPicture.CreateProductDetailsPicture();
                            pic.Name         = "商品图片";
                            pic.SubId        = userId;
                            pic.SubTime      = DateTime.Now;
                            pic.PicturesPath = "http://img13.360buyimg.com/n1/" + itempic.path;
                            pic.CommodityId  = Com.Id;
                            pic.Sort         = Convert.ToInt32(itempic.orderSort);
                            contextSession.SaveObject(pic);
                        }
                        #endregion
                        #region 商品分类
                        var ComCategory = CategoryList.Where(p => item.CategoryName.Contains(p.Name)).ToList();
                        if (ComCategory.Any())
                        {
                            foreach (var itemcate in ComCategory)
                            {
                                CommodityCategory comcate = CommodityCategory.CreateCommodityCategory();
                                comcate.CategoryId  = itemcate.Id;
                                comcate.CommodityId = Com.Id;
                                comcate.SubId       = userId;
                                comcate.SubTime     = DateTime.Now;
                                comcate.Name        = "商品分类";
                                comcate.IsDel       = false;
                                #region 本地测试
                                //comcate.SubId = AppId;
                                //comcate.AppId = AppId;
                                //comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                                #endregion
                                comcate.SubId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.AppId    = new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6");
                                comcate.CrcAppId = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(new Guid("8B4D3317-6562-4D51-BEF1-0C05694AC3A6"));
                                contextSession.SaveObject(comcate);
                            }
                        }
                        else
                        {
                            NoCategoryData.Add(item.JDCode);
                        }
                        #endregion
                        #region 商城分类
                        var innerCateid = categoryList.Where(p => p.Name == item.VideoName.Trim()).FirstOrDefault();
                        if (innerCateid != null)
                        {
                            CommodityInnerCategory comInnerCate = CommodityInnerCategory.CreateCommodityInnerCategory();
                            comInnerCate.CategoryId  = innerCateid.Id;
                            comInnerCate.CommodityId = Com.Id;
                            comInnerCate.SubId       = userId;
                            comInnerCate.SubTime     = DateTime.Now;
                            comInnerCate.Name        = "商品分类";
                            comInnerCate.IsDel       = false;
                            comInnerCate.SubId       = AppId;
                            comInnerCate.AppId       = AppId;
                            comInnerCate.CrcAppId    = Jinher.JAP.Common.Crc64.ComputeAsAsciiGuid(AppId);
                            contextSession.SaveObject(comInnerCate);
                        }
                        #endregion
                    }
                    #endregion

                    int count = contextSession.SaveChanges();
                    JdComDTO.NoCategoryData = NoCategoryData;
                }
                return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> {
                    Data = JdComDTO, ResultCode = 0, isSuccess = true, Message = "自动同步成功"
                });
            }
            catch (Exception ex)
            {
                LogHelper.Error("YJEmployeeBP.AutoSyncCommodityInfoExt 异常", ex);
                return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> {
                    ResultCode = 1, isSuccess = false, Message = ex.Message
                });
            }
        }