private void Query(Action<IQueryable<ProductMapEntity>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var pms = db.Set<ProductMapEntity>()
                          .Join(db.Set<ProductEntity>().Where(p=>p.Status==1),o=>o.ProductId,i=>i.Id,(o,i)=>o)
                          .Where(pm => !db.Set<ResourceEntity>().Where(r => r.SourceType == (int)SourceType.Product).Any(r => r.SourceId == pm.ProductId));

                if (callback != null)
                    callback(pms);
            }
        }
        private void Query(Action<IQueryable<ExOrderEntity>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {

                var prods = db.Set<ExOrderEntity>().Where(o =>o.IsShipped.HasValue && o.IsShipped.Value== true
                            && !db.Set<JobSuccessHistoryEntity>().Any(j => j.JobType == (int)JobType.Wx_ShippingEx && j.JobId == o.Id));


                if (callback != null)
                    callback(prods);
            }
        }
         private void Query(Action<IQueryable<OrderEntity>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {

                var prods = db.Set<OrderEntity>().Where(o => o.Status >= (int)OrderStatus.Shipped
                            && o.OrderSource == WxPayConfig.ORDER_SOURCE
                            && !db.Set<JobSuccessHistoryEntity>().Any(j => j.JobType == (int)JobType.Wx_Shipping && j.JobId == o.Id));


                if (callback != null)
                    callback(prods);
            }
        }
        private void Query(DateTime benchTime, Action<IQueryable<Map4Order>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var orders =
                    db.Set<Map4Order>()
                        .Where(
                            m =>
                                m.CreateDate >= benchTime && m.Channel == ConstValue.WGW_CHANNEL_NAME &&
                                !db.Set<Order2ExEntity>().Any(o => o.OrderNo == m.OrderNo));

                if (callback != null)
                    callback(orders);
            }
        }
        public static void SyncOne(PRO_CLASS_DICT cat)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var existCat = db.Set<CategoryEntity>().Where(b => b.ExCatId == cat.SID).FirstOrDefault();
                if (existCat == null)
                {
                    db.Categories.Add(new CategoryEntity()
                    {
                        ExCatCode = cat.PRO_CLASS_NUM,
                        ExCatId = (int)cat.SID,
                        Name = cat.PRO_CLASS_DESC,
                        Status = 1,
                        UpdateDate = cat.OPT_UPDATE_TIME ?? DateTime.Now

                    });
                }
                else
                {
                    existCat.ExCatCode = cat.PRO_CLASS_NUM;
                    existCat.Name = cat.PRO_CLASS_DESC;
                    existCat.UpdateDate = cat.OPT_UPDATE_TIME ?? DateTime.Now;
                }
                db.SaveChanges();

            }
        }
Beispiel #6
0
        private void Query(DateTime benchTime, Action<IQueryable<OrderTransactionEntity>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var accounts = db.Set<OrderTransactionEntity>().Where(ot => ot.IsSynced == false);

                if (callback != null)
                    callback(accounts);
            }
        }
        private void Query(DateTime benchTime, Action<IQueryable<OrderEntity>> callback)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var orders = db.Set<OrderEntity>().Where(ot => ot.Status == (int)OrderStatus.Create 
                            && ot.CreateDate < benchTime);

                if (callback != null)
                    callback(orders);
            }
        }
        private static void EnsureSectionContext(SALE_CODE section)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var entity = db.Set<StoreEntity>().Where(b => b.ExStoreId == section.SHOP_SID).FirstOrDefault();
                if (null == entity)
                {
                    StoreSyncJob.SyncOne(section.SHOP_INFO);
                }

            }
        }
