/// <summary> /// 取消订单加库存时调用 /// </summary> /// <param name="orderItem"></param> /// <param name="needRefreshCacheCommoditys"></param> public static void AddStock(OrderItem orderItem, List <Commodity> needRefreshCacheCommoditys) { var contextSession = ContextFactory.CurrentThreadContext; var presents = OrderItemPresent.ObjectSet().Where(_ => _.OrderItemId == orderItem.Id).ToList(); var presentCommodityIds = presents.Select(a => a.CommodityId).ToList(); var presentCommodityList = Commodity.ObjectSet().Where(a => presentCommodityIds.Contains(a.Id) && !a.IsDel).ToList(); var presentCommodityStockIds = presents.Where(c => c.CommodityStockId.HasValue).Select(a => a.CommodityStockId).Distinct().ToList(); List <CommodityStock> presentCommodityStockList = new List <CommodityStock>(); if (presentCommodityStockIds.Count > 0) { presentCommodityStockList = CommodityStock.ObjectSet().Where(c => presentCommodityIds.Contains(c.Id)).ToList(); } foreach (var present in presents) { Commodity com = presentCommodityList.First(c => c.Id == orderItem.CommodityId); if (present.CommodityStockId.HasValue && present.CommodityStockId.Value != Guid.Empty) { CommodityStock cStock = presentCommodityStockList.FirstOrDefault(c => orderItem.CommodityStockId == c.Id); cStock.EntityState = System.Data.EntityState.Modified; cStock.Stock += present.Number; contextSession.SaveObject(cStock); } com.EntityState = System.Data.EntityState.Modified; com.Stock += present.Number; contextSession.SaveObject(com); needRefreshCacheCommoditys.Add(com); } }
/// <summary> /// 保存库存 /// </summary> /// <param name="item"></param> /// <param name="contextSession"></param> /// <param name="isUpdate"></param> void SaveCommodityStock(Commodity item, ContextSession contextSession, bool isUpdate = false) { try { CommodityStock cs = CommodityStock.CreateCommodityStock(); cs.ComAttribute = "[]"; cs.Id = item.Id; cs.CommodityId = item.Id; cs.Price = item.Price; cs.MarketPrice = item.MarketPrice; cs.Stock = item.Stock; cs.Duty = item.Duty; cs.Barcode = item.Barcode; cs.No_Code = item.No_Code; cs.JDCode = item.JDCode; cs.ErQiCode = item.ErQiCode; cs.CostPrice = item.CostPrice; if (isUpdate == true) { cs.EntityState = EntityState.Modified; } contextSession.SaveObject(cs); } catch (Exception ex) { LogHelper.Error(string.Format("商品发布服务保存库存异常。SaveCommodityStock"), ex); } }
/// <summary> /// 查询商品 /// </summary> public ResultDTO <ListResult <PresentPromotionCommoditySearchResultDTO> > GetCommoditiesExt(PresentPromotionCommoditySearchDTO input) { if (input.AppId == Guid.Empty) { return(new ResultDTO <ListResult <PresentPromotionCommoditySearchResultDTO> > { isSuccess = false, Message = "参数错误" }); } // 今日活动商品 var hasAddCommodityIds = TodayPromotion.ObjectSet().Select(_ => _.CommodityId).ToList(); var query = Commodity.ObjectSet().Where(_ => !_.IsDel && _.State == 0 && _.AppId == input.AppId && !hasAddCommodityIds.Contains(_.Id)); #region 增加商品查询条件---分类、毛利率区间,价格区间 query = AddCommoditySelectWhere(input, query, hasAddCommodityIds); #endregion if (!string.IsNullOrWhiteSpace(input.Name)) { query = query.Where(_ => _.Name.Contains(input.Name)); } var count = query.Count(); var data = query.OrderByDescending(q => q.SubTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).Select(_ => new PresentPromotionCommoditySearchResultDTO { Id = _.Id, Code = _.No_Code, Name = _.Name, Pic = _.PicturesPath, Price = _.Price, Stock = _.Stock }).ToList(); var ids = data.Select(_ => _.Id).ToList(); var stocks = CommodityStock.ObjectSet().Where(_ => ids.Contains(_.CommodityId)); foreach (var d in data) { d.SKU = new List <PresentPromotionCommoditySearchResultDTO.CommoditySKUModel>(); foreach (var s in stocks.Where(_ => _.CommodityId == d.Id)) { var sku = new PresentPromotionCommoditySearchResultDTO.CommoditySKUModel(); sku.Id = s.Id; sku.Code = s.No_Code; sku.Price = s.Price; sku.Stock = s.Stock; var skuAttr = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ComAttributeDTO> >(s.ComAttribute); sku.Name = string.Join(";", skuAttr.Select(_ => _.Attribute + ":" + _.SecondAttribute)); d.SKU.Add(sku); } } return(new ResultDTO <ListResult <PresentPromotionCommoditySearchResultDTO> > { isSuccess = true, Data = new ListResult <PresentPromotionCommoditySearchResultDTO> { List = data, Count = count } }); }
/// <summary> /// 退款结果回调 /// </summary> /// <param name="result"></param> public static void OrderRefundResult(RefundResult result) { try { Guid orderId; Guid.TryParse(result.orderId, out orderId); LogHelper.Debug("进入 YXOrderHelper.OrderRefundResult,Input:" + JsonConvert.SerializeObject(result)); var orderRefund = OrderRefundAfterSales.ObjectSet().Where(_ => _.ApplyId == result.applyId).FirstOrDefault(); if (orderRefund == null) { LogHelper.Error("YXOrderHelper.OrderRefundResult 失败,未找到退款记录,Input:" + JsonConvert.SerializeObject(result)); } var orderItem = OrderItem.FindByID(orderRefund.OrderItemId.Value); string skuId; if (orderItem.CommodityStockId == null || orderItem.CommodityStockId.Value == Guid.Empty || orderItem.CommodityStockId == orderItem.CommodityId) { var commodity = Commodity.FindByID(orderItem.CommodityId); skuId = commodity.JDCode; } else { var comStock = CommodityStock.FindByID(orderItem.CommodityStockId.Value); skuId = comStock.JDCode; } var skuResult = result.refundSkuList.Where(_ => _.skuId == skuId).FirstOrDefault(); var skuOperateResult = skuResult.operateSkus.Where(_ => _.skuId == skuId).FirstOrDefault(); if (skuOperateResult.status == OrderRefundApplySkuOperateStatusEnum.审核通过) { var refundResult = OrderHelper.ApproveOrderRefundAfterSales(orderRefund.OrderId, orderRefund.OrderItemId ?? Guid.Empty); if (refundResult.ResultCode != 0) { // 失败 LogHelper.Error("YXOrderHelper.OrderRefundResult 失败," + refundResult.Message + ",Input:" + JsonConvert.SerializeObject(result)); } } else if (skuOperateResult.status == OrderRefundApplySkuOperateStatusEnum.已拒绝) { var refundResult = OrderHelper.RejectOrderRefundAfterSales(orderId, orderRefund.OrderItemId ?? Guid.Empty, skuOperateResult.reason); if (refundResult.ResultCode != 0) { // 失败 LogHelper.Error("YXOrderHelper.RejectOrderRefund 失败," + refundResult.Message + ",Input:" + JsonConvert.SerializeObject(result)); } } else { LogHelper.Error("YXOrderHelper.RejectOrderRefund -> OrderId: " + orderId + ", ApplyId: " + result.applyId + ", 忽略的状态:" + skuOperateResult.status.ToString()); } } catch (Exception ex) { LogHelper.Error("YXOrderHelper.OrderRefundResult 异常,Input:" + JsonConvert.SerializeObject(result), ex); } }
private List <CommodityStockDTO> getComStocks(OrderScoreCheckDTO paramDto) { List <CommodityStockDTO> result = new List <CommodityStockDTO>(); Dictionary <Guid, Tuple <string, string> > dict = new Dictionary <Guid, Tuple <string, string> >(); List <Guid> comIds = new List <Guid>(); if (paramDto == null || paramDto.Coms == null || !paramDto.Coms.Any()) { return(result); } foreach (var comScoreCheckDTO in paramDto.Coms) { if (string.IsNullOrEmpty(comScoreCheckDTO.ColorAndSize)) { continue; } comScoreCheckDTO.ColorAndSize = comScoreCheckDTO.ColorAndSize.Replace("null", "").Replace("nil", "").Replace("undefined", "").Replace("(null)", "").Replace(",", ","); var arr = comScoreCheckDTO.ColorAndSize.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 2) { comIds.Add(comScoreCheckDTO.CommodityId); if (!dict.ContainsKey(comScoreCheckDTO.ItemId)) { dict.Add(comScoreCheckDTO.ItemId, new Tuple <string, string>(arr[0], arr[1])); } } } comIds = comIds.Distinct().ToList(); List <CommodityStockDTO> temp = CommodityStock.ObjectSet().Where(c => comIds.Contains(c.CommodityId)).Select(m => new CommodityStockDTO { Id = m.Id, Price = m.Price, Stock = m.Stock, CommodityId = m.CommodityId, ComAttribute = m.ComAttribute }).ToList(); foreach (var comScoreCheckDTO in paramDto.Coms) { if (comIds.All(c => c != comScoreCheckDTO.CommodityId)) { comScoreCheckDTO.CommodityStockId = Guid.Empty; continue; } var comStockDto = getComStock(temp, comScoreCheckDTO.CommodityId, dict[comScoreCheckDTO.ItemId].Item1, dict[comScoreCheckDTO.ItemId].Item2); if (comStockDto != null) { comScoreCheckDTO.CommodityStockId = comStockDto.Id; result.Add(comStockDto); } } return(result); }
/// <summary> /// 更新保存库存 /// </summary> /// <param name="item"></param> /// <param name="contextSession"></param> /// <param name="isUpdate"></param> void UpdateCommodityStock(Commodity Com, YXComDetailDTO YXComDetailInfo, List <StockDTO> stockNumList, ContextSession contextSession, bool isUpdate = false) { try { LogHelper.Debug(string.Format("更新保存库存", JsonHelper.JsonSerializer(YXComDetailInfo.skuList))); var ComStock = CommodityStock.ObjectSet().Where(p => p.CommodityId == Com.Id).ToList(); //根据SkuId获取商品库存 var SkuId = YXComDetailInfo.skuList.Select(p => p.id).ToList(); var stockNum = stockNumList.Where(p => SkuId.Contains(p.skuId)).ToList(); Com.Stock = stockNum.Sum(p => p.inventory); //库存表中存在则更新 foreach (var item in ComStock) { var YXStockInfo = YXComDetailInfo.skuList.FirstOrDefault(p => p.id == item.JDCode); if (YXStockInfo != null) { List <ComAttributeDTO> ComAttribute = new List <ComAttributeDTO>(); foreach (var it in YXStockInfo.itemSkuSpecValueList) { ComAttributeDTO ComAtt = new ComAttributeDTO(); ComAtt.Attribute = it.skuSpec.name; ComAtt.SecondAttribute = it.skuSpecValue.value; ComAttribute.Add(ComAtt); } item.ComAttribute = JsonHelper.JsonSerializer <List <ComAttributeDTO> >(ComAttribute); item.Price = YXStockInfo.channelPrice; item.Stock = stockNum.FirstOrDefault(p => p.skuId == YXStockInfo.id).inventory; item.Duty = Com.Duty; item.Barcode = Com.Barcode; item.No_Code = Com.No_Code; item.ErQiCode = Com.ErQiCode; item.CostPrice = YXStockInfo.channelPrice * Convert.ToDecimal(0.8); item.JDCode = YXStockInfo.id; if (isUpdate == true) { item.EntityState = EntityState.Modified; } item.EntityState = EntityState.Modified; } else { item.EntityState = EntityState.Deleted; } contextSession.SaveObject(item); } } catch (Exception ex) { LogHelper.Error(string.Format("更新保存库存服务保存库存异常。UpdateCommodityStock"), ex); } }
/// <summary> /// 同步库存 /// </summary> /// <param name="skuStockDir"></param> /// <param name="type"></param> /// <returns></returns> public static int UpdateCommodityStock(Dictionary <string, int> skuStockDir, ThirdECommerceTypeEnum type) { try { ContextSession contextSession = ContextFactory.CurrentThreadContext; var skuIds = skuStockDir.Select(p => p.Key).ToList(); List <Commodity> commoditys = new List <Commodity>(); List <CommodityStock> commodityStocks = new List <CommodityStock>(); if (type == ThirdECommerceTypeEnum.JingDongDaKeHu) { commoditys = Commodity.ObjectSet().Where(p => skuIds.Contains(p.JDCode) && p.State == 0 && CustomConfig.JdAppIdList.Contains(p.AppId)).ToList(); } List <Guid> commodityIds = new List <Guid>(); if (commoditys != null && commoditys.Count > 0) { commodityIds = commoditys.Select(p => p.Id).ToList(); } commodityStocks = CommodityStock.ObjectSet().Where(p => skuIds.Contains(p.JDCode) && p.State == 0 && commodityIds.Contains(p.CommodityId)).ToList(); commoditys.ForEach(p => { LogHelper.Info(string.Format("商品(Commodity)调整库存:CommodityId={0},Stock={1}", p.Id, skuStockDir[p.JDCode])); p.Stock = skuStockDir[p.JDCode]; p.ModifiedOn = DateTime.Now; var commodityStock = commodityStocks.FirstOrDefault(x => x.CommodityId == p.Id); if (commodityStock != null) { LogHelper.Info(string.Format("商品(CommodityStock)调整库存:CommodityId={0},Stock={1}", p.Id, skuStockDir[p.JDCode])); commodityStock.Stock = skuStockDir[p.JDCode]; commodityStock.ModifiedOn = DateTime.Now; } }); var count = contextSession.SaveChanges(); if (count > 0) { LogHelper.Info("商品(Commodity)调整库存:count=" + count); } return(count); } catch (Exception ex) { LogHelper.Error(ex.ToString()); } return(0); }
/// <summary> /// 保存库存 /// </summary> /// <param name="item"></param> /// <param name="contextSession"></param> /// <param name="isUpdate"></param> void UpdateCommodityStock(Commodity item, ContextSession contextSession, bool isUpdate = false) { try { var cs = CommodityStock.ObjectSet().FirstOrDefault(p => p.Id == item.Id); cs.ComAttribute = "[]"; cs.Price = item.Price; cs.MarketPrice = item.MarketPrice; cs.Stock = item.Stock; cs.Duty = item.Duty; cs.Barcode = item.Barcode; cs.No_Code = item.No_Code; cs.JDCode = item.JDCode; cs.ErQiCode = item.ErQiCode; cs.CostPrice = item.CostPrice; } catch (Exception ex) { LogHelper.Error(string.Format("商品发布服务保存库存异常。SaveCommodityStock"), ex); } }
/// <summary> /// 发布保存库存 /// </summary> /// <param name="item"></param> /// <param name="contextSession"></param> /// <param name="isUpdate"></param> void SaveCommodityStock(Commodity Com, YXComDetailDTO YXComDetailInfo, List <StockDTO> stockNumList, ContextSession contextSession) { try { LogHelper.Info(string.Format("发布保存库存SaveCommodityStock:", JsonHelper.JsonSerializer(YXComDetailInfo.skuList))); //根据SkuId获取商品库存 var SkuId = YXComDetailInfo.skuList.Select(p => p.id).ToList(); var stockNum = stockNumList.Where(p => SkuId.Contains(p.skuId)).ToList(); Com.Stock = stockNum.Sum(p => p.inventory); foreach (var item in YXComDetailInfo.skuList) { List <ComAttributeDTO> ComAttribute = new List <ComAttributeDTO>(); foreach (var it in item.itemSkuSpecValueList) { ComAttributeDTO ComAtt = new ComAttributeDTO(); ComAtt.Attribute = it.skuSpec.name; ComAtt.SecondAttribute = it.skuSpecValue.value; ComAttribute.Add(ComAtt); } CommodityStock cs = CommodityStock.CreateCommodityStock(); cs.ComAttribute = JsonHelper.JsonSerializer <List <ComAttributeDTO> >(ComAttribute); cs.CommodityId = Com.Id; cs.Price = item.channelPrice; cs.Stock = stockNum.FirstOrDefault(p => p.skuId == item.id).inventory; cs.Duty = Com.Duty; cs.Barcode = Com.Barcode; cs.No_Code = Com.No_Code; cs.ThumImg = item.picUrl; cs.JDCode = item.id; cs.ErQiCode = Com.ErQiCode; cs.CostPrice = item.channelPrice * Convert.ToDecimal(0.8); contextSession.SaveObject(cs); } } catch (Exception ex) { LogHelper.Error(string.Format("商品发布服务保存库存异常。SaveCommodityStock"), ex); } }
public bool initComs() { bool hasError = false; var selecid = _condition.coms.Select(c => c.commodityId).Distinct().ToList(); var cStockid = _condition.coms.Where(c => c.commodityStockId != Guid.Empty).Select(c => c.commodityStockId).Distinct().ToList(); var promotionIds = _condition.coms.Select(c => c.promotionId != Guid.Empty).Distinct().ToList(); var commodityList = ( from c in Commodity.ObjectSet() join s in CommodityStock.ObjectSet() on c.Id equals s.CommodityId into os from ss in os.DefaultIfEmpty() where c.CommodityType == 0 && selecid.Contains(c.Id) && (ss == null || cStockid.Contains(ss.Id)) select new CheckCommodityDTO { Id = c.Id, Price = ss != null ? ss.Price : c.Price, State = c.IsDel ? 3 : c.State, Stock = ss != null ? ss.Stock : c.Stock, Intensity = 10, DiscountPrice = -1, OPrice = c.Price, LimitBuyEach = -1, LimitBuyTotal = -1, SurplusLimitBuyTotal = 0, CommodityStockId = ss != null ? ss.Id : Guid.Empty, IsEnableSelfTake = c.IsEnableSelfTake, AppId = c.AppId }).ToList(); var vipAppIds = (from condition in _condition.coms join com in commodityList on condition.commodityId equals com.Id where condition.promotionId == Guid.Empty select com.AppId ).Distinct().ToList(); var vipDict = AVMSV.GetVipIntensities(vipAppIds, _condition.userId); List <TodayPromotionDTO> promotionDic = new List <TodayPromotionDTO>(); //商品在每日促销表里集合 if (promotionIds.Any()) { promotionDic = TodayPromotion.ObjectSet().Where(a => selecid.Contains(a.CommodityId)). Select(a => new TodayPromotionDTO { CommodityId = a.CommodityId, Intensity = a.Intensity, DiscountPrice = a.DiscountPrice, LimitBuyTotal = a.LimitBuyTotal ?? -1, SurplusLimitBuyTotal = a.SurplusLimitBuyTotal, LimitBuyEach = a.LimitBuyEach, PromotionId = a.PromotionId, PromotionType = a.PromotionType, OutsideId = a.OutsideId, GroupMinVolume = a.GroupMinVolume, ExpireSecond = a.ExpireSecond, StartTime = a.StartTime, EndTime = a.EndTime }).Distinct().ToList(); } foreach (var createOrderCom in _condition.coms) { createOrderCom.checkResult = new CreateOrderComCheckResult(); var com = commodityList.FirstOrDefault(c => c.Id == createOrderCom.commodityId && c.CommodityStockId == createOrderCom.commodityStockId); if (!checkComCanBuy(com, createOrderCom)) { hasError = true; continue; } var realPrice = com.Price; TodayPromotionDTO promotion; //有活动参加活动 if (createOrderCom.promotionId != Guid.Empty) { promotion = promotionDic.FirstOrDefault(c => c.CommodityId == createOrderCom.commodityId && c.PromotionId == createOrderCom.promotionId); if (!checkCanBuyByPromotion(promotion, createOrderCom)) { hasError = true; continue; } if (promotion != null) { realPrice = (promotion.DiscountPrice > -1) ? promotion.DiscountPrice.Value : decimal.Round((com.Price * promotion.Intensity / 10), 2, MidpointRounding.AwayFromZero); } } //没有活动有vip机制,采用vip体系 else if (vipDict.ContainsKey(com.AppId) && vipDict[com.AppId] != null && vipDict[com.AppId].IsVip) { realPrice = (vipDict[com.AppId].DiscountPrice > -1) ? vipDict[com.AppId].DiscountPrice : decimal.Round((com.Price * vipDict[com.AppId].Intensity / 10), 2, MidpointRounding.AwayFromZero); } if (createOrderCom.realPrice != realPrice) { createOrderCom.checkResult.FillData(true, false, 0, ComCantBuyReasonEnum.Price, "商品价格发生变化"); hasError = true; } } return(!hasError); }
/// <summary> /// 发起售后申请(售前-不支持) /// </summary> /// <returns></returns> public static ResultDTO ApplyRefundOrder(CommodityOrder order, OrderItem orderItem, OrderRefund refund) { string skuId = null; if (orderItem.CommodityStockId.HasValue && orderItem.CommodityStockId != Guid.Empty && orderItem.CommodityStockId != orderItem.CommodityId) { var comStock = CommodityStock.FindByID(orderItem.CommodityStockId.Value); if (comStock == null) { return(new ResultDTO { isSuccess = false, Message = "商品不存在。", ResultCode = -1 }); } else { skuId = comStock.JDCode; } } else { var commodity = Commodity.FindByID(orderItem.CommodityId); if (commodity == null) { return(new ResultDTO { isSuccess = false, Message = "商品不存在。", ResultCode = -1 }); } else { skuId = commodity.JDCode; } } if (string.IsNullOrEmpty(skuId)) { return(new ResultDTO { isSuccess = false, Message = "商品SKU编码不存在。", ResultCode = -1 }); } var orderSku = YXOrderSku.ObjectSet().Where(_ => _.OrderId == order.Id && _.SkuId == skuId).FirstOrDefault(); if (orderSku == null) { return(new ResultDTO { isSuccess = false, Message = "订单SKU存在。", ResultCode = -1 }); } var requestData = new ApplyInfo { orderId = order.Id.ToString(), requestId = refund.Id.ToString(), applyUser = new ApplyUser { name = order.ReceiptUserName, mobile = order.ReceiptPhone }, applySku = new ApplySku { packageId = orderSku.PackageId, skuId = orderSku.SkuId, count = orderSku.SaleCount, originalPrice = orderSku.OriginPrice, subtotalPrice = orderSku.SubtotalAmount, applySkuReason = new ApplySkuReason { reason = refund.RefundReason, reasonDesc = refund.RefundDesc }, applyPicList = new List <ApplyPic> { } } }; if (!string.IsNullOrEmpty(refund.OrderRefundImgs)) { foreach (var img in refund.OrderRefundImgs.Split(',')) { requestData.applySku.applyPicList.Add(new ApplyPic { fileName = System.IO.Path.GetFileName(img), url = img }); } } var result = YXSV.ApplyRefundOrder(requestData); if (!result.isSuccess) { return(result); } refund.ApplyId = result.Data.applyId; return(new ResultDTO { isSuccess = true }); }
/// <summary> /// 同步商品上下架 /// </summary> public static void AutoUpdateSNSkuStateByMessage() { try { LogHelper.Info("SNJobHelper.AutoUpdateJdSkuStateByMessage 开始同步易派客商品上下架"); var messages = SuningSV.suning_govbus_message_get("10"); if (messages == null || messages.Count == 0) { return; } var delMsg = messages = messages.Where(_ => _.status == "1" || _.status == "2" || _.status == "0" || _.status == "4").ToList(); if (messages == null || messages.Count == 0) { return; } LogHelper.Info("SNJobHelper.AutoUpdateJdSkuStateByMessage 开始同步易派客商品上下架,获取结果如下:" + JsonHelper.JsonSerializer(messages)); //status 1上架 2下架 0 添加 4 删除 // 0 1代表上架 2 4 代表下架 var skuIds = messages.Where(_ => _.status == "1" || _.status == "2" || _.status == "0" || _.status == "4").Select(_ => _.cmmdtyCode).Where(_ => !string.IsNullOrEmpty(_)).Distinct().ToList(); // 易派客商品Ids var allCommodityIds = Commodity.ObjectSet().Where(_ => !_.IsDel && YPKAppIdList.Contains(_.AppId)).Select(_ => _.Id).ToList(); List <CommodityStock> commodityStocks = new List <CommodityStock>(); for (int i = 0; i < allCommodityIds.Count; i += 100) { var currentCommodityIds = allCommodityIds.Skip(i).Take(100).ToList(); commodityStocks.AddRange(CommodityStock.ObjectSet().Where(_ => currentCommodityIds.Contains(_.CommodityId) && skuIds.Contains(_.JDCode)).ToList()); } var stockCommodityIds = commodityStocks.Select(_ => _.CommodityId).Distinct(); var stockCommodities = Commodity.ObjectSet().Where(_ => stockCommodityIds.Contains(_.Id)).ToList(); List <SNSkuStateDto> snSkuStates = new List <SNSkuStateDto>(); for (int i = 0; i < skuIds.Count; i += 30) { snSkuStates.AddRange(SuningSV.GetSkuState(skuIds.Skip(i).Take(30).ToList())); } int count = 0; //List<Guid> autoAuditOnShelfIds = new List<Guid>(); //List<Guid> autoAuditOffShelfIds = new List<Guid>(); //var autoAuditAppIds = JDAuditMode.ObjectSet().Where(_ => _.StockModeState == 0).Select(_ => _.AppId).ToList(); ContextSession contextSession = ContextFactory.CurrentThreadContext; foreach (var group in commodityStocks.GroupBy(_ => _.CommodityId)) { var addCount = 0; var com = stockCommodities.Where(_ => _.Id == group.Key).FirstOrDefault(); var auditCom = AddCommodityAudit(com); foreach (var item in group) { var snState = snSkuStates.Where(_ => _.skuId == item.JDCode).FirstOrDefault(); if (snState == null) { LogHelper.Info("SNJobHelper.AutoUpdateSkuState-SKU 未获取到易派客上下架状态,商品Id: " + item.Id + ",SkuId: " + item.JDCode); continue; } // 转换JD状态 var state = 0; // 上架 int auditState = 2; // 已上架 if (snState.state == "0") // 下架 { state = 1; auditState = 1; } if (item.State != state) { // 对比审核表 var latestAuditState = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityStockId == item.Id && _.AuditType == 3).OrderByDescending(_ => _.SubTime).Select(_ => _.JdStatus).FirstOrDefault(); if (latestAuditState == 0 || latestAuditState != auditState) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, com.AppId, item, Deploy.Enum.OperateTypeEnum.架无货商品审核); auditStock.AuditType = 3; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdStatus = auditState; contextSession.SaveObject(auditStock); //if (autoAuditAppIds.Contains(com.AppId)) //{ // if (auditState == 2) // { // autoAuditOnShelfIds.Add(auditStock.Id); // } // else // { // autoAuditOffShelfIds.Add(auditStock.Id); // } //} LogHelper.Info("SNJobHelper.AutoUpdateSkuState-SKU 更新易派客商品上下架状态,商品Id: " + item.Id + ",SkuId: " + item.JDCode); } } } if (addCount > 0) { contextSession.SaveObject(auditCom); } if (count >= 200) { contextSession.SaveChanges(); count = 0; } } // 处理无属性商品,并Stock表中无数据的情况 count = 0; var oldcommodityIds = allCommodityIds.Except(stockCommodityIds).ToList(); for (int i = 0; i < oldcommodityIds.Count; i += 100) { var commodityIds = oldcommodityIds.Skip(i).Take(100); var commodities = Commodity.ObjectSet().Where(_ => commodityIds.Contains(_.Id) && (string.IsNullOrEmpty(_.ComAttribute) || _.ComAttribute == "[]") && skuIds.Contains(_.JDCode)).ToList(); foreach (var com in commodities) { var snState = snSkuStates.Where(_ => _.skuId == com.JDCode).FirstOrDefault(); if (snState == null) { LogHelper.Info("SNJobHelper.AutoUpdateSkuState 未获取到易派客上下架状态,商品Id: " + com.Id + ",SkuId: " + com.JDCode); continue; } // 转换JD状态 var state = 0; // 上架 int auditState = 2; // 已上架 if (snState.state == "0") // 下架 { state = 1; auditState = 1; } // 售价 if (com.State != state) { // 对比审核表 var latestAuditState = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityStockId == com.Id && _.AuditType == 3).OrderByDescending(_ => _.SubTime).Select(_ => _.JdStatus).FirstOrDefault(); if (latestAuditState == 0 || latestAuditState != auditState) { var auditCom = AddCommodityAudit(com); var auditStock = AddCommodityStockAudit(contextSession, com, Deploy.Enum.OperateTypeEnum.架无货商品审核); auditStock.AuditType = 3; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdStatus = auditState; contextSession.SaveObject(auditStock); //if (auditState == 2) //{ // autoAuditOnShelfIds.Add(auditStock.Id); //} //else //{ // autoAuditOffShelfIds.Add(auditStock.Id); //} contextSession.SaveObject(auditCom); count++; LogHelper.Info("SNJobHelper.AutoUpdateSkuState 更新易派客商品上下架状态,商品Id: " + com.Id + ",SkuId: " + com.JDCode); } } if (count >= 200) { contextSession.SaveChanges(); count = 0; } } contextSession.SaveChanges(); } //删除消息 foreach (var item in delMsg) { SuningSV.suning_govbus_message_delete(item.id); } } catch (Exception ex) { LogHelper.Error("SNJobHelper.AutoUpdateSkuState 异常", ex); throw; } LogHelper.Info("SNJobHelper.AutoUpdateJdSkuStateByMessage 结束同步Jd商品上下架"); }
/// <summary> /// 同步商品价格 /// </summary> public static void AutoUpdatePriceByMessage() { LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 开始同步易派客商品价格"); try { var messages = SuningSV.GetPriceMessage(); if (messages == null || messages.Count == 0) { return; } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 开始同步SN商品价格,获取结果如下:" + JsonHelper.JsonSerializer(messages)); var skuIds = messages.Select(_ => _.cmmdtyCode).Where(_ => !string.IsNullOrEmpty(_)).Distinct().ToList(); // // 易派客商品Ids var allCommodityIds = Commodity.ObjectSet().Where(_ => !_.IsDel && YPKAppIdList.Contains(_.AppId)).Select(_ => _.Id); var commodityStocks = CommodityStock.ObjectSet().Where(_ => allCommodityIds.Contains(_.CommodityId) && skuIds.Contains(_.JDCode)).ToList(); var stockCommodityIds = commodityStocks.Select(_ => _.CommodityId).Distinct(); var stockCommodities = Commodity.ObjectSet().Where(_ => stockCommodityIds.Contains(_.Id)).ToList(); List <Guid> autoAuditPriceIds = new List <Guid>(); List <Guid> autoAuditCostPriceIds = new List <Guid>(); var autoAuditPriceAppIds = JDAuditMode.ObjectSet().Where(_ => _.PriceModeState == 0).Select(_ => _.AppId).ToList(); var autoAuditCostPriceAppIds = JDAuditMode.ObjectSet().Where(_ => _.CostModeState == 0).Select(_ => _.AppId).ToList(); List <SNPriceDto> SNPrices = new List <SNPriceDto>(); for (int i = 0; i < skuIds.Count; i += 30) { SNPrices.AddRange(SuningSV.GetPrice(skuIds.Skip(i).Take(30).ToList())); } ContextSession contextSession = ContextFactory.CurrentThreadContext; int count = 0; foreach (var group in commodityStocks.GroupBy(_ => _.CommodityId)) { var addCount = 0; var com = stockCommodities.Where(_ => _.Id == group.Key).FirstOrDefault(); var auditCom = AddCommodityAudit(com); foreach (var item in group) { var snprice = SNPrices.Where(_ => _.skuId == item.JDCode).FirstOrDefault(); if (snprice == null) { LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage-SKU 未获取到易派客价,商品Id: " + item.Id + ",SkuId: " + item.JDCode); continue; } // 进货价 if (!string.IsNullOrEmpty(snprice.price)) { // 对比审核表 var latestAuditData = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityStockId == item.Id && _.AuditType == 1 && _.JdCostPrice.HasValue).OrderByDescending(_ => _.SubTime).Select(_ => _.JdCostPrice).FirstOrDefault(); if (latestAuditData == null || latestAuditData.Value != Convert.ToDecimal(snprice.price)) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, com.AppId, item, Deploy.Enum.OperateTypeEnum.京东修改进货价); auditStock.AuditType = 1; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdPrice = string.IsNullOrEmpty(snprice.snPrice) ? Decimal.Zero : Convert.ToDecimal(snprice.snPrice); auditStock.JdCostPrice = string.IsNullOrEmpty(snprice.price) ? Decimal.Zero : Convert.ToDecimal(snprice.price); contextSession.SaveObject(auditStock); if (autoAuditCostPriceAppIds.Contains(com.AppId)) { autoAuditCostPriceIds.Add(auditStock.Id); } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 更新易派客商品进货价,商品Id: " + item.Id + ",SkuId: " + item.JDCode); } } // 售价 if (item.Price != Convert.ToDecimal(snprice.snPrice)) { // 对比审核表 var latestAuditData = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityStockId == item.Id && _.AuditType == 2 && _.JdPrice.HasValue).OrderByDescending(_ => _.SubTime).Select(_ => _.JdPrice).FirstOrDefault(); if (latestAuditData == null || latestAuditData.Value != Convert.ToDecimal(snprice.snPrice)) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, com.AppId, item, Deploy.Enum.OperateTypeEnum.京东修改现价); auditStock.AuditType = 2; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdPrice = Convert.ToDecimal(snprice.snPrice); contextSession.SaveObject(auditStock); if (autoAuditPriceAppIds.Contains(com.AppId)) { autoAuditPriceIds.Add(auditStock.Id); } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 更新易派客商品售价,商品Id: " + item.Id + ",SkuId: " + item.JDCode); } } } if (addCount > 0) { contextSession.SaveObject(auditCom); } if (count >= 200) { contextSession.SaveChanges(); count = 0; } } // 处理无属性商品,并Stock表中无数据的情况 count = 0; var commodityIds = allCommodityIds.Except(stockCommodityIds); var commodities = Commodity.ObjectSet().Where(_ => commodityIds.Contains(_.Id) && (string.IsNullOrEmpty(_.ComAttribute) || _.ComAttribute == "[]") && skuIds.Contains(_.JDCode)).ToList(); foreach (var com in commodities) { var snprice = SNPrices.Where(_ => _.skuId == com.JDCode).FirstOrDefault(); if (snprice == null) { LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage-SKU 未获取到 易派客价,商品Id: " + com.Id + ",SkuId: " + com.JDCode); continue; } var addCount = 0; var auditCom = AddCommodityAudit(com); // 进货价 if (!string.IsNullOrEmpty(snprice.price) && com.CostPrice != Convert.ToDecimal(snprice.price)) { // 对比审核表 var latestAuditData = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityId == com.Id && _.AuditType == 1 && _.JdCostPrice.HasValue).OrderByDescending(_ => _.SubTime).Select(_ => _.JdCostPrice).FirstOrDefault(); if (latestAuditData == null || latestAuditData.Value != Convert.ToDecimal(snprice.price)) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, com, Deploy.Enum.OperateTypeEnum.京东修改进货价); auditStock.AuditType = 1; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdCostPrice = Convert.ToDecimal(snprice.price); contextSession.SaveObject(auditStock); if (autoAuditCostPriceAppIds.Contains(com.AppId)) { autoAuditCostPriceIds.Add(auditStock.Id); } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 更新易派客商品进货价,商品Id: " + com.Id + ",SkuId: " + com.JDCode); } } // 售价 if (com.Price != Convert.ToDecimal(snprice.snPrice)) { // 对比审核表 var latestAuditData = JdAuditCommodityStock.ObjectSet().Where(_ => _.CommodityId == com.Id && _.AuditType == 2 && _.JdPrice.HasValue).OrderByDescending(_ => _.SubTime).Select(_ => _.JdPrice).FirstOrDefault(); if (latestAuditData == null || latestAuditData.Value != Convert.ToDecimal(snprice.snPrice)) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, com, Deploy.Enum.OperateTypeEnum.京东修改现价); auditStock.AuditType = 2; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdPrice = Convert.ToDecimal(snprice.snPrice); contextSession.SaveObject(auditStock); if (autoAuditPriceAppIds.Contains(com.AppId)) { autoAuditPriceIds.Add(auditStock.Id); } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 更新易派客商品售价,商品Id: " + com.Id + ",SkuId: " + com.JDCode); } } if (addCount > 0) { contextSession.SaveObject(auditCom); } if (count >= 200) { contextSession.SaveChanges(); count = 0; } } contextSession.SaveChanges(); // 自动审核 var auditComFacade = new JDAuditComFacade(); auditComFacade.ContextDTO = AuthorizeHelper.InitAuthorizeInfo(); if (autoAuditCostPriceIds.Count > 0) { auditComFacade.AuditJDCostPrice(autoAuditCostPriceIds, 1, "自动审核", 0, 0); } if (autoAuditPriceIds.Count > 0) { auditComFacade.AuditJDPrice(autoAuditPriceIds, 1, 0, "自动审核", 0); } // 删除消息 //JDSV.DelMessage(messages.Select(_ => _.Id).ToList()); } catch (Exception ex) { LogHelper.Error("SNJobHelper.AutoUpdatePrice 异常", ex); throw; } LogHelper.Info("SNJobHelper.AutoUpdatePriceByMessage 结束同步易派客商品价格"); }
private static List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO> GenegrateCommodityChangeDto(List <Guid> ids) { List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO> list = new List <Deploy.CustomDTO.CommodityChangeDTO>(); foreach (var item in ids) { #region //取出商品变动明细插入CommodityChange //取出Commodity表中编辑的数据 List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO> list1 = (from n in Commodity.ObjectSet() where n.Id == item select new Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO { CommodityId = n.Id, Name = n.Name, Code = n.Code, No_Number = n.No_Number, SubId = n.SubId, Price = n.Price, Stock = n.Stock, PicturesPath = n.PicturesPath, Description = n.Description, State = n.State, IsDel = n.IsDel, AppId = n.AppId, No_Code = n.No_Code, TotalCollection = n.TotalCollection, TotalReview = n.TotalReview, Salesvolume = n.Salesvolume, ModifiedOn = n.ModifiedOn, GroundTime = n.GroundTime, ComAttribute = n.ComAttribute, CategoryName = n.CategoryName, SortValue = n.SortValue, FreightTemplateId = n.FreightTemplateId, MarketPrice = n.MarketPrice, IsEnableSelfTake = n.IsEnableSelfTake, Weight = n.Weight, PricingMethod = n.PricingMethod, SaleAreas = n.SaleAreas, SharePercent = n.SharePercent, CommodityType = n.CommodityType, HtmlVideoPath = n.HtmlVideoPath, MobileVideoPath = n.MobileVideoPath, VideoPic = n.VideoPic, VideoName = n.VideoName, ScorePercent = n.ScorePercent, Duty = n.Duty, SpreadPercent = n.SpreadPercent, ScoreScale = n.ScoreScale, TaxRate = n.TaxRate, TaxClassCode = n.TaxClassCode, Unit = n.Unit, InputRax = n.InputRax, Barcode = n.Barcode, JDCode = n.JDCode, CostPrice = n.CostPrice, IsAssurance = n.IsAssurance, TechSpecs = n.TechSpecs, SaleService = n.SaleService, IsReturns = n.IsReturns, Isnsupport = n.Isnsupport, ServiceSettingId = n.ServiceSettingId, Type = n.Type, YJCouponActivityId = n.YJCouponActivityId, YJCouponType = n.YJCouponType, SubOn = n.SubTime, ModifiedId = n.ModifieId }).ToList(); //取出CommodityStock表中编辑的数据 List <Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO> list2 = (from n in Commodity.ObjectSet() join m in CommodityStock.ObjectSet() on n.Id equals m.CommodityId where m.CommodityId == item select new Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO { CommodityId = m.Id, Name = n.Name, Code = n.Code, No_Number = n.No_Number, SubId = n.SubId, Price = m.Price, Stock = m.Stock, PicturesPath = n.PicturesPath, Description = n.Description, State = n.State, IsDel = n.IsDel, AppId = n.AppId, No_Code = m.No_Code, TotalCollection = n.TotalCollection, TotalReview = n.TotalReview, Salesvolume = n.Salesvolume, ModifiedOn = n.ModifiedOn, GroundTime = n.GroundTime, ComAttribute = n.ComAttribute, CategoryName = n.CategoryName, SortValue = n.SortValue, FreightTemplateId = n.FreightTemplateId, MarketPrice = m.MarketPrice, IsEnableSelfTake = n.IsEnableSelfTake, Weight = n.Weight, PricingMethod = n.PricingMethod, SaleAreas = n.SaleAreas, SharePercent = n.SharePercent, CommodityType = n.CommodityType, HtmlVideoPath = n.HtmlVideoPath, MobileVideoPath = n.MobileVideoPath, VideoPic = n.VideoPic, VideoName = n.VideoName, ScorePercent = n.ScorePercent, Duty = m.Duty, SpreadPercent = n.SpreadPercent, ScoreScale = n.ScoreScale, TaxRate = n.TaxRate, TaxClassCode = n.TaxClassCode, Unit = n.Unit, InputRax = n.InputRax, Barcode = m.Barcode, JDCode = m.JDCode, CostPrice = m.CostPrice, IsAssurance = n.IsAssurance, TechSpecs = n.TechSpecs, SaleService = n.SaleService, IsReturns = n.IsReturns, Isnsupport = n.Isnsupport, ServiceSettingId = n.ServiceSettingId, Type = n.Type, YJCouponActivityId = n.YJCouponActivityId, YJCouponType = n.YJCouponType, SubOn = n.SubTime, ModifiedId = n.ModifieId }).ToList(); if (list2.Count() > 0) { list.AddRange(list2); } else { list.AddRange(list1); } #endregion } //Jinher.AMP.BTP.IBP.Facade.CommodityChangeFacade ChangeFacade = new Jinher.AMP.BTP.IBP.Facade.CommodityChangeFacade(); //ChangeFacade.ContextDTO = AuthorizeHelper.InitAuthorizeInfo(); //Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO DTO = ChangeFacade.SaveCommodityChange(list); return(list); }
public static void AutoSettingCommodityPrice() { LogHelper.Info("Jobs.AutoSettingCommodityPrice Begin......................................................"); try { ContextSession contextSession = ContextFactory.CurrentThreadContext; var apps = CommodityPriceFloat.ObjectSet().Where(p => !p.IsDel && p.EsAppId == YJB.Deploy.CustomDTO.YJBConsts.YJAppId).ToList(); LogHelper.Info("Begin update price, AppIds:" + JsonHelper.JsonSerializer(apps.Select(_ => _.AppIds))); var appIds = apps.SelectMany(_ => _.AppIds.Split(',')).Select(_ => new Guid(_)); LogHelper.Info("Begin update price, AppGuidIds:" + JsonHelper.JsonSerializer(appIds)); var commodityQuery = Commodity.ObjectSet().Where(_ => appIds.Contains(_.AppId)); var commoditys = commodityQuery.Where(_ => _.CostPrice >= _.Price).ToList(); var commodityIds = commoditys.Select(_ => _.Id).ToList(); var commodityStocks = CommodityStock.ObjectSet().Where(_ => commodityQuery.Any(c => c.Id == _.CommodityId) && _.CostPrice >= _.Price).ToList(); List <Guid> updateCommodityIds = new List <Guid>(); LogHelper.Info("Begin Commodity.........." + commoditys.Count + "............................................"); foreach (var com in commoditys) { LogHelper.Info("Begin update price, CommodityId:" + com.Id + ", AppId:" + com.AppId); var priceFloat = apps.Find(_ => _.AppIds.Split(',').Select(appId => new Guid(appId)).Contains(com.AppId)); if (com.CostPrice >= com.Price) { LogHelper.Info("CostPrice:" + com.CostPrice + ", FloatPrice:" + priceFloat.FloatPrice); com.Price = (com.CostPrice ?? 0) + priceFloat.FloatPrice; com.EntityState = EntityState.Modified; contextSession.SaveObject(com); } // stock var stocks = commodityStocks.Where(_ => _.CommodityId == com.Id).ToList(); foreach (var stock in stocks) { stock.Price = (stock.CostPrice ?? 0) + priceFloat.FloatPrice; stock.EntityState = EntityState.Modified; contextSession.SaveObject(stock); } updateCommodityIds.Add(com.Id); // 保存到商品明细报表 if (updateCommodityIds.Count >= 100) { SaveCommodityChange(updateCommodityIds, contextSession); contextSession.SaveChanges(); updateCommodityIds = new List <Guid>(); } } // 商品表价格没问题,但是SKU表价格有问题的商品 var otherCommodityIds = commodityStocks.Select(_ => _.CommodityId).Distinct().Except(commodityIds).ToList(); var otherCommodities = Commodity.ObjectSet().Where(_ => otherCommodityIds.Contains(_.Id)).ToList(); LogHelper.Info("Begin CommodityStock.........." + otherCommodities.Count + "............................................"); foreach (var com in otherCommodities) { LogHelper.Info("Begin update price, CommodityId:" + com.Id + ", AppId:" + com.AppId); var priceFloat = apps.Find(_ => _.AppIds.Split(',').Select(appId => new Guid(appId)).Contains(com.AppId)); // stock var stocks = commodityStocks.Where(_ => _.CommodityId == com.Id).ToList(); foreach (var stock in stocks) { stock.Price = (stock.CostPrice ?? 0) + priceFloat.FloatPrice; stock.EntityState = EntityState.Modified; contextSession.SaveObject(stock); } updateCommodityIds.Add(com.Id); // 保存到商品明细报表 if (updateCommodityIds.Count >= 100) { SaveCommodityChange(updateCommodityIds, contextSession); contextSession.SaveChanges(); updateCommodityIds = new List <Guid>(); } } SaveCommodityChange(updateCommodityIds, contextSession); contextSession.SaveChanges(); } catch (Exception ex) { LogHelper.Error("Jobs.AutoSettingCommodityPrice 异常", ex); } LogHelper.Info("Jobs.AutoSettingCommodityPrice End......................................................"); }
/// <summary> /// 同步价格 /// </summary> /// <param name="skuIds"></param> /// <param name="priceDtos"></param> /// <param name="type"></param> /// <returns></returns> public static int UpdateCommodityPrice(List <string> skuIds, List <SNPriceDto> priceDtos, ThirdECommerceTypeEnum type) { try { ContextSession contextSession = ContextFactory.CurrentThreadContext; var floatPrice = GetFloatPrice(); List <Commodity> commoditys = new List <Commodity>(); if (type == ThirdECommerceTypeEnum.SuNingYiGou) { commoditys = Commodity.ObjectSet().Where(p => skuIds.Contains(p.JDCode) && CustomConfig.SnAppIdList.Contains(p.AppId)).ToList(); } if (type == ThirdECommerceTypeEnum.JingDongDaKeHu) { commoditys = Commodity.ObjectSet().Where(p => skuIds.Contains(p.JDCode) && CustomConfig.JdAppIdList.Contains(p.AppId)).ToList(); } var commodityIds = commoditys.Select(p => p.Id).ToList(); var commodityStocks = CommodityStock.ObjectSet().Where(p => commodityIds.Contains(p.CommodityId)).ToList(); var commodityStockIds = commodityStocks.Select(p => p.Id).ToList(); commoditys.ForEach(p => { var priceDto = priceDtos.Where(x => x.skuId == p.JDCode).FirstOrDefault(); var price = Decimal.Zero; var snPrice = Decimal.Zero; if (priceDto != null) { if (!string.IsNullOrEmpty(priceDto.price)) { price = Convert.ToDecimal(priceDto.price); } if (!string.IsNullOrEmpty(priceDto.snPrice)) { snPrice = Convert.ToDecimal(priceDto.snPrice); } } if (priceDto == null) { if (p.State == 0) { LogHelper.Info("未获取到商品价格信息,商品下架:CommodityId=" + p.Id); p.State = 1; p.ModifiedOn = DateTime.Now; } return; } if ((price <= 0 || snPrice <= 0)) { if (p.State == 0) { LogHelper.Info("进价或售价为0,商品下架:CommodityId=" + p.Id); p.State = 1; p.ModifiedOn = DateTime.Now; } return; } var commodityStock = commodityStocks.FirstOrDefault(x => x.CommodityId == p.Id); if (p.CostPrice != price) { if (price >= snPrice) { snPrice = Convert.ToDecimal(priceDto.price) + floatPrice; priceDto.snPrice = snPrice.ToString(); } LogHelper.Info(string.Format("商品进价从{0}调整为{1}:CommodityId={2}", p.CostPrice, priceDto.price, p.Id)); LogHelper.Info(string.Format("商品售价从{0}调整为{1}", p.Price, priceDto.snPrice)); p.CostPrice = price; p.Price = snPrice; p.ModifiedOn = DateTime.Now; if (commodityStock != null) { LogHelper.Info(string.Format("商品单品进价从{0}调整为{1}:CommodityStockId={2}", commodityStock.CostPrice, priceDto.price, commodityStock.Id)); LogHelper.Info(string.Format("商品单品售价从{0}调整为{1}", commodityStock.Price, priceDto.snPrice)); commodityStock.CostPrice = price; commodityStock.Price = snPrice; commodityStock.ModifiedOn = DateTime.Now; } } else if (p.CostPrice >= p.Price || (commodityStock != null && commodityStock.CostPrice >= commodityStock.Price)) { if (price >= snPrice) { snPrice = Convert.ToDecimal(priceDto.price) + floatPrice; priceDto.snPrice = snPrice.ToString(); } LogHelper.Info(string.Format("商品售价从{0}调整为{1}:CommodityId={2}", p.Price, priceDto.snPrice, p.Id)); p.Price = snPrice; p.ModifiedOn = DateTime.Now; if (commodityStock != null) { LogHelper.Info(string.Format("商品单品售价从{0}调整为{1}:CommodityStockId={2}", commodityStock.Price, priceDto.snPrice, commodityStock.Id)); commodityStock.Price = snPrice; commodityStock.ModifiedOn = DateTime.Now; } } }); var count = contextSession.SaveChanges(); if (count > 0) { LogHelper.Info("调整商品价格:count=" + count); } return(count); } catch (Exception ex) { LogHelper.Error(ex.ToString()); } return(0); }
/// <summary> /// 获取统计数据 /// </summary> /// <returns></returns> public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CustomDTO.totalNum> GetTotalListExt(Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO Search) { LogHelper.Debug("CommodityChangeBP.GetTotalListExt,入参:" + JsonHelper.JsonSerializer(Search)); try { var query = from m in Commodity.ObjectSet() join n in CommodityStock.ObjectSet() on m.Id equals n.CommodityId into CommodityList from com in CommodityList.DefaultIfEmpty() where Search.Appids.Contains(m.AppId) select new Jinher.AMP.BTP.Deploy.CustomDTO.CommodityChangeDTO { Id = com.Id, CommodityId = com.CommodityId, AppId = m.AppId, Barcode = com.Barcode, No_Code = com.No_Code, JDCode = com.JDCode, //备注编码 Name = m.Name, SubId = m.SubId, SubOn = com.SubTime, ModifiedId = m.ModifieId, ModifiedOn = com.ModifiedOn, State = m.State, IsDel = m.IsDel }; #region 查询条件 //根据供应商 if (Search.AppidsList.Count > 0) { query = query.Where(p => Search.AppidsList.Contains(p.AppId)); } //商铺名称 if (Search.AppId != Guid.Empty) { query = query.Where(p => p.AppId == Search.AppId); } //商品名称 if (!string.IsNullOrEmpty(Search.Name)) { query = query.Where(p => Search.Name.Contains(p.Name) || p.Name.Contains(Search.Name)); } //备注编码 if (!string.IsNullOrEmpty(Search.JDCode)) { query = query.Where(p => p.JDCode == Search.JDCode); } //商品条形码 if (!string.IsNullOrEmpty(Search.Barcode)) { query = query.Where(p => p.Barcode == Search.Barcode); } //发布人 if (Search.SubId != Guid.Empty) { query = query.Where(p => p.SubId == Search.SubId); } if (!string.IsNullOrEmpty(Search.SubStarTime)) { var StartTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value; StartTime = DateTime.Parse(Search.SubStarTime); query = query.Where(p => p.SubOn >= StartTime); } if (!string.IsNullOrEmpty(Search.SubEndTime)) { var EndTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value; EndTime = DateTime.Parse(Search.SubEndTime).AddDays(1); query = query.Where(p => p.SubOn <= EndTime); } if (Search.ModifiedId != Guid.Empty) { query = query.Where(p => p.ModifiedId == Search.ModifiedId); } if (!string.IsNullOrEmpty(Search.ModStarTime)) { var StartTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value; StartTime = DateTime.Parse(Search.ModStarTime); query = query.Where(p => p.ModifiedOn >= StartTime); } if (!string.IsNullOrEmpty(Search.ModEndTime)) { var EndTime = System.Data.SqlTypes.SqlDateTime.MinValue.Value; EndTime = DateTime.Parse(Search.ModEndTime).AddDays(1); query = query.Where(p => p.ModifiedOn <= EndTime); } if (Search.State != -1) { if (Search.State == 3) { //已删除的数据 query = query.Where(p => p.IsDel == true); } else { query = query.Where(p => p.State == Search.State && p.IsDel == false); } } #endregion totalNum num = new totalNum(); num.totalGoods = query.Count(); num.selling = query.Where(p => p.State == 0 && p.IsDel == false).Count(); num.soldout = query.Where(p => p.State == 1 && p.IsDel == false).Count(); num.isdel = query.Where(p => p.IsDel == true).Count(); List <totalNum> list = new List <totalNum>(); list.Add(num); return(list); } catch (Exception ex) { LogHelper.Error("CommodityChangeBP.GetTotalListExt异常", ex); } return(new List <totalNum>()); }
/// <summary> /// 根据用户ID查询收藏商品 /// </summary> /// <param name="userId">商品ID</param> /// <param name="appId">appId</param> /// <returns></returns> public System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.CustomDTO.CommoditySDTO> GetCollectionItemsExt(System.Guid userId, System.Guid appId) { var commodityList = (from data in Collection.ObjectSet() join data1 in Commodity.ObjectSet() on data.CommodityId equals data1.Id where data.UserId == userId && data.AppId == appId && data1.IsDel == false && data1.CommodityType == 0 select new CommoditySDTO { Name = data1.Name, Id = data1.Id, Price = data1.Price, Pic = data1.PicturesPath, Stock = data1.Stock, State = data1.State, CollectNum = data1.TotalCollection, ReviewNum = data1.TotalReview, Total = data1.Salesvolume }).ToList(); DateTime now = DateTime.Now; List <Guid> commodityIds = commodityList.Select(c => c.Id).ToList(); //读今日折扣表 try { //zgx-modify var comAttributeList = (from a in CommodityStock.ObjectSet() where commodityIds.Contains(a.CommodityId) group a by a.CommodityId into g select new { minPrice = g.Min(a => a.Price), maxPrice = g.Max(a => a.Price), CommodityId = g.Key }).ToList(); var promotionDic = TodayPromotion.GetCurrentPromotionsWithPresell(commodityIds); foreach (var commodity in commodityList) { //zgx-modify if (comAttributeList != null && comAttributeList.Count > 0) { var comAttribute = comAttributeList.Find(r => r.CommodityId == commodity.Id); if (comAttribute != null) { commodity.MaxPrice = comAttribute.maxPrice; commodity.MinPrice = comAttribute.minPrice; } } bool isdi = false; foreach (var com in promotionDic) { if (com.CommodityId == commodity.Id) { commodity.LimitBuyEach = com.LimitBuyEach == null ? -1 : com.LimitBuyEach; commodity.LimitBuyTotal = com.LimitBuyTotal == null ? -1 : com.LimitBuyTotal; commodity.SurplusLimitBuyTotal = com.SurplusLimitBuyTotal == null ? 0 : com.SurplusLimitBuyTotal; if (com.DiscountPrice > -1) { commodity.DiscountPrice = Convert.ToDecimal(com.DiscountPrice); commodity.Intensity = 10; isdi = true; break; } else { commodity.DiscountPrice = -1; commodity.Intensity = com.Intensity; isdi = true; break; } } } if (!isdi) { commodity.DiscountPrice = -1; commodity.Intensity = 10; commodity.LimitBuyEach = -1; commodity.LimitBuyTotal = -1; commodity.SurplusLimitBuyTotal = -1; } //if (promotionDic.ContainsKey(commodity.Id)) //{ // commodity.Intensity = promotionDic[commodity.Id]; //} //else //{ // commodity.Intensity = 10; //} } } catch (Exception e) { Jinher.JAP.Common.Loging.LogHelper.Error(string.Format("商品列表查询错误,userId{111},appId{111}", userId, appId), e); } return(commodityList); }
/// <summary> /// 全量获取严选价格信息 /// </summary> public static Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO AutoUpdateYXComPrice() { Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO result = new Deploy.CustomDTO.ResultDTO() { isSuccess = false, ResultCode = 1 }; if (isSyncYXComInfo) { LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 正在全量获取严选价格信息,跳过。。。"); return(result); } isSyncYXComInfo = true; LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 开始写入严选价格信息"); try { ContextSession contextSession = ContextFactory.CurrentThreadContext; int count = 0; AutoGetAllSPU(); var YXComList = YXComInfo.ObjectSet().ToList(); var UpdateSpuList = YXComList.Select(s => s.SPU).ToList(); List <YXComDetailDTO> YXComLists = new List <YXComDetailDTO>(); for (int i = 0; i < YXComList.Count; i += 30) { YXComLists.AddRange(YXSV.GetComDetailList(UpdateSpuList.Skip(i).Take(30).ToList())); //Thread.Sleep(1000); } foreach (var YXComlist in YXComLists) { foreach (var item in YXComlist.skuList) { YXComInfo YXCom = YXComInfo.CreateYXComInfo(); YXCom.Id = Guid.NewGuid(); YXCom.SPU = YXComlist.id; YXCom.SKU = item.id; YXCom.Price = item.channelPrice; YXCom.CostPrice = item.channelPrice * Convert.ToDecimal(0.8); YXCom.SubTime = DateTime.Now; contextSession.SaveObject(YXCom); } } count = contextSession.SaveChanges(); YXComInfo.ObjectSet().Context.ExecuteStoreCommand("delete from YXComInfo where SKU is null"); //取出最细你的严选价格信息 var YXComNewList = YXComInfo.ObjectSet().ToList(); //取出所有网易严选的商品信息 Guid AppId = new Guid("1d769e14-f870-4b19-82ab-875a9e8678e4"); var YXCom1 = Commodity.ObjectSet().Where(p => p.AppId == AppId).ToList(); LogHelper.Info(string.Format("取出严选商品条数:{0}", YXCom1.Count())); int savecount = 0; //取出定时改价中严选商品 List <Guid> YXappids = CustomConfig.YxAppIdList; var timingComIds = Jinher.AMP.BTP.TPS.YJBSV.GetYXChangeComInfo(YXappids).Data.Select(s => s.CommodityId).ToList(); for (int i = 0; i < YXCom1.Count; i += 100) { var YxComList = YXCom1.Skip(i).Take(100).ToList();//取出商品id var ComIds = YxComList.Select(s => s.Id); LogHelper.Info(string.Format("严选商品Id:{0}", JsonHelper.JsonSerializer(ComIds))); var YXComStock = CommodityStock.ObjectSet().Where(p => ComIds.Contains(p.CommodityId) && !timingComIds.Contains(p.Id)).ToList(); foreach (var item in YXComStock) { LogHelper.Info(string.Format("获取严选sku:{0}", item.JDCode)); var NewPriceInfo = YXComNewList.FirstOrDefault(p => p.SKU == item.JDCode); if (NewPriceInfo == null) { LogHelper.Info(string.Format("不存在严选sku:{0}", item.JDCode)); item.IsDel = true; item.ModifiedOn = DateTime.Now; } if (NewPriceInfo != null && NewPriceInfo.Price.HasValue && NewPriceInfo.CostPrice.HasValue && NewPriceInfo.Price > 0 && NewPriceInfo.CostPrice > 0) { LogHelper.Info(string.Format("获取严选商品sku:{0},售价:{1},进货价:{2}", NewPriceInfo.SKU, NewPriceInfo.Price, NewPriceInfo.CostPrice)); item.Price = NewPriceInfo.Price ?? item.Price; item.CostPrice = NewPriceInfo.CostPrice ?? item.CostPrice; item.IsDel = false; item.ModifiedOn = DateTime.Now; } } foreach (var item1 in YxComList) { var YXComMinPrice = YXComNewList.Where(p => p.SPU == item1.Barcode).OrderBy(p => p.Price).FirstOrDefault(); if (YXComMinPrice == null) { LogHelper.Info(string.Format("不存在严选SPU:{0}", item1.Barcode)); item1.IsDel = true; item1.State = 0; } if (YXComMinPrice != null && YXComMinPrice.Price > 0 && YXComMinPrice.CostPrice > 0) { LogHelper.Info(string.Format("获取严选商品最小价格sku:{0},售价:{1},进货价:{2}", YXComMinPrice.SKU, YXComMinPrice.Price, YXComMinPrice.CostPrice)); item1.Price = YXComMinPrice.Price ?? item1.Price; item1.CostPrice = YXComMinPrice.CostPrice ?? item1.CostPrice; item1.ModifiedOn = DateTime.Now; } } savecount += contextSession.SaveChanges(); LogHelper.Info(string.Format("获取苏宁价格保存条数:{0}", count)); } result.isSuccess = true; result.Message = "严选接口保存成功" + count + "条;商品表修改条数:" + savecount; isSyncYXComInfo = false; return(result); } catch (Exception ex) { LogHelper.Error("YXJobHelper.AutoUpdateYXComPrice 异常", ex); isSyncYXComInfo = false; return(result); } }
/// <summary> /// 全量获取严选价格信息 /// </summary> public static void AutoUpdateYXComInfo() { if (isSyncYXComInfo) { LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 正在全量获取严选价格信息,跳过。。。"); return; } isSyncYXComInfo = true; LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 开始写入严选价格信息"); try { AutoGetAllSPU(); var YXComList = YXComInfo.ObjectSet().ToList(); var UpdateSpuList = YXComList.Select(s => s.SPU).ToList(); List <YXComDetailDTO> YXComLists = new List <YXComDetailDTO>(); for (int i = 0; i < YXComList.Count; i += 30) { YXComLists.AddRange(YXSV.GetComDetailList(UpdateSpuList.Skip(i).Take(30).ToList())); //Thread.Sleep(1000); } ContextSession contextSession = ContextFactory.CurrentThreadContext; List <string> SkuIds = new List <string>(); foreach (var YXComlist in YXComLists) { foreach (var item in YXComlist.skuList) { YXComInfo YXCom = YXComInfo.CreateYXComInfo(); YXCom.Id = Guid.NewGuid(); YXCom.SPU = YXComlist.id; YXCom.SKU = item.id; YXCom.Price = item.channelPrice; YXCom.CostPrice = item.channelPrice * Convert.ToDecimal(0.8); YXCom.SubTime = DateTime.Now; contextSession.SaveObject(YXCom); SkuIds.Add(item.id); } } int count1 = contextSession.SaveChanges(); YXComInfo.ObjectSet().Context.ExecuteStoreCommand("delete from YXComInfo where SKU is null"); #region //取出定时改价中严选商品 List <Guid> YXappids = CustomConfig.YxAppIdList; var timingComIds = Jinher.AMP.BTP.TPS.YJBSV.GetYXChangeComInfo(YXappids).Data.Select(s => s.CommodityId).ToList(); //最新价格更新到YXComInfo,对比库存表和价格审核表 判断是否需要审核(过滤掉定时改价中严选的商品) var ComStockList = CommodityStock.ObjectSet().Where(p => SkuIds.Contains(p.JDCode) && !timingComIds.Contains(p.Id)).ToList(); var ComIds = ComStockList.Select(s => s.CommodityId).Distinct().ToList(); var ComList = Commodity.ObjectSet().Where(p => ComIds.Contains(p.Id)).ToList(); var YXComInfoList = YXComInfo.ObjectSet().Where(p => SkuIds.Contains(p.SKU)).ToList(); var AuditAuditModeApp = JDAuditMode.ObjectSet().Where(_ => _.PriceModeState == 0).Select(_ => _.AppId).ToList(); List <Guid> autoAuditPriceIds = new List <Guid>(); int count = 0; foreach (var group in ComList) { int addCount = 0; var Com = ComList.FirstOrDefault(p => p.Id == group.Id); var auditCom = AddCommodityAudit(Com); var ComStocks = ComStockList.Where(p => p.CommodityId == group.Id).ToList(); foreach (var item in ComStocks) { var YXComNew = YXComInfoList.FirstOrDefault(p => p.SKU == item.JDCode); if (YXComNew != null && YXComNew.Price.HasValue && item.Price != YXComNew.Price) { var latestAuditData = JdAuditCommodityStock.ObjectSet().Where(p => p.CommodityStockId == item.Id && p.AuditType == 2).OrderByDescending(p => p.SubTime).FirstOrDefault(); if (latestAuditData == null || latestAuditData.Price != item.Price) { count++; addCount++; var auditStock = AddCommodityStockAudit(contextSession, group.AppId, item, Deploy.Enum.OperateTypeEnum.京东修改现价); auditStock.AuditType = 2; auditStock.JdAuditCommodityId = auditCom.Id; auditStock.JdPrice = YXComNew.Price; auditStock.CostPrice = YXComNew.Price * Convert.ToDecimal(0.8); contextSession.SaveObject(auditStock); if (AuditAuditModeApp.Contains(group.AppId)) { autoAuditPriceIds.Add(auditStock.Id); } LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 更新商品售价,商品Id: " + item.Id + ",SkuId: " + item.JDCode); } } } if (addCount > 0) { contextSession.SaveObject(auditCom); } } int ccc = contextSession.SaveChanges(); // 自动审核 var auditComFacade = new JDAuditComFacade(); auditComFacade.ContextDTO = AuthorizeHelper.InitAuthorizeInfo(); if (autoAuditPriceIds.Count > 0) { auditComFacade.AuditJDCostPrice(autoAuditPriceIds, 1, "自动审核", 0, 0); } #endregion } catch (Exception ex) { LogHelper.Error("YXJobHelper.AutoUpdateYXComInfo 异常", ex); isSyncYXComInfo = false; throw; } LogHelper.Info("YXJobHelper.AutoUpdateYXComInfo 全量获取严选商品信息"); isSyncYXComInfo = false; }
/// <summary> /// 严选库存回调执行方法 /// </summary> /// <param name="sku"></param> public static void SkuCheckStock(List <SkuCheck> sku) { ContextSession contextSession = ContextFactory.CurrentThreadContext; var SkuList = sku.Select(s => s.skuId).ToList(); //取出库存表中所有的skuid var stockList = (from m in Commodity.ObjectSet() join n in CommodityStock.ObjectSet() on m.Id equals n.CommodityId where CustomConfig.YxAppIdList.Contains(m.AppId) && n.IsDel == false && m.IsDel == false && SkuList.Contains(n.JDCode) select n).ToList(); if (!stockList.Any()) { LogHelper.Info("JdOrderHelper.SkuCheckStock 店铺中未找到商品,跳过~"); return; } List <Guid> ComIds = new List <Guid>(); //更新库存 foreach (var item in sku) { var ComStock = stockList.FirstOrDefault(p => p.JDCode == item.skuId); if (ComStock != null) { ComStock.Stock = item.count; ComStock.ModifiedOn = DateTime.Now; ComIds.Add(ComStock.CommodityId); } } int mmm = contextSession.SaveChanges(); #region 重新计算Commodity表库存信息 //出去所有严选商品信息 var commodity = Commodity.ObjectSet().Where(p => ComIds.Distinct().Contains(p.Id) && p.IsDel == false).ToList(); var comids = commodity.Select(s => s.Id).ToList(); var commodityStock = CommodityStock.ObjectSet().Where(p => comids.Contains(p.CommodityId)).ToList(); var AuditModeApp = JDAuditMode.ObjectSet().Where(_ => _.StockModeState == 0).Select(_ => _.AppId).ToList(); //库存自动审核appid集合 List <Guid> NoticeComIds = new List <Guid>(); //到货提醒商品Id foreach (var item in commodity) { var StockNo = commodityStock.Where(p => p.CommodityId == item.Id).Sum(s => s.Stock); if (StockNo == 0)//无库存商品下架处理 { item.State = 1; } else if (item.State == 1 && StockNo > 0)//有库存上架处理审核处理 { item.State = 0; } if (item.Stock == 0 && StockNo > 0 && item.State == 0) { NoticeComIds.Add(item.Id); } item.Stock = StockNo; item.ModifiedOn = DateTime.Now; } int nnn = contextSession.SaveChanges(); //调用到货提醒接口 if (NoticeComIds.Any()) { for (int i = 0; i < NoticeComIds.Count; i += 30) { ZPHSV.SendStockNotifications(NoticeComIds.Skip(i).Take(30).ToList()); } } #endregion }
private static JdAuditCommodityStock AddCommodityStockAudit(ContextSession contextSession, Guid appId, CommodityStock stock, Jinher.AMP.BTP.Deploy.Enum.OperateTypeEnum type) { //添加审核表信息 AuditManage AuditInfo = AuditManage.CreateAuditManage(); AuditInfo.Status = 0; //0 待审核 1 审核通过 2 3审核不通过 4 已撤销 AuditInfo.EsAppId = Jinher.AMP.YJB.Deploy.CustomDTO.YJBConsts.YJAppId; AuditInfo.AppId = appId; AuditInfo.ApplyUserId = Jinher.JAP.BF.BE.Deploy.Base.ContextDTO.Current.LoginUserID; AuditInfo.ApplyTime = DateTime.Now; AuditInfo.Action = (int)type; contextSession.SaveObject(AuditInfo); JdAuditCommodityStock auditComStock = JdAuditCommodityStock.CreateJdAuditCommodityStock(); auditComStock.Id = AuditInfo.Id; auditComStock.CommodityStockId = stock.Id; auditComStock.CommodityId = stock.CommodityId; auditComStock.ComAttribute = stock.ComAttribute; auditComStock.Price = stock.Price; auditComStock.Stock = stock.Stock; auditComStock.MarketPrice = stock.MarketPrice; auditComStock.SubTime = stock.SubTime; auditComStock.ModifiedOn = DateTime.Now; auditComStock.Duty = stock.Duty; auditComStock.Barcode = stock.Barcode; auditComStock.No_Code = stock.Code; auditComStock.JDCode = stock.JDCode; auditComStock.CostPrice = stock.CostPrice; auditComStock.ThumImg = stock.ThumImg; auditComStock.CarouselImgs = stock.CarouselImgs; contextSession.SaveObject(AuditInfo); return(auditComStock); }
public static void InsertDataInShoppingCartItems() { int pageIndex = 1; int pageSize = 1000; ContextSession contextSession = ContextFactory.CurrentThreadContext; var listShop = ShoppingCartItems.ObjectSet().Select(t => t).OrderBy(t => t.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); while (listShop.Count == pageSize) { foreach (var itemShop in listShop) { var attrsShop = itemShop.ComAttributeIds.Replace("null", "") .Replace("nil", "") .Replace("undefined", ""); var arr = attrsShop.Split(','); if (arr[0] != "" && arr[1] != "") { var list = CommodityStock.ObjectSet().Where(t => t.CommodityId == itemShop.CommodityId). Select(t => t).ToList(); foreach (var item in list) { var attrs = JsonHelper.JsonDeserialize <List <ComAttributeDTO> >(item.ComAttribute); if ((attrs[0].SecondAttribute == arr[0] && attrs[1].SecondAttribute == arr[1]) || (attrs[0].SecondAttribute == arr[1] && attrs[1].SecondAttribute == arr[0])) { itemShop.CommodityStockId = item.Id; itemShop.ModifiedOn = DateTime.Now; itemShop.EntityState = System.Data.EntityState.Modified; } } contextSession.SaveChanges(); pageIndex++; listShop = ShoppingCartItems.ObjectSet().Select(t => t).OrderBy(t => t.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } } } if (listShop.Count > 0) { foreach (var itemShop in listShop) { var attrsShop = itemShop.ComAttributeIds.Replace("null", "") .Replace("nil", "") .Replace("undefined", ""); var arr = attrsShop.Split(','); if (arr[0] != "" && arr[1] != "") { var list = CommodityStock.ObjectSet().Where(t => t.CommodityId == itemShop.CommodityId). Select(t => t).ToList(); foreach (var item in list) { var attrs = JsonHelper.JsonDeserialize <List <ComAttributeDTO> >(item.ComAttribute); if ((attrs[0].SecondAttribute == arr[0] && attrs[1].SecondAttribute == arr[1]) || (attrs[0].SecondAttribute == arr[1] && attrs[1].SecondAttribute == arr[0])) { itemShop.CommodityStockId = item.Id; itemShop.ModifiedOn = DateTime.Now; itemShop.EntityState = System.Data.EntityState.Modified; } } contextSession.SaveChanges(); } } } }
/// <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); }
/// <summary> /// 全量同步严选库存信息 /// </summary> public static Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO AutoSyncAllStockNum() { Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO result = new Deploy.CustomDTO.ResultDTO() { isSuccess = false, ResultCode = 1 }; LogHelper.Info("YXJobHelper.AutoSyncAllStockNum 开始写入严选库存信息"); try { ContextSession contextSession = ContextFactory.CurrentThreadContext; Guid AppId = new Guid("1d769e14-f870-4b19-82ab-875a9e8678e4"); //取出库存表中所有的skuid var stockList = (from m in Commodity.ObjectSet() join n in CommodityStock.ObjectSet() on m.Id equals n.CommodityId where m.AppId == AppId && m.IsDel == false && n.IsDel == false select n).ToList(); //取出所有SkuID var SkuidList = stockList.OrderBy(p => p.SubTime).Select(s => s.JDCode).ToList(); List <StockDTO> YXstockList = new List <StockDTO>(); for (int i = 0; i < SkuidList.Count; i += 99) { LogHelper.Info(string.Format("严选sku:{0}", JsonHelper.JsonSerializer(SkuidList.Skip(i).Take(99).ToList()))); YXstockList.AddRange(YXSV.GetStockNum(SkuidList.Skip(i).Take(99).ToList())); Thread.Sleep(1000); } if (!YXstockList.Any()) { LogHelper.Info("YXJobHelper.AutoSyncAllStockNum 未获取到严选库存信息,跳出~"); return(result); } //更新库存 foreach (var item in stockList) { var YXStock = YXstockList.FirstOrDefault(p => p.skuId == item.JDCode); if (YXStock != null) { item.Stock = YXStock.inventory; item.State = 0; item.IsDel = false; } else { item.Stock = 0; item.State = 1; item.IsDel = true; } item.ModifiedOn = DateTime.Now; } int countstock = contextSession.SaveChanges(); LogHelper.Info(string.Format("严选库存更新库存保存条数:{0}", countstock)); #region 重新计算Commodity表库存信息 //出去所有严选商品信息 var commodity = Commodity.ObjectSet().Where(p => CustomConfig.YxAppIdList.Contains(p.AppId) && p.IsDel == false).ToList(); var comids = commodity.Select(s => s.Id).ToList(); var commodityStock = CommodityStock.ObjectSet().Where(p => comids.Contains(p.CommodityId)).ToList(); //var AuditModeApp = JDAuditMode.ObjectSet().Where(_ => _.StockModeState == 0).Select(_ => _.AppId).ToList();//库存自动审核appid集合 //到货提醒商品Id集合 List <Guid> NoticeComIds = new List <Guid>(); foreach (var item in commodity) { var StockNo = commodityStock.Where(p => p.CommodityId == item.Id).Sum(s => s.Stock); if (StockNo == 0)//无库存商品下架处理 { item.State = 1; } else if (item.State == 1 && StockNo > 0)//有库存上架处理审核处理 { item.State = 0; } if (item.Stock == 0 && StockNo > 0) { NoticeComIds.Add(item.Id); } item.Stock = StockNo; item.ModifiedOn = DateTime.Now; } int countCom = contextSession.SaveChanges(); LogHelper.Info(string.Format("严选库存更新库存保存条数:{0}", countCom)); result.isSuccess = true; result.ResultCode = 0; result.Message = "库存表保存条数:{0}" + countstock + "商品表保存条数:{1}" + countCom; return(result); #endregion } catch (Exception ex) { LogHelper.Error("YXJobHelper.AutoSyncAllStockNum 异常", ex); return(result); } }