public bool DeleteCommodity(Commodity commodity) { if (commodity == null) return false; _unitOfWork.CommodityRepository.Delete(commodity); _unitOfWork.Save(); return true; }
IEnumerator ProduceCommodity() { readyToProduce = false; yield return new WaitForSeconds(timeToProduce); if(bldgScript.readyToProduce) { Commodity tempCommod; tempCommod = new Commodity(); tempCommod.nameOf = bldgScript.product.ToString(); tempCommod.numOf = 1; curLoad++; npcCarryScript.AddCommodity(tempCommod); readyToProduce = true; if(curLoad < maxLoad) { StartCoroutine("ProduceCommodity"); } else { Deliver(); } yield return null; } else { //Deliver goods and pick up supplies Deliver(); yield return null; } }
public void AddCommodity(Commodity commod) { Debug.Log ("Add to NPC"); if(carryCommodity.Count > 0) { foreach(Commodity com in carryCommodity) { if(com.nameOf == commod.nameOf) { com.numOf += commod.numOf; } else { carryCommodity.Add(commod); } } } else { carryCommodity.Add(commod); } nameOf = carryCommodity[0].nameOf; }
//private string[] neighbours; //public Noble lastOwnerKnown { get; private set; } //public bool commodityKnown { get; private set; } public Province(string name, ProvinceScript pS, Commodity c, Noble o) { provinceName = name; provinceScript = pS; commodity = c; owner = o; //MakeNeighbours(); }
public Commodity(Commodity Commodity) { this.EDDBID = Commodity.EDDBID; this.Name = Commodity.Name; this.Category = Commodity.Category; this.AveragePrice = Commodity.AveragePrice; this.Rare = Commodity.Rare; }
public Business(string seller, Commodity commodity, int level, double count, double price) { this.Seller = seller; this.Commodity = commodity; this.Level = level; this.Count = count; this.Price = price; commodity.Add(this); }
public float BuySuppliesSM(Commodity commod) { bool sold; sold = RemoveCommodity(commod); if(sold) { return 1f; } else { return 0f; } }
// Use this for initialization void Start () { prodCommod = new Commodity(); prodCommod.nameOf = product.ToString(); suppCommod = new Commodity(); suppCommod.nameOf = "None"; supplyList.Add(suppCommod); productList.Add(prodCommod); curWorkers = 0; maxWorkers = 4; }
void AddCommodity(Commodity commod) { if(commodityList.Count > 0) { foreach(Market_Commodity c in goodsList) { if(c.nameOf == commod.nameOf) { c.atMarket += commod.numOf; Debug.Log ("At Market " + c.atMarket + " adding " +commod.numOf); } } } }
public ActionResult Create(Commodity commodity) { var commodityToCreate = new Commodity(); TransferValues(commodity, commodityToCreate); if (ModelState.IsValid) { _commodityRepository.EnsurePersistent(commodityToCreate); Message = "Commodity Created Successfully"; return RedirectToAction("Index"); } else { var viewModel = CommodityViewModel.Create(Repository); viewModel.Commodity = commodity; return View(viewModel); } }
//returns the $$$ made in the sale public float SellProductsSM(Commodity commod) { //AddCommodity(commod); int numberToSell; numberToSell = commod.numOf; float pricePer; pricePer = 0; foreach(Market_Commodity c in goodsList) { if(c.nameOf == commod.nameOf) { c.atMarket += commod.numOf; pricePer = c.currentPrice; break; } } float profit; profit = numberToSell * pricePer; return profit; }
/// <summary> /// Transfer editable values from source to destination. Use of AutoMapper is recommended /// </summary> private static void TransferValues(Commodity source, Commodity destination) { throw new NotImplementedException(); }
static void Main() { int numberOfProducts = 6; int knapsackCapacity = 10; int knapsackLength = 0; int[] knapsack; List<Commodity> products = new List<Commodity>(); Commodity beer = new Commodity(3, 2); products.Add(beer); Commodity vodka = new Commodity(12, 8); products.Add(vodka); Commodity cheese = new Commodity(5, 4); products.Add(cheese); Commodity nuts = new Commodity(4, 1); products.Add(nuts); Commodity ham = new Commodity(3, 2); products.Add(ham); Commodity whiskey = new Commodity(13, 8); products.Add(whiskey); // Another knapsack example got from here: http://www.youtube.com/watch?v=EH6h7WA7sDw // Please add comment to the commodities above and remove comments from bottom ones; //Commodity item1 = new Commodity(5, 3); //products.Add(beer); //Commodity item2 = new Commodity(3, 2); //products.Add(vodka); //Commodity item3 = new Commodity(4, 1); //products.Add(cheese); //numberOfProducts = 3; //knapsackCapacity = 5; for (int i = 0; i < numberOfProducts; i++) { knapsackLength += products[i].Price; } knapsack = new int[knapsackLength + 1]; foreach (Commodity product in products) { var indexerCopy = new int[indexer.Count]; indexer.CopyTo(indexerCopy); foreach (int price in indexerCopy) { PlaceProduct(knapsack, knapsackCapacity, price + product.Price, knapsack[price] + product.Weight); } if (indexer.Contains(product.Price)) { if (knapsack[product.Price] > product.Weight) { knapsack[product.Price] = product.Weight; } } else { knapsack[product.Price] = product.Weight; indexer.Add(product.Price); } } for (int i = knapsack.Length - 1; i >= 0; i--) { if (knapsack[i] != 0) { Console.WriteLine("Price = {0}, Weight = {1}", i, knapsack[i]); break; } } }
/// <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 }); } }
//checks if commodity is present and enough of it //then removes it from stock bool RemoveCommodity(Commodity commod) { if(commodityList.Count > 0) { foreach(Market_Commodity c in goodsList) { if(c.nameOf == commod.nameOf && c.atMarket >= commod.numOf) { c.atMarket -= commod.numOf; return true; } } } return false; }
void UnloadCommodity(Commodity _commodity) { loadedCommodities.Remove(_commodity); }
public ShopingModelBase() { _innerObject = new Commodity(); }
private static JdAuditCommodityStock AddCommodityStockAudit(ContextSession contextSession, Commodity com, 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 = com.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 = com.Id; auditComStock.CommodityId = com.Id; auditComStock.ComAttribute = com.ComAttribute; auditComStock.Price = com.Price; auditComStock.Stock = com.Stock; auditComStock.MarketPrice = com.MarketPrice; auditComStock.SubTime = com.SubTime; auditComStock.ModifiedOn = DateTime.Now; auditComStock.Duty = com.Duty; auditComStock.Barcode = com.Barcode; auditComStock.No_Code = com.Code; auditComStock.JDCode = com.JDCode; auditComStock.CostPrice = com.CostPrice; //auditComStock.ThumImg = com.ThumImg; //auditComStock.CarouselImgs = com.CarouselImgs; contextSession.SaveObject(AuditInfo); return(auditComStock); }
private List <Commodity> GetCommodityList(Category category, string url) { string html = HttpHelper.DownloadUrl(url); List <Commodity> commodityList = new List <Commodity>(); try { if (string.IsNullOrEmpty(html)) { return(commodityList); } HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); string liPath = "//*[@id='plist']/ul/li"; HtmlNodeCollection noneNodeList = doc.DocumentNode.SelectNodes(liPath); if (noneNodeList == null || noneNodeList.Count == 0) { warnRepository.SaveWarn(category, string.Format("GetCommodityList商品数据为空,Name={0} Level={1} category.Url={2} url={3}", category.Name, category.CategoryLevel, category.Url, url)); return(commodityList); } foreach (var node in noneNodeList) { HtmlDocument docChild = new HtmlDocument(); docChild.LoadHtml(node.OuterHtml); Commodity commodity = new Commodity() { CategoryId = category.Id }; string urlPath = "//*[@class='p-name']/a"; HtmlNode urlNode = docChild.DocumentNode.SelectSingleNode(urlPath); if (urlNode == null) { continue; } commodity.Url = urlNode.Attributes["href"].Value; if (!commodity.Url.StartsWith("http:")) { commodity.Url = "http:" + commodity.Url; } string sId = Path.GetFileName(commodity.Url).Replace(".html", ""); commodity.ProductId = long.Parse(sId); //*[@id="plist"]/ul/li[1]/div/div[3]/a/em string titlePath = "//*[@class='p-name']/a/em"; HtmlNode titleNode = docChild.DocumentNode.SelectSingleNode(titlePath); if (titleNode == null) { //Log.Error(titlePath); continue; } commodity.Title = titleNode.InnerText; string iamgePath = "//*[@class='p-img']/a/img"; HtmlNode imageNode = docChild.DocumentNode.SelectSingleNode(iamgePath); if (imageNode == null) { continue; } if (imageNode.Attributes.Contains("src")) { commodity.ImageUrl = imageNode.Attributes["src"].Value; } else if (imageNode.Attributes.Contains("original")) { commodity.ImageUrl = imageNode.Attributes["original"].Value; } else if (imageNode.Attributes.Contains("data-lazy-img")) { commodity.ImageUrl = imageNode.Attributes["data-lazy-img"].Value; } else { continue; } if (!commodity.ImageUrl.StartsWith("http:")) { commodity.ImageUrl = "http:" + commodity.ImageUrl; } commodityList.Add(commodity); } Console.WriteLine("{0}一共获取了{1}条数据", url, commodityList.Count); } catch (Exception ex) { logger.Error(string.Format("GetCommodityList出现异常,url={0}", url), ex); } return(GetCommodityPrice(category, commodityList)); }
private static JdAuditCommodity AddCommodityAudit(Commodity com) { JdAuditCommodity auditCom = JdAuditCommodity.CreateJdAuditCommodity(); auditCom.CommodityId = com.Id; auditCom.Name = com.Name; auditCom.Code = com.Code; auditCom.SubTime = com.SubTime; auditCom.SubId = com.SubId; auditCom.No_Number = com.No_Number; auditCom.Price = com.Price; auditCom.Stock = com.Stock; auditCom.PicturesPath = com.PicturesPath; auditCom.Description = com.Description; auditCom.State = com.State; auditCom.IsDel = com.IsDel; auditCom.AppId = com.AppId; auditCom.No_Code = com.No_Code; auditCom.TotalCollection = com.TotalCollection; auditCom.TotalReview = com.TotalReview; auditCom.Salesvolume = com.Salesvolume; auditCom.ModifiedOn = DateTime.Now; auditCom.GroundTime = com.GroundTime; auditCom.ComAttribute = com.ComAttribute; auditCom.CategoryName = com.CategoryName; auditCom.SortValue = com.SortValue; auditCom.FreightTemplateId = com.FreightTemplateId; auditCom.MarketPrice = com.MarketPrice; auditCom.IsEnableSelfTake = com.IsEnableSelfTake; auditCom.Weight = com.Weight; auditCom.PricingMethod = com.PricingMethod; auditCom.SaleAreas = com.SaleAreas; auditCom.SharePercent = com.SharePercent; auditCom.CommodityType = com.CommodityType; auditCom.HtmlVideoPath = com.HtmlVideoPath; auditCom.MobileVideoPath = com.MobileVideoPath; auditCom.VideoPic = com.VideoPic; auditCom.VideoName = com.VideoName; auditCom.ScorePercent = com.ScorePercent; auditCom.Duty = com.Duty; auditCom.SpreadPercent = com.SpreadPercent; auditCom.ScoreScale = com.ScoreScale; auditCom.TaxRate = com.TaxRate; auditCom.TaxClassCode = com.TaxClassCode; auditCom.Unit = com.Unit; auditCom.InputRax = com.InputRax; auditCom.Barcode = com.Barcode; auditCom.JDCode = com.JDCode; auditCom.CostPrice = com.CostPrice; auditCom.IsAssurance = com.IsAssurance; auditCom.TechSpecs = com.TechSpecs; auditCom.SaleService = com.SaleService; auditCom.IsReturns = com.IsReturns; auditCom.ServiceSettingId = com.ServiceSettingId; auditCom.Type = com.CommodityType; auditCom.YJCouponActivityId = com.YJCouponActivityId; auditCom.YJCouponType = com.YJCouponType; auditCom.ModifieId = Jinher.JAP.BF.BE.Deploy.Base.ContextDTO.Current.LoginUserID; auditCom.FieldName = ""; return(auditCom); }
/// <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); } }
/// <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 }
public ActionResult Delete(int id, Commodity commodity) { var commodityToDelete = _commodityRepository.GetNullableById(id); if (commodityToDelete == null) return RedirectToAction("Index"); _commodityRepository.Remove(commodityToDelete); Message = "Commodity Removed Successfully"; return RedirectToAction("Index"); }
public void CommodityConstructorTest() { Commodity target = new Commodity(); Assert.Inconclusive("TODO: Implement code to verify target"); }
/// <summary> /// 保存一个京东订单 /// </summary> /// <param name="item">一个订单</param> /// <param name="comList">订单项对应的商品</param> private ResultDTO SaveOneJdOrder(OrderSDTO item, List <Commodity> comList) { ResultDTO <List <CommoditySummaryDTO> > result = new ResultDTO <List <CommoditySummaryDTO> >(); if (item == null) { result.ResultCode = (int)ReturnCodeEnum.ParamEmpty; result.Message = ReturnCodeEnum.ParamEmpty.GetDescription(); return(result); } if (item.ShoppingCartItemSDTO == null || !item.ShoppingCartItemSDTO.Any() || comList == null || !comList.Any()) { result.ResultCode = (int)ReturnCodeEnum.ParamEmpty; result.Message = ReturnCodeEnum.ParamEmpty.GetDescription(); return(result); } //易捷北京所有的AppId string Appids = CustomConfig.AppIds; LogHelper.Info(string.Format("Appids{0}", Appids)); List <string> Appidlist = null; if (!string.IsNullOrEmpty(Appids)) { Appidlist = Appids.Split(new char[] { ',' }).ToList(); } if (!Appidlist.Contains(comList[0].AppId.ToString().ToUpper())) { //todo 返回非京东app. result.ResultCode = (int)ReturnCodeEnum.NotJdShop; result.Message = ReturnCodeEnum.NotJdShop.GetDescription(); return(result); } LogHelper.Info(string.Format("Appidlist的数量{0}", Appidlist.Count())); string orderPriceSnap = null; string sku = null; //订单项里的商品都是同一店铺的,店铺名称相同。 string appName = APPSV.GetAppName(comList[0].AppId); List <CommoditySummaryDTO> errorCommodities = new List <CommoditySummaryDTO>(); orderPriceSnap = null; sku = null; ContextSession contextSession = ContextFactory.CurrentThreadContext; var scis = item.ShoppingCartItemSDTO; foreach (var _item in scis) { Commodity commodity = comList.FirstOrDefault(_ => _.Id == _item.Id); LogHelper.Info(string.Format("京东日志:商品Id:{0},JDCode:{1},AppId:{2}", commodity.Id, commodity.JDCode, commodity.AppId)); //京东店铺的商品没有JDCode,返回错误。 if (string.IsNullOrWhiteSpace(commodity.JDCode)) { #region Jdlogs model = new Jdlogs(); model.Id = Guid.NewGuid(); model.Content = (appName + "App中" + commodity.Name + "商品的备注编码不存在,请尽快补充填写~"); model.Remark = string.Empty; model.AppId = commodity.AppId; model.ModifiedOn = DateTime.Now; model.SubTime = DateTime.Now; model.Isdisable = false; model.EntityState = EntityState.Added; contextSession.SaveObject(model); bool falg = EmailHelper.SendEmail("京东错误日志", model.Content, "*****@*****.**"); var errorCommodity = new CommoditySummaryDTO(); errorCommodity.Id = commodity.Id; errorCommodity.Name = commodity.Name; errorCommodity.PicturesPath = commodity.PicturesPath; errorCommodity.Price = _item.Price; errorCommodity.Sku = _item.SizeAndColorId; errorCommodity.ShopCartItemId = _item.ShopCartItemId; errorCommodities.Add(errorCommodity); result.ResultCode = (int)ReturnCodeEnum.CommoditySold; result.Message = ReturnCodeEnum.CommoditySold.GetDescription(); result.Data = errorCommodities; return(result); #endregion } orderPriceSnap += "{'price':" + commodity.CostPrice + ",'skuId':" + commodity.JDCode + "},"; sku += "{'skuId':" + commodity.JDCode + ", 'num':" + _item.CommodityNumber + ",'bNeedAnnex':true, 'bNeedGift':false},"; LogHelper.Info(string.Format("京东日志2:{0}:{1}", orderPriceSnap, sku)); } LogHelper.Info(string.Format("京东日志3:{0}:{1}", orderPriceSnap, sku)); if (string.IsNullOrEmpty(orderPriceSnap) || string.IsNullOrEmpty(sku)) { //没有商品要去京东下单。 result.ResultCode = (int)ReturnCodeEnum.NoCommodityNeedJdOrder; result.Message = ReturnCodeEnum.NoCommodityNeedJdOrder.GetDescription(); return(result); } orderPriceSnap = orderPriceSnap.Remove(orderPriceSnap.Length - 1, 1); sku = sku.Remove(sku.Length - 1, 1); orderPriceSnap = "[" + orderPriceSnap + "]"; sku = "[" + sku + "]"; string thirdOrder = Guid.NewGuid().ToString(); if (string.IsNullOrEmpty(item.StreetCode)) { item.StreetCode = "0"; } //获取京东编号 ResultDTO jdResult = JdHelper.GetJDOrderNew(thirdOrder, orderPriceSnap, sku, item.ReceiptUserName, item.ReceiptAddress, item.ReceiptPhone, "*****@*****.**", item.ProvinceCode, item.CityCode, item.DistrictCode, item.StreetCode); LogHelper.Info(string.Format("京东日志4:{0}:{1}", orderPriceSnap, sku)); //正常下单,保存订单项关系。 if (jdResult.ResultCode == 0) { #region 京东下单情况 JdOrderItem jdorderitemdto = new JdOrderItem() { Id = Guid.NewGuid(), //todo jdporderId???? //JdPorderId = jdporderId, TempId = Guid.Parse(thirdOrder), JdOrderId = Guid.Empty.ToString(), MainOrderId = Guid.Empty.ToString(), CommodityOrderId = Guid.Empty.ToString(), State = Convert.ToInt32(JdEnum.YZ), StateContent = new EnumHelper().GetDescription(JdEnum.YZ), SubTime = DateTime.Now, ModifiedOn = DateTime.Now }; //todo SaveJdOrderItem(jdorderitemdto); JdJournal jdjournaldto = new JdJournal() { Id = Guid.NewGuid(), //todo jdporderId //JdPorderId = jdporderId, TempId = Guid.Parse(thirdOrder), JdOrderId = Guid.Empty.ToString(), MainOrderId = Guid.Empty.ToString(), CommodityOrderId = Guid.Empty.ToString(), Name = "京东统一下单接口", Details = "初始状态为" + Convert.ToInt32(JdEnum.YZ), SubTime = DateTime.Now }; //todo SaveJdJournal(jdjournaldto); #endregion } else { #region 记录京东日志 int resultCode = jdResult.ResultCode; string jdlog = jdResult.Message; if (resultCode == 3017) //账户异常情况特殊 { #region EmailHelper.SendEmail("京东错误日志", "您的京东账户余额不足,请充值!", "*****@*****.**"); Jinher.AMP.BTP.Deploy.JdlogsDTO model = new Jinher.AMP.BTP.Deploy.JdlogsDTO(); model.Id = Guid.NewGuid(); model.Content = "您的京东账户余额不足,请充值!"; model.Remark = string.Empty; model.AppId = Guid.Empty; model.ModifiedOn = DateTime.Now; model.SubTime = DateTime.Now; model.Isdisable = false; //SaveJdlogs(model); foreach (var itemlog in scis) { var errorCommodity = new CommoditySummaryDTO(); errorCommodity.Id = itemlog.Id; errorCommodity.Name = itemlog.Name; errorCommodity.PicturesPath = itemlog.Pic; errorCommodity.Price = itemlog.Price; errorCommodity.Sku = itemlog.SizeAndColorId; errorCommodity.ShopCartItemId = itemlog.ShopCartItemId; errorCommodities.Add(errorCommodity); } #endregion } else { #region if (!string.IsNullOrEmpty(jdResult.Message)) { string num = null; var matches = Regex.Matches(jdResult.Message, @"(\d+)"); int count = 0; foreach (Match match in matches) { if (count == 0) { num = match.Value; } count++; } foreach (var itemlog in scis) { Commodity commodity = comList.FirstOrDefault(_ => _.Id == itemlog.Id); if (commodity.JDCode != num.ToString()) { continue; } var errorCommodity = new CommoditySummaryDTO(); errorCommodity.Id = commodity.Id; errorCommodity.Name = commodity.Name; errorCommodity.PicturesPath = commodity.PicturesPath; errorCommodity.Price = itemlog.Price; errorCommodity.Sku = itemlog.SizeAndColorId; errorCommodity.ShopCartItemId = itemlog.ShopCartItemId; errorCommodities.Add(errorCommodity); string content = null; content += (APPSV.GetAppName(commodity.AppId) + "App中" + itemlog.Name) + "商品[" + commodity.JDCode + "]"; if (resultCode == 2004) { content += "京东商品池中不存在"; } else if (resultCode == 3019) { string str = jdlog; if (!string.IsNullOrEmpty(str)) { content += "价格错误,"; int num1 = str.IndexOf('['); int num2 = str.IndexOf(']'); string strjdprice = str.Substring(num1 + 1, (num2 - num1 - 1)); string[] arr = strjdprice.Split(new char[] { '=' }); content += "京东价" + arr[1] + "元," + "易捷价" + commodity.CostPrice + "元"; } } else if (resultCode == 3008) { content += "已售馨"; } else { content += "异常信息:" + jdlog; } EmailHelper.SendEmail("京东错误日志", content, "*****@*****.**"); Jinher.AMP.BTP.Deploy.JdlogsDTO model = new Jinher.AMP.BTP.Deploy.JdlogsDTO(); model.Id = Guid.NewGuid(); model.Content = content; model.Remark = string.Empty; model.AppId = itemlog.AppId; model.ModifiedOn = DateTime.Now; model.SubTime = DateTime.Now; model.Isdisable = false; //SaveJdlogs(model); } } #endregion } #endregion #region 获取京东订单单号失败的情况 //////京东确认取消订单 ////bool flag = JdHelper.OrderCancel(jdorderid.JdporderId); ////if (flag == true) ////{ //// List<string> jdorder = new List<string>(); //// jdorder.Add(jdorderid.JdporderId); //// //删除京东对应订单 //// var res = jdorderitemfacade.DeleteJdOrderItem(jdorder); //// if (res.isSuccess == true) //// { //// JdJournal jdjournaldto = new JdJournal() //// { //// Id = Guid.NewGuid(), //// JdPorderId = jdporderId, //// TempId = Guid.Parse(thirdOrder), //// JdOrderId = Guid.Empty.ToString(), //// MainOrderId = Guid.Empty.ToString(), //// CommodityOrderId = Guid.Empty.ToString(), //// Name = "京东确认取消订单", //// Details = "删除JdOrderItem表中相应的内容", //// SubTime = DateTime.Now //// }; //// //SaveJdJournal(jdjournaldto); //// } ////} #endregion //LogHelper.Error("商品已售馨,请选择其他商品,Jdlogs:" + jdlog + " resultCode:" + resultCode); //return Json(new OrderResultDTO { ResultCode = 2, Message = "商品已售馨,请选择其他商品", ErrorCommodities = errorCommodities }, JsonRequestBehavior.AllowGet); } return(result); }
public virtual bool CheckCanLoad(Commodity _commodity) { return(true); }
public ActionResult CommandersLog(HttpPostedFileBase file) { string json = null; if (file == null) { return(View("CommandersLogError", null, "No file uploaded")); } var kb = (double)file.ContentLength / 1024d; if (kb > 1024 || kb == 0) { return(View("CommandersLogError", null, "File cannot be larger than 1 MB")); } try { using (var output = new MemoryStream()) { using (var writer = new StreamWriter(output)) { using (var reader = new StreamReader(file.InputStream)) { do { var inp = reader.ReadLine().Trim(); if (!String.IsNullOrEmpty(inp)) { if (inp == "{") { writer.Write(inp); } else if (inp == "}") { writer.Write("},"); } else if (inp.Contains("=")) { var parts = inp.Split('='); writer.Write("\"" + parts[0].Trim().ToLower() + "\":" + parts[1].Trim() + ","); } else if (!inp.StartsWith("\"")) { writer.Write("\"" + inp.ToLower().Replace(" ", "_") + "\":"); } } }while (reader.Peek() != -1); } } json = Encoding.UTF8.GetString(output.ToArray()); json = json.Replace(",}", "}"); json = "{" + json.Trim(',') + "}"; } } catch { return(View("CommandersLogError", null, "Unable to read file.")); } Dictionary <string, List <string> > saved = new Dictionary <string, List <string> >(); List <string> skipped = new List <string>(); List <string> failed = new List <string>(); if (json != null) { JToken data = null; try { data = JObject.Parse(json).SelectToken("save_data"); } catch { return(View("CommandersLogError", null, "Unable to parse data")); } var version = Convert.ToInt32(((JValue)data.SelectToken("saveversion")).Value); if (version != 2) { return(View("CommandersLogError", null, "Incorrect save version. Must be 2.")); } foreach (var child in data.Children()) { try { if (child is JProperty && ((JProperty)child).Value is JObject) { var systemName = ((JProperty)child).Name.Replace("_", " "); using (var session = DB.Instance.GetSession()) { var solarSystem = session.Query <SolarSystem>() .Where(x => x.Name == systemName) .FirstOrDefault(); if (solarSystem == null) { skipped.Add(Capitalize(systemName)); continue; } foreach (var objStation in child) { var stationName = ((JObject)objStation).Properties().First().Name.Replace("_", " "); try { var station = solarSystem.Stations.FirstOrDefault(x => x.Name.Equals(stationName, StringComparison.CurrentCultureIgnoreCase)); if (station != null) { var commodities = ((JObject)objStation) .Properties() .First() .Value .SelectToken("commodities"); if (commodities != null) { //Gather commodities for station List <Commodity> stationCommodities = new List <Commodity>(); foreach (var commodity in commodities) { var objCommodity = (JProperty)commodity; var commodityName = objCommodity.Name; CommodityType type = CommodityType.Advanced_Catalysers; if (Enum.TryParse <CommodityType>(commodityName, true, out type)) { var status = Convert.ToInt32(((JValue)objCommodity.Value.SelectToken("status")).Value); var price = 0; var tokenPrice = objCommodity.Value.SelectToken("price"); if (tokenPrice != null) { int.TryParse(((JValue)tokenPrice).Value.ToString(), out price); } int[] timeArray = null; var tokenTime = objCommodity.Value.SelectToken("modtime"); if (tokenTime != null) { timeArray = ((JValue)tokenTime).Value.ToString() .Split(',') .Select(x => int.Parse(x.TrimStart('0').PadLeft(1, '0'))) .ToArray(); } var stationCommodity = new Commodity { Type = type, Price = price }; if (timeArray != null) { stationCommodity.Updated = new DateTime(timeArray[0], timeArray[1], timeArray[2], timeArray[3], timeArray[4], 0).ToUniversalTime(); } switch (status) { case 0: stationCommodity.Supply = CommodityAvailability.High; break; case 1: stationCommodity.Supply = CommodityAvailability.Medium; break; case 2: stationCommodity.Supply = CommodityAvailability.Low; break; case 4: stationCommodity.Demand = CommodityAvailability.Low; break; case 5: stationCommodity.Demand = CommodityAvailability.Medium; break; case 6: stationCommodity.Demand = CommodityAvailability.High; break; } stationCommodities.Add(stationCommodity); } } //Update db with commodities List <Commodity> removedCommodities = new List <Commodity>(); foreach (var c in stationCommodities) { var existingCommodity = station.Commodities.FirstOrDefault(x => x.Type == c.Type); if (existingCommodity != null && c.Updated >= existingCommodity.Updated) { if (c.Demand == CommodityAvailability.None && c.Supply == CommodityAvailability.None) { removedCommodities.Add(existingCommodity); } else { existingCommodity.Demand = c.Demand; existingCommodity.Supply = c.Supply; existingCommodity.Price = c.Price; } } else if (c.Demand != CommodityAvailability.None || c.Supply != CommodityAvailability.None) { station.Commodities.Add(c); } } if (removedCommodities.Count > 0) { station.Commodities = station.Commodities.Except(removedCommodities).ToList(); } if (!saved.ContainsKey(systemName)) { saved.Add(systemName, new List <string>()); } saved[systemName].Add(stationName + " - Imported"); } } else { if (!saved.ContainsKey(systemName)) { saved.Add(systemName, new List <string>()); } saved[systemName].Add(stationName + " - Does not exist in tracker"); } } catch { failed.Add(stationName); } } session.SaveChanges(); } } } catch { //Failed system } } } ViewBag.Saved = saved; ViewBag.Skipped = skipped; ViewBag.Failed = failed; return(View("CommandersLogSuccess")); }
public MissionCompletedEvent(DateTime timestamp, long?missionid, string name, string faction, Commodity commodity, int?amount, bool communal, long reward, List <CommodityAmount> commodityrewards, long donation) : base(timestamp, NAME) { this.missionid = missionid; this.name = name; this.faction = faction; this.commodity = (commodity == null ? null : commodity.name); this.amount = amount; this.communal = communal; this.reward = reward; this.commodityrewards = commodityrewards; this.donation = donation; if (commodityrewards.Count > 0) { this.rewardCommodity = commodityrewards[0].commodity; this.rewardAmount = commodityrewards[0].amount; } }
protected void SetInnerObject(Commodity comm) { _innerObject = comm; }
public bool AddCommodity(Commodity commodity) { _unitOfWork.CommodityRepository.Add(commodity); _unitOfWork.Save(); return true; }
public ResultJson UpdateComm(EditCommdityRequest request) { #region 若有原材料ID var MaterialId = request.MaterialId.ParseInt(); var MaterialColorInfo = ""; var MaterialColorList = ""; if (MaterialId != null) { var Material = Raw_MaterialsFunc.Instance.SelectById(MaterialId.Value); if (Material != null) { #region 重设价格列表 request.PriceList = ""; var saleInfoList = Material.SalesInfoList.Split(';').Where(p => !string.IsNullOrEmpty(p)).ToList(); foreach (var item in saleInfoList) { var saleInfoDetail = item.Split('|').Where(p => !string.IsNullOrEmpty(p)).ToList(); request.PriceList = request.PriceList + "|" + saleInfoDetail[1] + "," + saleInfoDetail[0] + "," + saleInfoDetail[2]; } #endregion #region 设置颜色图片 var colorInfoList = ColorinfoFunc.Instance.GetColorListBase(); var Material_ColorList = Materials_ColorinfoFunc.Instance.SelectByModel(new Materials_Colorinfo { MaterialsId = Material.Id }); foreach (var item in Material_ColorList) { var thisColorInfo = colorInfoList.Where(p => p.Id == item.ColorId).FirstOrDefault(); if (thisColorInfo != null) { MaterialColorInfo = MaterialColorInfo + $"{item.ColorId};{item.SKUImage}|"; MaterialColorList = MaterialColorList + thisColorInfo.Id + ","; } } #endregion #region 设置位置 request.Position = ""; foreach (var item in Material_ColorList) { request.Position = $"{request.Position}{item.ColorId}({item.PositionInfo})"; } #endregion request.GradeId = Material.Genera.ParseInt().Value; } } #endregion #region 初始判断 var price = request.CommPrice.ParseDouble(); if (price == null || price <= 0) { return(new ResultJson { HttpCode = 300, Message = "价格不正确!" }); } if (request.ImgList == null && MaterialColorInfo == "") { return(new ResultJson { HttpCode = 300, Message = "至少有一张图片!" }); } else if (request.ImgList == null) { request.ImgList = ""; } if (request.ColorIds == null && MaterialColorList == "") { return(new ResultJson { HttpCode = 300, Message = "至少有一个颜色!" }); } else if (request.ColorIds == null) { request.ImgList = ""; } #endregion #region 价格判断 if (request.PriceList == null) { request.PriceList = ""; } #endregion #region 检测有无临时图片 if (request.ShowImage.Contains("temp")) { FileHelper.Instance.Move(HttpContext.Current.Server.MapPath(request.ShowImage), HttpContext.Current.Server.MapPath($"/current/images/Commodity/" + request.ShowImage.Split('/').Last()), HttpContext.Current.Server.MapPath($"/current/images/Commodity")); request.ShowImage = $"/current/images/Commodity/" + request.ShowImage.Split('/').Last(); } var FrontViewArray = request.FrontView.Split('|').Where(p => !string.IsNullOrEmpty(p)).ToList(); request.FrontView = ""; foreach (var item in FrontViewArray) { if (item.Contains("temp")) { FileHelper.Instance.Move(HttpContext.Current.Server.MapPath(item), HttpContext.Current.Server.MapPath($"/current/images/Commodity/" + item.Split('/').Last()), HttpContext.Current.Server.MapPath($"/current/images/Commodity")); request.FrontView = request.FrontView + $"/current/images/Commodity/" + item.Split('/').Last() + "|"; } else { request.FrontView = request.FrontView + item + "|"; } } if (request.BackView.Contains("temp")) { FileHelper.Instance.Move(HttpContext.Current.Server.MapPath(request.BackView), HttpContext.Current.Server.MapPath($"/current/images/Commodity/" + request.BackView.Split('/').Last()), HttpContext.Current.Server.MapPath($"/current/images/Commodity")); request.BackView = $"/current/images/Commodity/" + request.BackView.Split('/').Last(); } var array = request.ImgList.Split('|').Where(p => !string.IsNullOrEmpty(p)).ToList(); var colorList = request.ColorIds.Split(',').Where(p => !string.IsNullOrEmpty(p)).ToList(); request.ImgList = ""; foreach (var item in array) { if (item.Contains("temp")) { if (item.Contains(';')) { var color = colorList.Where(p => p == item.Split(';')[0]).FirstOrDefault(); if (color != null) { var array2 = item.Split(';')[1]; FileHelper.Instance.Move(HttpContext.Current.Server.MapPath(array2), HttpContext.Current.Server.MapPath($"/current/images/Commodity/" + item.Split('/').Last()), HttpContext.Current.Server.MapPath($"/current/images/Commodity")); request.ImgList = request.ImgList + $"{item.Split(';')[0]};/current/images/Commodity/" + item.Split('/').Last() + "|"; } } else { FileHelper.Instance.Move(HttpContext.Current.Server.MapPath(item), HttpContext.Current.Server.MapPath($"/current/images/Commodity/" + item.Split('/').Last()), HttpContext.Current.Server.MapPath($"/current/images/Commodity")); request.ImgList = request.ImgList + $"/current/images/Commodity/" + item.Split('/').Last() + "|"; } } else { if (item.Contains(';')) { var color = colorList.Where(p => p == item.Split(';')[0]).FirstOrDefault(); if (color != null) { request.ImgList = request.ImgList + item + "|"; } } else { request.ImgList = request.ImgList + item + "|"; } } } #endregion Commodity commodity = new Commodity { Id = request.CommId, BackView = request.BackView, Color = request.ColorIds + MaterialColorList, Content = request.content, FrontView = request.FrontView, GradeId = request.GradeId, Image = request.ShowImage, ImageList = request.ImgList + MaterialColorInfo, Introduce = request.Introduce, Name = request.CommName, IsRelease = request.Release == "on" ? true : false, Points = request.PriceList + "|" + request.CommPrice + ",0,0", ScenceIds = request.SceneIds, MaterialId = request.MaterialId.ParseInt(), PringtingPosition = request.Position, CommodityInfo = request.Collocations }; if (CommodityFunc.Instance.InsertCommodity(commodity)) { CommodityFunc.Instance.ReGetAllCommList(); return(new ResultJson { HttpCode = 200, Message = "操作成功!" }); } else { return(new ResultJson { HttpCode = 400, Message = "操作失败,请再次尝试!" }); } }
public bool EditCommodity(Commodity commodity) { _unitOfWork.CommodityRepository.Edit(commodity); _unitOfWork.Save(); return true; }
public override bool Equals(object obj) { Commodity commodity = obj as Commodity; return(this.Id == commodity.Id); }
/// <summary> /// 导入严选商品信息 /// </summary> public Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> ImportYXCommodityDataExt(System.Collections.Generic.List <Jinher.AMP.BTP.Deploy.JdCommodityDTO> JdComList, System.Guid AppId) { try { JdCommoditySearchDTO JdComDTO = new JdCommoditySearchDTO(); var SPUIdLis = YXSV.GetAllSPU(); List <string> SPUIds = JdComList.Select(s => s.JDCode).ToList(); //严选商品池不存在的SKUid JdComDTO.InvalidData = SPUIds.Except(SPUIdLis).ToList(); //店铺中已存在的严选 JdComDTO.RepeatData = Commodity.ObjectSet().Where(p => SPUIds.Contains(p.JDCode) && !p.IsDel && p.AppId == AppId).Select(s => s.JDCode).ToList(); //严选商品表中已存在的备注编码 JdComDTO.JdRepeatData = JdCommodity.ObjectSet().Where(p => SPUIds.Contains(p.JDCode) && !p.IsDel && p.AppId == AppId && p.State != 1).Select(s => s.JDCode).ToList(); if (JdComDTO.InvalidData.Any() || JdComDTO.JdRepeatData.Any()) { return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> { Data = JdComDTO, ResultCode = 1, isSuccess = false, Message = "存在重复备注编码和无效备注编码,请核对后再导入~" }); } //获取运费模板 var FreightTemplateInfo = FreightTemplate.ObjectSet().FirstOrDefault(p => p.AppId == AppId && p.IsDefault == 1); ContextSession contextSession = ContextFactory.CurrentThreadContext; Guid userId = this.ContextDTO.LoginUserID; //获取不到商品类目的 List <string> NoCategoryData = new List <string>(); foreach (var input in JdComList) { JdCommodity JdCom = JdCommodity.CreateJdCommodity(); JdCom.Barcode = input.JDCode; JdCom.TaxRate = input.TaxRate; JdCom.InputRax = input.InputRax; JdCom.TaxClassCode = input.TaxClassCode; JdCom.State = 0; //是否补全 JdCom.SubId = userId; JdCom.SubTime = DateTime.Now; JdCom.AppId = input.AppId; JdCom.JDCode = input.JDCode; JdCom.FreightTemplateId = FreightTemplateInfo.Id; JdCom.SaleAreas = "430000,220000,420000,210000,310000,120000,140000,410000,320000,340000,350000,510000,440000,450000,500000,370000,530000,460000,610000,110000,230000,360000,620000,330000,640000,520000,130000,630000";//出去港澳台 新疆 西藏 JdCom.No_Code = input.JDCode; JdCom.ErQiCode = input.ErQiCode; JdCom.IsAssurance = input.IsAssurance; JdCom.IsReturns = input.IsReturns; JdCom.Isnsupport = input.Isnsupport; JdCom.ServiceSettingId = input.ServiceSettingId; JdCom.TechSpecs = input.TechSpecs; JdCom.SaleService = input.SaleService; JdCom.CategoryName = input.CategoryName; JdCom.VideoName = input.VideoName; contextSession.SaveObject(JdCom); } int count = contextSession.SaveChanges(); return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> { Data = JdComDTO, ResultCode = 0, isSuccess = true, Message = "导入成功" }); } catch (Exception ex) { LogHelper.Error("YXCommodityBP.ImportYXCommodityDataExt 异常", ex); return(new ResultDTO <Jinher.AMP.BTP.Deploy.CustomDTO.YJEmployee.JdCommoditySearchDTO> { isSuccess = false, ResultCode = 2, Message = ex.Message }); } }
public int Compare(Amount x, Amount y) { return(Commodity.CompareByCommodityComparison(x, y)); }
public void Commodity_Equals_IgnoresNulls() { Commodity commodity1 = new Commodity(CommodityPool.Current, new CommodityBase("comm1")); Assert.IsFalse(commodity1.Equals((Commodity)null)); }
/// <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 结束同步易派客商品价格"); }
public static Commodity Commodity(int? counter, bool loadAll = true) { var rtValue = new Commodity(); rtValue.SetIdTo(counter.Extra()); if (loadAll) { rtValue.Name = "Name" + counter.Extra(); rtValue.GroupCode = "GroupCode" + counter.Extra(); rtValue.SubGroupCode = "SubGroupCode" + counter.Extra(); } rtValue.IsActive = true; return rtValue; }
public ActionResult Edit(int id, Commodity commodity) { var commodityToEdit = _commodityRepository.GetNullableById(id); if (commodityToEdit == null) return RedirectToAction("Index"); TransferValues(commodity, commodityToEdit); if (ModelState.IsValid) { _commodityRepository.EnsurePersistent(commodityToEdit); Message = "Commodity Edited Successfully"; return RedirectToAction("Index"); } else { var viewModel = CommodityViewModel.Create(Repository); viewModel.Commodity = commodity; return View(viewModel); } }
static void Main(string[] args) { using (var db = new ShopContext()) { var monitor = new Commodity(); var battery = new Commodity(); monitor.Model = "y570"; monitor.Price = 2120; monitor.Producer = "Lenovo"; monitor.Category = "Monitors"; //battery.Model = "sl10"; //battery.Price = 20; //battery.Producer = "lenovo"; //battery.Category = "Batteries"; db.DbGoods.Add(monitor); //db.DbGoods.Add(battery); var prop = new Property { Name = "ScreenSize", ValueChar = "1920x1080", }; var prop2 = new Property { Name = "Resolution", ValueChar = "1920x1080", }; //Person john = new Person(); //john.FirstName = "John"; //john.LastName = "Paul"; prop.Goods.Add(monitor); prop2.Goods.Add(monitor); //prop.Goods.Add(battery); db.DbProperties.Add(prop); db.DbProperties.Add(prop2); db.SaveChanges(); var goods = db.DbGoods.Include(p => p.Properties).ToList(); Console.Write(goods.ToString()); Console.ReadKey(); } }
Texture GetTextureFromCommodity(Commodity commodity) { switch(commodity) { default: case Commodity.LIVES: return PriceItemLifeTexture; case Commodity.BOMBS: return PriceItemBombTexture; } }
public Person CreateSeminarPerson(Application application, ModelStateDictionary modelState) { var person = SetPerson(application, application.User.Person); var firm = application.Firm ?? new Firm(application.FirmName, !string.IsNullOrWhiteSpace(application.FirmDescription)? application.FirmDescription : "n/a"); var seminarPerson = new SeminarPerson() { Seminar = application.Seminar, Title = application.JobTitle, Firm = firm, Commodities = new List<Commodity>(application.Commodities), FirmType = application.FirmType, OtherFirmType = application.OtherFirmType }; if (!string.IsNullOrWhiteSpace(application.OtherCommodity)) { // transfer "other" commodities var others = application.OtherCommodity.Split(','); if (others.Count() > 0) { foreach (var com in others) { var existing = _commodityRepository.Queryable.Where(a => a.Name == com).FirstOrDefault(); // check for an existing commodity if (existing != null) { // assign that commodity if it exists seminarPerson.Commodities.Add(existing); } else { // otherwise create a new one var newcom = new Commodity() { IsActive = false, Name = com }; seminarPerson.Commodities.Add(newcom); } } } } person.AddSeminarPerson(seminarPerson); UpdateAddress(person, application); UpdateAssistant(person, application); person.TransferValidationMessagesTo(modelState); seminarPerson.TransferValidationMessagesTo(modelState); if (modelState.IsValid) { _firmRepository.EnsurePersistent(firm); _personRepository.EnsurePersistent(person); _seminarPersonRepository.EnsurePersistent(seminarPerson); return person; } return null; }
/// <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> /// Ported from draft_t::insert /// </summary> public Xact Insert(Journal journal) { if (Tmpl == null) { return(null); } if (Tmpl.PayeeMask == null) { throw new RuntimeError(RuntimeError.ErrorMessageXactCommandRequiresAtLeastAPayee); } Xact matching = null; Xact added = new Xact(); Xact xact = Lookup.LookupProbableAccount(Tmpl.PayeeMask.ToString(), journal.Xacts.Reverse()).Item1; if (xact != null) { Logger.Current.Debug("draft.xact", () => String.Format("Found payee by lookup: transaction on line {0}", xact.Pos.BegLine)); matching = xact; } else { matching = journal.Xacts.LastOrDefault(x => Tmpl.PayeeMask.Match(x.Payee)); if (matching != null) { Logger.Current.Debug("draft.xact", () => String.Format("Found payee match: transaction on line {0}", matching.Pos.BegLine)); } } if (!Tmpl.Date.HasValue) { added.Date = TimesCommon.Current.CurrentDate; Logger.Current.Debug("draft.xact", () => "Setting date to current date"); } else { added.Date = Tmpl.Date; Logger.Current.Debug("draft.xact", () => String.Format("Setting date to template date: {0}", Tmpl.Date)); } added.State = ItemStateEnum.Uncleared; if (matching != null) { added.Payee = matching.Payee; //added->code = matching->code; //added->note = matching->note; Logger.Current.Debug("draft.xact", () => String.Format("Setting payee from match: {0}", added.Payee)); } else { added.Payee = Tmpl.PayeeMask.ToString(); Logger.Current.Debug("draft.xact", () => String.Format("Setting payee from template: {0}", added.Payee)); } if (!String.IsNullOrEmpty(Tmpl.Code)) { added.Code = Tmpl.Code; Logger.Current.Debug("draft.xact", () => String.Format("Now setting code from template: {0}", added.Code)); } if (!String.IsNullOrEmpty(Tmpl.Note)) { added.Note = Tmpl.Note; Logger.Current.Debug("draft.xact", () => String.Format("Now setting note from template: {0}", added.Note)); } if (!Tmpl.Posts.Any()) { if (matching != null) { Logger.Current.Debug("draft.xact", () => "Template had no postings, copying from match"); foreach (Post post in matching.Posts) { added.AddPost(new Post(post) { State = ItemStateEnum.Uncleared }); } } else { throw new RuntimeError(String.Format(RuntimeError.ErrorMessageNoAccountsAndNoPastTransactionMatchingSmth, Tmpl.PayeeMask.ToString())); } } else { Logger.Current.Debug("draft.xact", () => "Template had postings"); bool anyPostHasAmount = Tmpl.Posts.Any(p => (bool)p.Amount); if (anyPostHasAmount) { Logger.Current.Debug("draft.xact", () => " and at least one has an amount specified"); } foreach (DraftXactPostTemplate post in Tmpl.Posts) { Post newPost = null; Commodity foundCommodity = null; if (matching != null) { if (post.AccountMask != null) { Logger.Current.Debug("draft.xact", () => "Looking for matching posting based on account mask"); Post x = matching.Posts.FirstOrDefault(p => post.AccountMask.Match(p.Account.FullName)); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => String.Format("Founding posting from line {0}", x.Pos.BegLine)); } } else { if (post.From) { Post x = matching.Posts.LastOrDefault(p => p.MustBalance); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Copied last real posting from matching"); } } else { Post x = matching.Posts.FirstOrDefault(p => p.MustBalance); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Copied first real posting from matching"); } } } } if (newPost == null) { newPost = new Post(); Logger.Current.Debug("draft.xact", () => "New posting was NULL, creating a blank one"); } if (newPost.Account == null) { Logger.Current.Debug("draft.xact", () => "New posting still needs an account"); if (post.AccountMask != null) { Logger.Current.Debug("draft.xact", () => "The template has an account mask"); Account acct = journal.FindAccountRe(post.AccountMask.ToString()); if (acct != null) { Logger.Current.Debug("draft.xact", () => "Found account as a regular expression"); } else { acct = journal.FindAccount(post.AccountMask.ToString()); if (acct != null) { Logger.Current.Debug("draft.xact", () => "Found (or created) account by name"); } } // Find out the default commodity to use by looking at the last // commodity used in that account foreach (Xact j in journal.Xacts.Reverse()) { Post x = j.Posts.FirstOrDefault(p => p.Account == acct && !(p.Amount == null || p.Amount.IsEmpty)); if (x != null) { newPost = new Post(x); Logger.Current.Debug("draft.xact", () => "Found account in journal postings, setting new posting"); break; } } newPost.Account = acct; Logger.Current.Debug("draft.xact", () => String.Format("Set new posting's account to: {0}", acct.FullName)); } else { if (post.From) { newPost.Account = journal.FindAccount("Liabilities:Unknown"); Logger.Current.Debug("draft.xact", () => "Set new posting's account to: Liabilities:Unknown"); } else { newPost.Account = journal.FindAccount("Expenses:Unknown"); Logger.Current.Debug("draft.xact", () => "Set new posting's account to: Expenses:Unknown"); } } } if (newPost.Account == null) { throw new InvalidOperationException("assert(new_post->account)"); } if (newPost != null && !(newPost.Amount == null || newPost.Amount.IsEmpty)) { foundCommodity = newPost.Amount.Commodity; if (anyPostHasAmount) { newPost.Amount = new Amount(); Logger.Current.Debug("draft.xact", () => "New posting has an amount, but we cleared it"); } else { anyPostHasAmount = true; Logger.Current.Debug("draft.xact", () => "New posting has an amount, and we're using it"); } } if ((bool)post.Amount) { newPost.Amount = post.Amount; Logger.Current.Debug("draft.xact", () => "Copied over posting amount"); if (post.From) { newPost.Amount.InPlaceNegate(); Logger.Current.Debug("draft.xact", () => "Negated new posting amount"); } } if ((bool)post.Cost) { if (post.Cost.Sign < 0) { throw new ParseError(ParseError.ParseError_PostingCostMayNotBeNegative); } post.Cost.InPlaceUnround(); if (post.CostOperator == "@") { // For the sole case where the cost might be uncommoditized, // guarantee that the commodity of the cost after multiplication // is the same as it was before. Commodity costCommodity = post.Cost.Commodity; post.Cost = post.Cost.Multiply(newPost.Amount); post.Cost.SetCommodity(costCommodity); } else if (newPost.Amount.Sign < 0) { newPost.Cost.InPlaceNegate(); } newPost.Cost = post.Cost; Logger.Current.Debug("draft.xact", () => "Copied over posting cost"); } if (foundCommodity != null && !(newPost.Amount == null) && !(newPost.Amount.IsEmpty) && !(newPost.Amount.HasCommodity)) { newPost.Amount.SetCommodity(foundCommodity); Logger.Current.Debug("draft.xact", () => String.Format("Set posting amount commodity to: {0}", newPost.Amount.Commodity)); newPost.Amount = newPost.Amount.Rounded(); Logger.Current.Debug("draft.xact", () => String.Format("Rounded posting amount to: {0}", newPost.Amount)); } added.AddPost(newPost); newPost.Account.AddPost(newPost); newPost.State = ItemStateEnum.Uncleared; Logger.Current.Debug("draft.xact", () => "Added new posting to derived entry"); } } if (!journal.AddXact(added)) { throw new RuntimeError(RuntimeError.ErrorMessageFailedToFinalizeDerivedTransactionCheckCommodities); } return(added); }
public void Commodity_ParseSymbol_HandlesNonCkisedQuotes() { string s = " \"asdqwe"; Commodity.ParseSymbol(ref s); }
public async Task <IEnumerable <Commodity> > GetCommoditiesAsync(string companyId, Commodity commodity = null, int?offset = null, int?limit = null) { return(await _masterDataRepository.GetCommoditiesAsync(companyId, commodity, offset, limit)); }
protected bool Equals(Commodity other) { return _id == other._id; }
public TransportPurchase(Commodity commodity, int quantity, decimal transportCosts) : base(commodity, quantity) { this.transportCosts = transportCosts; }
public int quantity; // amount of in game lives/coins received in this package public ProductData(Commodity commodity, int coinPrice, int quantity) { this.commodity = commodity; this.coinPrice = coinPrice; this.quantity = quantity; }
/// <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); }
public IEnumerable<ViewModels.Report.Data.BinCardViewModel> GetBinCard(int hubID, int? StoreID, int? CommodityID, string ProjectID) { var commodity = new Commodity(); if (CommodityID.HasValue) commodity = FindCommodityById(CommodityID.Value); List<BinCardReport> results = new List<BinCardReport>(); if (commodity != null && commodity.CommodityTypeID == 1) results = _unitOfWork.ReportRepository.RPT_BinCard(hubID, StoreID, CommodityID, ProjectID).ToList(); else results = _unitOfWork.ReportRepository.RPT_BinCardNonFood(hubID, StoreID, CommodityID, ProjectID).ToList(); //var results = db.RPT_BinCard(hubID,StoreID,CommodityID,ProjectID); var returnValue = new List<BinCardViewModel>(); decimal balance = 0; foreach (var res in results) { balance += (res.Received.HasValue) ? res.Received.Value : 0; balance -= (res.Dispatched.HasValue) ? res.Dispatched.Value : 0; returnValue.Add(new BinCardViewModel { SINumber = res.SINumber, DriverName = res.DriverName, Transporter = res.Transporter, TransporterAM = res.TransporterAM, Date = res.Date, Project = res.Projesct, Dispatched = res.Dispatched, Received = res.Received, Balance = balance, Identification = res.Identification, ToFrom = res.ToFrom }); } return returnValue; }
public void MemoizedPriceEntry_Integration_CanBeUsedAsDictionaryKey() { DateTime dt1 = new DateTime(2010, 10, 15); DateTime dt2 = new DateTime(2015, 10, 25); Commodity comm1 = new Commodity(CommodityPool.Current, new CommodityBase("memprice1")); Commodity comm2 = new Commodity(CommodityPool.Current, new CommodityBase("memprice2")); MemoizedPriceEntry key1 = new MemoizedPriceEntry(); MemoizedPriceEntry key2 = new MemoizedPriceEntry() { Start = dt1 }; MemoizedPriceEntry key3 = new MemoizedPriceEntry() { Start = dt1, End = dt2 }; MemoizedPriceEntry key4 = new MemoizedPriceEntry() { Start = dt2, End = dt1 }; MemoizedPriceEntry key5 = new MemoizedPriceEntry() { End = dt2 }; MemoizedPriceEntry key6 = new MemoizedPriceEntry() { Start = dt1, Commodity = comm1 }; MemoizedPriceEntry key7 = new MemoizedPriceEntry() { Start = dt1, End = dt2, Commodity = comm1 }; MemoizedPriceEntry key8 = new MemoizedPriceEntry() { Start = dt2, End = dt1, Commodity = comm1 }; MemoizedPriceEntry key9 = new MemoizedPriceEntry() { End = dt2, Commodity = comm1 }; MemoizedPriceEntry key10 = new MemoizedPriceEntry() { Commodity = comm1 }; MemoizedPriceEntry key11 = new MemoizedPriceEntry() { Start = dt1, Commodity = comm2 }; MemoizedPriceEntry key12 = new MemoizedPriceEntry() { Start = dt1, End = dt2, Commodity = comm2 }; MemoizedPriceEntry key13 = new MemoizedPriceEntry() { Start = dt2, End = dt1, Commodity = comm2 }; MemoizedPriceEntry key14 = new MemoizedPriceEntry() { End = dt2, Commodity = comm2 }; MemoizedPriceEntry key15 = new MemoizedPriceEntry() { Commodity = comm2 }; IDictionary <MemoizedPriceEntry, string> dictionary = new Dictionary <MemoizedPriceEntry, string>(); dictionary[key1] = "1"; dictionary[key2] = "2"; dictionary[key3] = "3"; dictionary[key4] = "4"; dictionary[key5] = "5"; dictionary[key6] = "6"; dictionary[key7] = "7"; dictionary[key8] = "8"; dictionary[key9] = "9"; dictionary[key10] = "10"; dictionary[key11] = "11"; dictionary[key12] = "12"; dictionary[key13] = "13"; dictionary[key14] = "14"; dictionary[key15] = "15"; MemoizedPriceEntry check1 = new MemoizedPriceEntry(); MemoizedPriceEntry check2 = new MemoizedPriceEntry() { Start = dt1 }; MemoizedPriceEntry check3 = new MemoizedPriceEntry() { Start = dt1, End = dt2 }; MemoizedPriceEntry check4 = new MemoizedPriceEntry() { Start = dt2, End = dt1 }; MemoizedPriceEntry check5 = new MemoizedPriceEntry() { End = dt2 }; MemoizedPriceEntry check6 = new MemoizedPriceEntry() { Start = dt1, Commodity = comm1 }; MemoizedPriceEntry check7 = new MemoizedPriceEntry() { Start = dt1, End = dt2, Commodity = comm1 }; MemoizedPriceEntry check8 = new MemoizedPriceEntry() { Start = dt2, End = dt1, Commodity = comm1 }; MemoizedPriceEntry check9 = new MemoizedPriceEntry() { End = dt2, Commodity = comm1 }; MemoizedPriceEntry check10 = new MemoizedPriceEntry() { Commodity = comm1 }; MemoizedPriceEntry check11 = new MemoizedPriceEntry() { Start = dt1, Commodity = comm2 }; MemoizedPriceEntry check12 = new MemoizedPriceEntry() { Start = dt1, End = dt2, Commodity = comm2 }; MemoizedPriceEntry check13 = new MemoizedPriceEntry() { Start = dt2, End = dt1, Commodity = comm2 }; MemoizedPriceEntry check14 = new MemoizedPriceEntry() { End = dt2, Commodity = comm2 }; MemoizedPriceEntry check15 = new MemoizedPriceEntry() { Commodity = comm2 }; Assert.Equal("1", dictionary[check1]); Assert.Equal("2", dictionary[check2]); Assert.Equal("3", dictionary[check3]); Assert.Equal("4", dictionary[check4]); Assert.Equal("5", dictionary[check5]); Assert.Equal("6", dictionary[check6]); Assert.Equal("7", dictionary[check7]); Assert.Equal("8", dictionary[check8]); Assert.Equal("9", dictionary[check9]); Assert.Equal("10", dictionary[check10]); Assert.Equal("11", dictionary[check11]); Assert.Equal("12", dictionary[check12]); Assert.Equal("13", dictionary[check13]); Assert.Equal("14", dictionary[check14]); Assert.Equal("15", dictionary[check15]); }
public ActionResult InOutWarehouse(string BtnSubmit, Commodity commodity, string sid, int Count) { InOutWarehouseViewModel inOutWarehouseViewModel = new InOutWarehouseViewModel(); inOutWarehouseViewModel.UserName = Session["User"].ToString(); if (BtnSubmit == "手动入库" || BtnSubmit == "手动出库") { if (!SelectIntoOut) { //显示物品的数据 CommodityBusinessLayer commodityBusinessLayer = new CommodityBusinessLayer(); inOutWarehouseViewModel.commodity = commodityBusinessLayer.GetCommodity(sid, commodity); if (!inOutWarehouseViewModel.commodity.Equals(commodity)) { SelectIntoOut = true; } } else { //存储数据到Storage表(出入库单号、物品号、物品数量) StorageBusinessLayer storageBusinessLayer = new StorageBusinessLayer(); Storage storage = new Storage(); storage.Co_id = commodity.Co_Id; //storage.IO_Id = Session["Table_Id"].ToString(); storage.IO_Id = Table_Id; storage.Count = Count; storage.IntoDate = DateTime.Now; storageBusinessLayer.InsertStorage(storage); SelectIntoOut = false; inOutWarehouseViewModel.commodity = new Commodity(); } } else { StorageBusinessLayer storageBusinessLayer = new StorageBusinessLayer(); if (BtnSubmit == "完成入库") { //将入库的数据存储到Exist表中 ExistBusinessLayer existBusinessLayer = new ExistBusinessLayer(); InOutWarehouseBusinessLayer inOutWarehouseBusinessLayer = new InOutWarehouseBusinessLayer(); Exist exist; List <Storage> storages = storageBusinessLayer.GetStorage("IO_Id", Table_Id); foreach (Storage storage in storages) { exist = inOutWarehouseBusinessLayer.GetExist(storage); existBusinessLayer.InsertExist(exist); } } else if (BtnSubmit == "完成出库") { //将入库的数据在exit表中删除 //将入库的数据存储到Exist表中 ExistBusinessLayer existBusinessLayer = new ExistBusinessLayer(); InOutWarehouseBusinessLayer inOutWarehouseBusinessLayer = new InOutWarehouseBusinessLayer(); //Exist exist; List <Storage> storages = storageBusinessLayer.GetStorage("IO_Id", Table_Id); foreach (Storage storage in storages) { existBusinessLayer.Delete(storage); } } else if (BtnSubmit == "取消入库" || BtnSubmit == "取消出库") { //将入库的数据删除 storageBusinessLayer.Delete(Table_Id); OutIntoWareBusinessLayer outIntoWareBusinessLayer = new OutIntoWareBusinessLayer(); outIntoWareBusinessLayer.Delete(Table_Id); } IsIntoOutWaretor = false; //设置为不是出入库状态IsIntoOutWaretor = false; SelectIntoOut = false; //设置状态为取消SelectIntoOut = false; Table_Id = ""; //表数据清除 } I_commodity = inOutWarehouseViewModel.commodity; return(RedirectToAction("RedirectInOutWarehouse")); //return View("inOutWarehouse", inOutWarehouseViewModel); }
private CustomsClearanceDetail buildCustomClearanceSpec() { CustomsClearanceDetail spec = new CustomsClearanceDetail(); spec.CommercialInvoice = new CommercialInvoice(); spec.CommercialInvoice.Purpose = PurposeOfShipmentType.SOLD; spec.CommercialInvoice.PurposeSpecified = true; spec.DocumentContent = InternationalDocumentContentType.NON_DOCUMENTS; spec.DutiesPayment = new Payment(); if (currentDespatch.ShippingAddressCountry == "CA") { spec.DutiesPayment.PaymentType = PaymentType.SENDER; spec.DutiesPayment.Payor = new Payor(); spec.DutiesPayment.Payor.ResponsibleParty = shipper; spec.CommercialInvoice.TermsOfSale = "DDP"; } else { spec.DutiesPayment.PaymentType = PaymentType.RECIPIENT; spec.CommercialInvoice.TermsOfSale = "DDU"; } List<Commodity> items = new List<Commodity>(); decimal desired = 9.0M/currentDespatch.Items.Length; // HAX decimal total = 0.0M; foreach(var item in currentDespatch.Items) { Commodity com = new Commodity(); com.NumberOfPieces = item.QuantityOrdered; com.Description = item.ItemGroupName; if (string.IsNullOrEmpty(item.Attribute5)) { com.CountryOfManufacture = "BD"; } else { com.CountryOfManufacture = LookupCountryCode(item.Attribute5); } com.Weight = new Weight(); com.Weight.Value = decimal.Parse(item.Weight); com.Weight.Units = WeightUnits.KG; com.Quantity = decimal.Parse(item.QuantityOrdered); com.QuantitySpecified = true; com.QuantityUnits = "EA"; com.UnitPrice = new Money(); //com.UnitPrice.Amount = decimal.Parse(item.SalePrice); com.UnitPrice.Amount = desired / com.Quantity; // HAX total += com.UnitPrice.Amount * com.Quantity; com.UnitPrice.Currency = "UKL"; com.CustomsValue = com.UnitPrice; com.PartNumber = item.Barcode; items.Add(com); } spec.Commodities = items.ToArray(); spec.CustomsValue = new Money(); spec.CustomsValue.Amount = total; spec.CustomsValue.Currency = "UKL"; return spec; }