Beispiel #9
0
        public static void SyncOne(SHOP_INFO store)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var existStore = db.Set<StoreEntity>().Where(b => b.ExStoreId == store.SID).FirstOrDefault();
                if (existStore == null)
                {
                    db.Stores.Add(new StoreEntity()
                    {

                        CreatedDate = DateTime.Now,
                        CreatedUser = 0,
                        ExStoreId = (int)store.SID,
                        Description = string.Empty,
                        Location = store.SHOP_ADDR??string.Empty,
                        Name = store.SHOP_NAME,
                        RMAAddress = store.SHOP_ADDR,
                        RMAPerson = store.REFUND_LINKER,
                        RMAPhone = store.REFUND_TEL,
                        RMAZipCode = store.POSTCODE.HasValue?store.POSTCODE.ToString():string.Empty,
                        UpdatedDate = store.OPT_UPDATE_TIME ?? DateTime.Now,
                        UpdatedUser = 0,
                        Status = 1,
                        Tel = store.LINKER_PHONE??string.Empty

                    });
                }
                else
                {
                    existStore.RMAZipCode = store.POSTCODE.HasValue ? store.POSTCODE.ToString() : string.Empty;
                    existStore.RMAPhone = store.REFUND_TEL;
                    existStore.RMAAddress = store.SHOP_ADDR;
                    existStore.RMAPerson = store.REFUND_LINKER;
                    existStore.UpdatedDate = store.OPT_UPDATE_TIME ?? DateTime.Now;
                    existStore.Location = store.SHOP_ADDR??string.Empty;
                    existStore.Tel = store.LINKER_PHONE ?? string.Empty;
                    existStore.Name = store.SHOP_NAME;
                    db.Entry(existStore).State = System.Data.EntityState.Modified;
                }
                db.SaveChanges();

            }
        }
Beispiel #10
0
        public static void SyncOne(BRAND brand)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var existBrand = db.Set<BrandEntity>().Where(b => b.ChannelBrandId == brand.SID).FirstOrDefault();
                if (existBrand == null)
                {
                    db.Brands.Add(new BrandEntity()
                    {
                        ChannelBrandId = (int)brand.SID,
                        CreatedDate = DateTime.Now,
                        CreatedUser = 0,
                        Name = brand.BRAND_NAME,
                        EnglishName = brand.BRAND_NAME_SECOND,
                        Logo = brand.PICTURE_URL??string.Empty,
                        Status = brand.BRAND_ACTIVE_BIT,
                        UpdatedDate = brand.OPT_UPDATE_TIME ?? DateTime.Now,
                        UpdatedUser = 0,
                        Description = brand.BRAND_STORY??string.Empty,
                        Group = (brand.BRAND_GROUP_NUM??0).ToString(),
                         WebSite = string.Empty

                    });
                }
                else
                {
                    existBrand.Name = brand.BRAND_NAME;
                    existBrand.EnglishName = brand.BRAND_NAME_SECOND;
                    existBrand.Logo = brand.PICTURE_URL??string.Empty;;
                    existBrand.Status = brand.BRAND_ACTIVE_BIT;
                    existBrand.UpdatedUser = 0;
                    existBrand.UpdatedDate = brand.OPT_UPDATE_TIME ?? DateTime.Now;
                    existBrand.Description = brand.BRAND_STORY??string.Empty;
                    existBrand.Group = (brand.BRAND_GROUP_NUM ?? 0).ToString();

                    db.Entry(existBrand).State = System.Data.EntityState.Modified;
                  
                }
                db.SaveChanges();

            }
        }
 private static void EnsureProductContext(SUPPLY_MIN_PRICE product)
 {
     using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
     {
         var exBrand = db.Set<BrandEntity>().Where(b => b.ChannelBrandId == product.BRAND_SID).FirstOrDefault();
         if (null == exBrand)
         {
             using (var erpDb = new ErpContext())
             {
                 var brand = erpDb.Set<BRAND>().Find(product.BRAND_SID);
                 if (null != brand)
                     BrandSyncJob.SyncOne(brand);
             }
         }
         var exCat = db.Set<CategoryEntity>().Where(c => c.ExCatId == product.PRO_CLASS_SID).FirstOrDefault();
         if (null == exCat)
         {
             using (var erpDb = new ErpContext())
             {
                 var cat = erpDb.Set<PRO_CLASS_DICT>().Find(product.PRO_CLASS_SID);
                 if (null != cat)
                     CategorySyncJob.SyncOne(cat);
             }
         }
         var exStore = db.Set<StoreEntity>().Where(c => c.ExStoreId == product.SHOP_SID).FirstOrDefault();
         if (null == exStore)
         {
             using (var erpDb = new ErpContext())
             {
                 var store = erpDb.Set<SHOP_INFO>().Find(product.SHOP_SID);
                 if (null != store)
                     StoreSyncJob.SyncOne(store);
             }
         }
     }
 }
        public static bool SyncOne(SUPPLY_MIN_PRICE product)
        {
            EnsureProductContext(product);
            if (!product.SHOP_SID.HasValue)
                return false;
            using (var ts = new TransactionScope())
            {
                using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
                {
                    var existProduct = db.Set<ProductMapEntity>().Where(b => b.ChannelPId == product.PRODUCT_SID).FirstOrDefault();
                    var tagEntity = db.Set<TagEntity>().Join(db.Set<CategoryMapEntity>().Where(cm => cm.ChannelCatId == product.PRO_CLASS_SID), o => o.Id, i => i.CatId, (o, i) => o)
                                    .FirstOrDefault();
            
                    var storeEntity = db.Set<StoreEntity>().Where(s => s.ExStoreId == product.SHOP_SID).FirstOrDefault();
                    if (storeEntity == null)
                    {
                        Log.Error(string.Format("product sid has no store:{0}", product.PRODUCT_SID));
                        return false;
                    }
                    var brandEntity = db.Set<BrandEntity>().Where(b => b.ChannelBrandId == product.BRAND_SID).FirstOrDefault();
                    if (brandEntity == null)
                    {
                        Log.Error(string.Format("product sid has no brand:{0}", product.PRODUCT_SID));
                        return false;
                    }
                    if (existProduct == null)
                    {
                        var newProduct = new ProductEntity()
                        {
                            CreatedDate = DateTime.Now,
                            CreatedUser = DEFAULT_OWNER_ID,
                            SkuCode = product.PRO_SKU,
                            Brand_Id = brandEntity == null ? 0 : brandEntity.Id,
                            Description = product.PRO_DESC ?? string.Empty,
                            Is4Sale = false,
                            Name = string.IsNullOrEmpty(product.PRODUCT_NAME)? string.Format("{0}-{1}", brandEntity.Name, product.PRO_SKU):product.PRODUCT_NAME,
                            UnitPrice = product.ORIGINAL_PRICE ?? NULL_PRICE,
                            RecommendedReason = product.PRO_DESC ?? string.Empty,
                            RecommendUser = DEFAULT_OWNER_ID,
                            SortOrder = 0,
                            Status = (int)DataStatus.Default,
                            Store_Id = storeEntity == null ? 0 : storeEntity.Id,
                            Tag_Id = tagEntity == null ? int.Parse(DEFAULT_TAG_ID) : tagEntity.Id,
                            Price = product.PROMOTION_PRICE ?? NULL_PRICE,
                            UpdatedDate = product.OPT_UPDATE_TIME ?? DateTime.Now,
                            UpdatedUser = DEFAULT_OWNER_ID,
                            BarCode = product.BARCODE,
                            Favorable = "1"


                        };
                        db.Products.Add(newProduct);
                        db.SaveChanges();
                        db.ProductMaps.Add(new ProductMapEntity()
                        {
                            Channel = "ERP",
                            ChannelBrandId = (int)product.BRAND_SID,
                            ChannelPId = (int)product.PRODUCT_SID,
                            ChannelCatId = (int)(product.PRO_CLASS_SID??0m),
                            ProductId = newProduct.Id,
                            UpdateDate = product.OPT_UPDATE_TIME ?? DateTime.Now
                        });
                    }
                    else
                    {
                        var existProductEntity = db.Set<ProductEntity>().Find(existProduct.ProductId);
                        existProductEntity.BarCode = product.BARCODE;
                        existProductEntity.UpdatedDate = product.OPT_UPDATE_TIME ?? DateTime.Now;
                        existProductEntity.Store_Id = storeEntity == null ? 0 : storeEntity.Id;
                        existProductEntity.Brand_Id = brandEntity == null ? 0 : brandEntity.Id;
                        existProductEntity.Tag_Id = tagEntity == null ? int.Parse(DEFAULT_TAG_ID) : tagEntity.Id;
                        existProductEntity.SkuCode = product.PRO_SKU;
                        existProductEntity.Name = string.IsNullOrEmpty(product.PRODUCT_NAME) ? string.Format("{0}-{1}", brandEntity.Name, product.PRO_SKU) : product.PRODUCT_NAME;
                        existProductEntity.UnitPrice = product.ORIGINAL_PRICE ?? NULL_PRICE;
                        existProductEntity.Price = product.PROMOTION_PRICE ?? NULL_PRICE;
                        existProductEntity.Description = product.PRO_DESC ?? string.Empty;
                        existProductEntity.RecommendedReason = product.PRO_DESC ?? string.Empty;

                    }
                    db.SaveChanges();

                }
                ts.Complete();
            }
            return true;
        }
        private static bool EnsureProductContext(decimal pid)
        {
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var productEntity = db.Set<ProductMapEntity>().Where(b => b.ChannelPId == pid).FirstOrDefault();
                if (null == productEntity)
                {
                    using (var erpDb = new ErpContext())
                    {
                        var exProduct = erpDb.Set<SUPPLY_MIN_PRICE>().Where(ep => ep.PRODUCT_SID == pid).FirstOrDefault();
                        if (null != exProduct)
                           return ProductSyncJob.SyncOne(exProduct);
                    }

                }
                return true;
            }
        }
Beispiel #14
0
        public static bool OrderPaid2Erp(OrderTransactionEntity order,bool isOnlinePay = true)
        {
            string vipCard = string.Empty;
            var log = ServiceLocator.Current.Resolve<ILog>();
            if (order.OutsiteType.HasValue && order.OutsiteType.Value == (int)OutsiteType.WX
                && !string.IsNullOrEmpty(order.OutsiteUId))
            {
                try
                {
                    AwsHelper.SendHttpMessage(string.Format("{0}card/find", ConfigManager.AwsHost), new
                    {
                        uid = order.OutsiteUId
                    }, ConfigManager.AwsHttpPublicKey, ConfigManager.AwsHttpPrivateKey, r => vipCard = r.data, null);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }
            bool isSuccess = false;
            if (order.OrderType == (int)PaidOrderType.Erp2)
            {
                isSuccess = Erp2ServiceHelper.SendHttpMessage(Erp2Config.PAY_URL, new { saleno = order.OrderNo, paymentcode = order.PaymentCode, transno = order.TransNo, vipno = vipCard }, null
                              , null);
            }
            else
            {
                var paymentName = string.Empty;

                string dealCode = order.OrderNo;

                using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
                {
                    var paymentEntity = db.Set<PaymentMethodEntity>().Where(p => p.Code == order.PaymentCode).FirstOrDefault();
                    if (paymentEntity == null)
                    {
                        log.Error(string.Format("orderno :{1} not support payment code paid:{0}", order.PaymentCode, order.OrderNo));
                        return false;
                    }
                    paymentName = paymentEntity.Name;

                    //渠道订单同步时传递的是渠道订单号
                    var channelOrder = db.Set<Map4Order>().FirstOrDefault(o=>o.OrderNo==dealCode);
                    if (channelOrder != null && !string.IsNullOrEmpty(channelOrder.ChannelOrderCode))
                    {
                        dealCode = channelOrder.ChannelOrderCode;
                    }
                }
                var paidFunc = isOnlinePay ? "WebOrdersPaid" : "WebSalesPaid";
                isSuccess = ErpServiceHelper.SendHttpMessage(ConfigManager.ErpBaseUrl, new { func = paidFunc, dealCode, PAY_TYPE = order.PaymentCode, PaymentName = paymentName, TRADE_NO = order.TransNo, CardNo = vipCard }, null
                              , null);
            }
            if (isSuccess)
            {
                using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
                {
                    order.IsSynced = true;
                    order.SyncDate = DateTime.Now;
                    db.Entry(order).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            return isSuccess;
        }
        public void Execute(IJobExecutionContext context)
        {
            ILog log = LogManager.GetLogger(this.GetType());

            JobDataMap data = context.JobDetail.JobDataMap;
            var benchDate = data.ContainsKey("benchdate") ? data.GetDateTime("benchdate") : DateTime.Today.AddDays(-1);
            var interval = data.ContainsKey("intervalOfSecs") ? data.GetInt("intervalOfSecs") : 5 * 60;
            int successCount = 0;
            int cursor = 0;
            int size = JobConfig.DEFAULT_PAGE_SIZE;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            int totalCount = 0;
            Query(o => totalCount = o.Count());
            while (cursor < totalCount)
            {
                var orderList = new List<ExOrderEntity>();
                Query(o => orderList = o.OrderBy(p => p.Id).Skip(cursor).Take(size).ToList());

                foreach (var l in orderList)
                {
                    using (var ts = new TransactionScope())
                    {
                        using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
                        {
                            db.JobSuccessHistories.Add(new JobSuccessHistoryEntity()
                            {
                                CreateDate = DateTime.Now,
                                JobId = l.Id,
                                JobType = (int)JobType.Wx_ShippingEx
                            });
                            var linq = db.Set<OrderTransactionEntity>().Where(ot => ot.PaymentCode == WxPayConfig.PaymentCode 
                                    && ot.OrderType == (int)PaidOrderType.Erp
                                    && ot.OrderNo == l.ExOrderNo).FirstOrDefault();
                            if (linq == null)
                            {
                                log.Info(string.Format("order has not transaction:{0}", l.ExOrderNo));
                                continue;
                            }

                            var requestData = new WxNotify()
                            {
                                DeliverMsg = "已提货",
                                DeliverStatus = "1",
                                DeliverTS = DateTime.Now.TicksOfWx().ToString(),
                                OutTradeNo = linq.OrderNo,
                                OpenId = linq.OutsiteUId,
                                TransactionId = linq.TransNo

                            };
                            bool notifyResult = WxServiceHelper.Notify(requestData.EncodedRequest, null, null);
                            if (notifyResult)
                            {
                                ts.Complete();
                                successCount++;
                            }

                        }
                    }

                }

                cursor += size;
            }

            sw.Stop();
            log.Info(string.Format("{0} wx ex orders notified in {1} => {2} docs/s", successCount, sw.Elapsed, successCount / sw.Elapsed.TotalSeconds));

        }
        public static bool SyncOne(decimal pid, decimal sizeId,string sizeName, decimal colorId,string colorName)
        {
            if (!EnsureProductContext(pid))
                return false;
            if (sizeId == 0 || colorId == 0)
            {
                Log.Error(string.Format("product sid:{0} with empty color sid or size sid",pid));
                return false;
            }

            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var product = db.Set<ProductMapEntity>().Where(p=>p.ChannelPId == pid).FirstOrDefault();
                if (product == null)
                    return false; ;
                var existColor = db.Set<ProductPropertyValueEntity>().Where(b =>b.ChannelValueId == colorId)
                                .Join(db.Set<ProductPropertyEntity>().Where(pp=>pp.ProductId==product.ProductId),o=>o.PropertyId,i=>i.Id,(o,i)=>o)
                                .FirstOrDefault();
                if (existColor == null)
                {
                    var colorEntity = db.Set<ProductPropertyEntity>().Where(p => p.ProductId == product.ProductId && p.IsColor.HasValue && p.IsColor.Value == true).FirstOrDefault();
                    if (colorEntity == null)
                    {
                        colorEntity = db.ProductProperties.Add(new ProductPropertyEntity()
                        {
                            IsColor = true,
                            ChannelPropertyId = 0,
                            ProductId = product.ProductId,
                            PropertyDesc = "颜色",
                            SortOrder = 0,
                            Status = 1,
                            UpdateDate = DateTime.Now,
                            UpdateUser = 0

                        });
                        db.SaveChanges();
                    }
                    db.ProductPropertyValues.Add(new ProductPropertyValueEntity() { 
                         ChannelValueId = (int)colorId,
                          PropertyId = colorEntity.Id,
                           CreateDate = DateTime.Now,
                            Status =1,
                            UpdateDate  = DateTime.Now,
                             ValueDesc = colorName
                    });
                }
                else
                {
                    existColor.ValueDesc = colorName;
                    existColor.UpdateDate = DateTime.Now;
                    
                }
                var existSize = db.Set<ProductPropertyValueEntity>().Where(b => b.ChannelValueId == sizeId)
                                .Join(db.Set<ProductPropertyEntity>().Where(pp => pp.ProductId == product.ProductId), o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                if (existSize == null)
                {
                    var sizeEntity = db.Set<ProductPropertyEntity>().Where(p => p.ProductId == product.ProductId && p.IsSize.HasValue && p.IsSize.Value == true).FirstOrDefault();
                    if (sizeEntity == null)
                    {
                        sizeEntity = db.ProductProperties.Add(new ProductPropertyEntity()
                        {
                            IsSize = true,
                            ChannelPropertyId = 0,
                            ProductId = product.ProductId,
                            PropertyDesc = "尺码",
                            SortOrder = 0,
                            Status = 1,
                            UpdateDate = DateTime.Now,
                            UpdateUser = 0

                        });
                        db.SaveChanges();
                    }
                    db.ProductPropertyValues.Add(new ProductPropertyValueEntity()
                    {
                        ChannelValueId = (int)sizeId,
                        PropertyId = sizeEntity.Id,
                        CreateDate = DateTime.Now,
                        Status = 1,
                        UpdateDate = DateTime.Now,
                        ValueDesc = sizeName
                    });
                }
                else
                {
                    existSize.ValueDesc = sizeName;
                    existSize.UpdateDate = DateTime.Now;
                }
                db.SaveChanges();

            }
            return true;
        }
Beispiel #17
0
        public static void SyncOne(SALE_CODE section)
        {
            EnsureSectionContext(section);
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var sectionId = section.SID;
                var existBrand = db.Set<SectionEntity>().Where(b => b.ChannelSectionId == sectionId).FirstOrDefault();
                var storeEntity = db.Set<StoreEntity>().Where(s => s.ExStoreId == section.SHOP_SID).FirstOrDefault();
                if (existBrand == null)
                {
                    db.Sections.Add(new SectionEntity()
                    {
                        ChannelSectionId = (int)section.SID,
                        CreateDate = DateTime.Now,
                        CreateUser = 0,
                        Location = section.ADDRESS ?? string.Empty,
                        Name = section.SALE_CODE_NAME ?? string.Empty,
                        ContactPhone = string.Empty,
                        StoreId = storeEntity.Id,
                        Status = (int)DataStatus.Normal,
                        UpdateDate = DateTime.Now,
                        UpdateUser = 0

                    });
                }
                else
                {
                    existBrand.Name = section.SALE_CODE_NAME ?? string.Empty;
                    existBrand.UpdateDate = section.OPT_UPDATE_TIME ?? DateTime.Now;
                    existBrand.Location = section.ADDRESS ?? string.Empty;
                    existBrand.StoreId = storeEntity.Id;
                    db.Entry(existBrand).State = System.Data.EntityState.Modified;
                }
                db.SaveChanges();

            }

        }
Beispiel #18
0
        private int GetInventoryByItemId(YintaiHangzhouContext context, string itemId)
        {
            string snapshotId = SnapShotId2ItemId(itemId);
            var product =
                context.Set<Map4Product>().Where(m => m.Channel == ConstValue.WGW_CHANNEL_NAME && (m.ChannelProductId == itemId || m.ChannelProductId == snapshotId))
                    .Join(context.Set<ProductEntity>(), m => m.ProductId, p => p.Id, (m, p) => p)
                    .FirstOrDefault();
            if (product == null)
            {
                throw new WgwSyncException(string.Format("Can't find product accordding itemId ({0})", itemId));
            }
            int productId = product.Id;
            var cnt = context.Inventories.Count(i => i.ProductId == productId);

            if (cnt == 0)
            {
                throw new WgwSyncException(string.Format("Product ({0}) has no stock", productId));
            }
            if (cnt > 1)
            {
                throw new WgwSyncException(string.Format("Product ({0}) is multi stocks , can't determine which is the correct inventory", productId));
            }
            return context.Inventories.First(i => i.ProductId == productId).Id;
        }
        public static void SyncOne(SUPPLY_MIN_PRICE_MX product)
        {
            if (!EnsureProductContext(product))
                return;
            using (var ts = new TransactionScope())
            {
                using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
                {
                    var existProduct = db.Set<ProductEntity>().Join(db.Set<ProductMapEntity>().Where(ep => ep.ChannelPId == product.PRODUCT_SID), o => o.Id, i => i.ProductId, (o, i) => o).FirstOrDefault();
                    var color = db.Set<ProductPropertyValueEntity>().Where(b => b.ChannelValueId == product.PRO_COLOR_SID)
                                .Join(db.Set<ProductPropertyEntity>().Where(pp => pp.ProductId == existProduct.Id), o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                    var size = db.Set<ProductPropertyValueEntity>().Where(b => b.ChannelValueId == product.PRO_STAN_SID)
                                .Join(db.Set<ProductPropertyEntity>().Where(pp => pp.ProductId == existProduct.Id), o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                    var inventory = db.Set<InventoryEntity>().Where(i => i.ChannelInventoryId == product.PRO_DETAIL_SID).FirstOrDefault();
                    int amount = (int)product.PRO_STOCK_SUM;
                    bool no4sale = product.PRO_ACTIVE_BIT.GetValueOrDefault()==0;
                    if (no4sale)
                        amount = 0;
                    if (inventory == null)
                    {
                        db.Inventories.Add(new InventoryEntity()
                        {
                            ProductId = existProduct.Id,
                            PColorId = color.Id,
                            PSizeId = size.Id,
                            UpdateDate = DateTime.Now,
                            UpdateUser = 0,
                            Amount = amount,
                            ChannelInventoryId = (int)product.PRO_DETAIL_SID
                        });
                    }
                    else
                    {
                        inventory.Amount = amount;
                    }
                    //update product.is4sale
                    if ((existProduct.Is4Sale ?? false) == false && !no4sale)
                    {
                        existProduct.Is4Sale = true;
                        existProduct.UpdatedDate = DateTime.Now;
                    }
                    db.SaveChanges();

                }
                ts.Complete();
            }
        }
        private void SyncOne(PRO_PICTURE product)
        {
            if (!EnsureProductContext(product))
                return ;
            var log = LogManager.GetLogger(this.GetType());
            //download remote picture
            string exPicDomain = ConfigurationManager.AppSettings["EXPIC_DOMAIN"];
            var filePath = FetchRemotePic(string.Format("{0}/{1}",exPicDomain.TrimEnd('/'),Path.Combine(product.PRO_PICT_DIR,product.PRO_PICT_NAME)));
            //resize pics
            var file = new FileInfo(filePath);
            FileInfor uploadFile;
            var uploadResult = FileUploadServiceManager.UploadFile(file, "product", out uploadFile, string.Empty);
            if (uploadResult != FileMessage.Success)
            {
                log.Error(string.Format("upload file error:{0}", filePath));
                 File.Delete(filePath);
                return;
            }
            
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {
                var existPic = db.Set<ResourceEntity>().Where(r => r.ChannelPicId == product.SID).FirstOrDefault();
                if (existPic == null)
                {
                    var colorEntity = db.Set<ProductPropertyValueEntity>().Where(ppv => ppv.ChannelValueId == product.PRO_COLOR_SID)
                                        .Join(db.Set<ProductPropertyEntity>().Join(db.Set<ProductMapEntity>().Where(pm => pm.ChannelPId == product.PRODUCT_SID), o => o.ProductId, i => i.ProductId, (o, i) => o),
                                                o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                    var existProduct = db.Set<ProductEntity>().Join(db.Set<ProductMapEntity>().Where(ep => ep.ChannelPId == product.PRODUCT_SID), o => o.Id, i => i.ProductId, (o, i) => o).FirstOrDefault();
                    db.Resources.Add(new ResourceEntity()
                    {
                        ColorId = colorEntity == null ? 0 : colorEntity.Id,
                        SourceId = existProduct.Id,
                        SourceType = (int)SourceType.Product,
                        ContentSize = uploadFile.FileSize,
                        CreatedDate = DateTime.Now,
                        CreatedUser = 0,
                        Domain = string.Empty,
                        ExtName = uploadFile.FileExtName,
                        Height = uploadFile.Height,
                        IsDefault = product.PICTURE_MAST_BIT == 1 ? true : false,
                        UpdatedDate = product.OPT_UPDATE_TIME ?? DateTime.Now,
                        Name = uploadFile.FileName,
                        Status = 1,
                        SortOrder = (int)product.PRO_PICT_ORDER,
                        Size = string.Format("{0}x{1}", uploadFile.Width, uploadFile.Height),
                        Type = (int)uploadFile.ResourceType,
                        Width = uploadFile.Width,
                        ChannelPicId = (int)product.SID
                    });
                    existProduct.IsHasImage = true;
                    existProduct.UpdatedDate = product.OPT_UPDATE_TIME ?? DateTime.Now;
                    existProduct.Status = (int)DataStatus.Normal;
                    db.SaveChanges();
                }
            }

            File.Delete(filePath);
        }
 private bool EnsureProductContext(PRO_PICTURE product)
 {
     using(var erpDb= new ErpContext())
     {
         
         using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
         {
             var colorEntity = db.Set<ProductPropertyValueEntity>().Where(ppv => ppv.ChannelValueId == product.PRO_COLOR_SID)
                             .Join(db.Set<ProductPropertyEntity>().Join(db.Set<ProductMapEntity>().Where(pm=>pm.ChannelPId==product.PRODUCT_SID),o=>o.ProductId,i=>i.ProductId,(o,i)=>o),
                                     o=>o.PropertyId,i=>i.Id,(o,i)=>o).FirstOrDefault();
             if (colorEntity == null)
             {
                 var exProduct = erpDb.Set<SUPPLY_MIN_PRICE_MX>().Where(ep => ep.PRODUCT_SID == product.PRODUCT_SID && ep.PRO_COLOR_SID == product.PRO_COLOR_SID).FirstOrDefault();
                 if (exProduct == null)
                 {
                     Log.Error(string.Format("product sid:{0} has no inventory record for color_sid:{1}",product.PRODUCT_SID,product.PRO_COLOR_SID));
                     return false;
                 }
                 return ProductPropertySyncJob.SyncOne(exProduct.PRODUCT_SID, exProduct.PRO_STAN_SID ?? 0, exProduct.PRO_STAN_NAME, exProduct.PRO_COLOR_SID ?? 0, exProduct.PRO_COLOR);
             }
  
         }
      
     }
     return true;
 }
        private static bool EnsureProductContext(SUPPLY_MIN_PRICE_MX product)
        {
            bool shouldSyncProduct = false;
            using (var db = new YintaiHangzhouContext("YintaiHangzhouContext"))
            {

                var colorEntity = db.Set<ProductPropertyValueEntity>().Where(ppv => ppv.ChannelValueId == product.PRO_COLOR_SID)
                                    .Join(db.Set<ProductPropertyEntity>()
                                            .Join(db.Set<ProductMapEntity>().Where(pm => pm.ChannelPId == product.PRODUCT_SID), o => o.ProductId, i => i.ProductId, (o, i) => o)
                                     ,o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                var sizeEntity = db.Set<ProductPropertyValueEntity>().Where(ppv => ppv.ChannelValueId == product.PRO_STAN_SID)
                                    .Join(db.Set<ProductPropertyEntity>()
                                            .Join(db.Set<ProductMapEntity>().Where(pm => pm.ChannelPId == product.PRODUCT_SID)
                                                   , o => o.ProductId, i => i.ProductId, (o, i) => o),
                                            o => o.PropertyId, i => i.Id, (o, i) => o).FirstOrDefault();
                if (colorEntity == null || sizeEntity == null)
                    shouldSyncProduct = true;
                
                if (shouldSyncProduct)
                   return ProductPropertySyncJob.SyncOne(product.PRODUCT_SID, product.PRO_STAN_SID ?? 0, product.PRO_STAN_NAME, product.PRO_COLOR_SID ?? 0, product.PRO_COLOR);
            }
            return true;
        }