Exemple #1
0
        /// <summary>
        /// 删除订单记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public async Task <bool> RemoveOrderRecord(int orderId)
        {
            bool result = true;

            var range = new SortedSetScoreRange();

            range.Rang((decimal)orderId, orderId);
            var history = await orderHistory.GetRangeByScoreAsync(range);

            if (history.Success && history.Value != null && history.Value.Any())
            {
                var dataList = history.Value.First().Split('/');
                if (dataList.Length == 5)
                {
                    var userId   = Guid.Parse(dataList[1]);
                    var deviceId = dataList[2];
                    var userTel  = dataList[3];
                    var dateTime = new DateTime(long.Parse(dataList[4]));

                    result = await DecreaseUserPurchaseCount(userId, deviceId, userTel);

                    if (dateTime >= _round.StartTime && dateTime < _round.EndTime)
                    {
                        result = result && await DecreaseActivityPurchaseCount();
                    }

                    Dictionary <string, string> data = new Dictionary <string, string>();
                    data["type"]    = "cancel";
                    data["orderId"] = orderId.ToString();
                    TuhuNotification.SendNotification("notification.baoyangfixedprice.cancelorder", data);
                }
            }

            return(result);
        }
Exemple #2
0
        private bool RefershSekillCache(Guid aid)
        {
            using (var client = new CacheClient())
            {
                var cacheresult = client.RefreshRedisCachePrefixForCommon(new RefreshCachePrefixRequest()
                {
                    Prefix     = "SecondKillPrefix",
                    ClientName = "FlashSale",
                    Expiration = TimeSpan.FromDays(1)
                });
                cacheresult.ThrowIfException(true);
            }
            var cache = QiangGouManager.ReflashQiangGouCache(aid, false, 1);

            if (cache == false)
            {
                return(false);
            }
            var pids = SeckillManager.SelectActivityProductPids(aid);

            Thread.Sleep(50);
            TuhuNotification.SendNotification("notification.productModify.ProductCommonTag", new
            {
                type = "RebuildCache",
                pids,
                tag = ProductCommonTag.Seckilling
            });
            return(true);
        }
Exemple #3
0
        private static void DoJob()
        {
            const int step  = 10000;
            var       start = 0;
            var       count = DalTask.GetWXBindUserCount();

            while (start < count)
            {
                var sw = new Stopwatch();
                sw.Start();
                var info = DalTask.GetWXBindUserList(start, step);
                start += step;
                if (info.Any())
                {
                    foreach (var item in info)
                    {
                        TuhuNotification.SendNotification("notification.TaskActionQueue", new Dictionary <string, string>
                        {
                            ["UserId"]     = item.ToString("D"),
                            ["ActionName"] = "4BindWX"
                        });
                        Thread.Sleep(100);
                    }
                }
                sw.Stop();
                Logger.Info($"会员任务-->绑定微信异常数据补偿Job-->第{start / step + 1}批,用时{sw.ElapsedMilliseconds}毫秒,共{count / step + 1}批");
            }
        }
Exemple #4
0
        public static int UpdatePromotionTaskStatus(int id, PromotionConsts.PromotionTaskStatusEnum taskStatus,
                                                    string operateBy)
        {
            int result = DalPromotionJob.UpdatePromotionTaskStatus(id, taskStatus, operateBy);

            if (result > 0)
            {
                var promotionTask = DalPromotionJob.GetPromotionTaskById(id);
                if (promotionTask == null)
                {
                    return(0);
                }
                if (promotionTask.IsImmediately == 1) //需要立即执行
                {
                    if (taskStatus == PromotionConsts.PromotionTaskStatusEnum.Executed)
                    {
                        TuhuNotification.SendNotification("ExecutePromotionTask.setting", new
                        {
                            PromotionTaskId = id
                        }, 10000);
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// 刷新改装产品信息到ES
        /// </summary>
        /// <param name="context"></param>
        public virtual void Execute(IJobExecutionContext context)
        {
            Logger.Info("启动任务");

            TuhuNotification.SendNotification("ProductModify", new { type = "RebuildGaiZhuangIndex" });

            Logger.Info("结束任务");
        }
Exemple #6
0
        /// <summary>
        /// 查询产品信息
        /// </summary>
        /// <param name="context"></param>
        public virtual void Execute(IJobExecutionContext context)
        {
            Logger.Info("启动任务");

            //TuhuNotification.SendNotification("ProductModify", new { type = "RebuildIndex" });//老的es
            //TuhuNotification.SendNotification("ProductModify", new { type = "RebuildIndexNew" }, 1000 * 60 * 10);//新的es
            TuhuNotification.SendNotification("notification.productmatch.rebuild", new { type = "RebuildIndex" }, 1000 * 60 * 20);//标签es

            Logger.Info("结束任务");
        }
Exemple #7
0
 // 拼团订单完成
 public JsonResult FinishPTOrder(int orderId, int type = 0)
 {
     if (env == "dev" && (type == 1 || type == 0))
     {
         TuhuNotification.SendNotification("notification.GroupBuyingOrderStatusQueue", new Dictionary <string, object>
         {
             ["OrderId"] = orderId,
             ["Operate"] = type == 0 ? "Paid" : "Canceled"
         });
         return(Json("消息已推送", JsonRequestBehavior.AllowGet));
     }
     return(Json("该工具只能在线下使用", JsonRequestBehavior.AllowGet));
 }
Exemple #8
0
        private void DoJob()
        {
            var data = DalGroupBuying.GetGroupInfo();

            foreach (var item in data)
            {
                TuhuNotification.SendNotification("notification.GroupBuyingCreateCouponQueue", new Dictionary <string, object>
                {
                    ["GroupId"]        = item.Item1,
                    ["ProductGroupId"] = item.Item2
                });
            }
        }
        public void Execute(IJobExecutionContext context)
        {
            Logger.Info($"开始刷新Suggest");
            var client      = new ProductSearchClient();
            var suggestList = ProductCacheDal.SelectSuggestWord(brash);

            foreach (var oneList in suggestList)
            {
                var response = client.SearchKeywordsResultNumber(oneList.Select(_ => _.Keyword).Distinct().ToList());
                if (!response.Success)
                {
                    client   = new ProductSearchClient();
                    response = client.SearchKeywordsResultNumber(oneList.Select(_ => _.Keyword).ToList()); if (response.Success)
                    {
                        if (!response.Success)
                        {
                            Logger.Error($"服务调用失败");
                            return;
                        }
                    }
                }

                if (response.Result == null)
                {
                    Logger.Warn($"服务返回null;{response.ErrorMessage}");
                    continue;
                }

                var upUnActive = ProductCacheDal.UpdateSuggestActive(
                    response.Result.Where(_ => _.Value == 0).Select(_ => _.Key).ToList()
                    , false);

                var upActive = ProductCacheDal.UpdateSuggestActive(
                    response.Result.Where(_ => _.Value > 0).Select(_ => _.Key).ToList()
                    , true);

                if (!upUnActive)
                {
                    Logger.Warn($"数据库更新失败upUnActive;");
                    continue;
                }
                if (!upActive)
                {
                    Logger.Warn($"数据库更新失败upActive;");
                    continue;
                }
            }
            Logger.Info($"刷新Suggest完成;通知刷新 RebuildSuggest");
            TuhuNotification.SendNotification("ProductModify", new { type = "RebuildSuggest" });
        }
        public ActionResult Save(SE_GiftManageConfigModel model)
        {
            model.ActivityType = 2;
            var dataSource = model;

            if (model.Id <= 0)
            {
                dataSource.Creater    = User.Identity.Name;
                dataSource.CreateTime = DateTime.Now;
                DiscountManageConfigManage.Insert(dataSource, new SE_DictionaryConfigModel
                {
                    ParentId   = dataSource.Id,
                    Key        = "SE_GiftManageConfig",
                    Extend1    = _CreateLogs != null ? JsonConvert.SerializeObject(_CreateLogs) : "",
                    Extend2    = dataSource != null ? JsonConvert.SerializeObject(dataSource) : "",
                    Extend3    = dataSource.Mender,
                    Extend4    = "新增",
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                });
                //Logs(dataSource, "新增");
            }
            else
            {
                dataSource.Mender     = User.Identity.Name;
                dataSource.UpdateTime = DateTime.Now;
                if (DiscountManageConfigManage.Update(dataSource))
                {
                    Logs(dataSource, "更新");
                }
            }
            RefreshCache();
            if (dataSource.P_PID != null)
            {
                var pidModel = JsonConvert.DeserializeObject <List <PidModel> >(dataSource.P_PID);
                var pids     = pidModel.Select(r => r.Pid).ToList();
                if (pids.Any())
                {
                    Thread.Sleep(50);
                    TuhuNotification.SendNotification("notification.productModify.ProductCommonTag", new
                    {
                        type = "RebuildCache",
                        pids,
                        tag = ProductCommonTag.Discount
                    });
                }
            }
            return(RedirectToAction("Index"));
        }
Exemple #11
0
 private static bool SendCleanProductCacheMsg(Dictionary <string, object> PIDS)
 {
     if (PIDS != null && PIDS.Any())
     {
         try
         {
             TuhuNotification.SendNotification("ProductModify", PIDS, 5000);
         }
         catch (Exception ex)
         {
             DalCouponPriceLogger.Error($"清除产品缓存失败:{ex}");
         }
     }
     return(true);
 }
        public void Execute(IJobExecutionContext context)
        {
            using (var cacheClient = new CacheClient())
            {
                //刷新轮胎适配redis缓存
                var refreshTireAsync = cacheClient.RefreshTireAdpterCache(null, 1);
                if (!refreshTireAsync.Success)
                {
                    Logger?.Warn($"RefreshTireAdpterCache刷新失败:{refreshTireAsync.ErrorMessage}", refreshTireAsync.Exception);
                }
            }
            //获取所有tid
            var allTids = ProductCacheDal.SelectAllTids();

            using (var cacheClient = new CacheClient())
            {
                //清除缓存
                var baoyangAdapterTire = cacheClient.RefreshBaoYangVehicleAdpterCache(new List <int>()
                {
                }, true);

                //分批次刷新保养适配redis缓存
                allTids.Split(100).ForEach(p => {
                    var resultOne = cacheClient.RefreshBaoYangVehicleAdpterCache(p.ToList(), false);
                    if (!resultOne.Success)
                    {
                        using (var cacheClient2 = new CacheClient())
                        {
                            resultOne = cacheClient2.RefreshBaoYangVehicleAdpterCache(p.ToList(), false);
                            if (!resultOne.Success)
                            {
                                Logger?.Warn($"RefreshBaoYangVehicleAdpterCache刷新失败", resultOne.Exception);
                            }
                        }
                    }
                });
            }
            //发送刷新通知
            Logger.Info($"notification.productmatch.modify.RebuildAdpter=>{DateTime.Now}");
            TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildAdpter" });

            //TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "UpdateAdpter", pids=new string[] { } });
        }
Exemple #13
0
        /// <summary>
        /// 添加订单记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="deviceId"></param>
        /// <param name="userTel"></param>
        /// <returns></returns>
        public async Task <bool> AddOrderRecord(int orderId, Guid userId, string deviceId, string userTel)
        {
            var addResult = await orderHistory.AddAsync($"{orderId}/{userId}/{deviceId}/{userTel}/{DateTime.Now.Ticks}", orderId);

            if (!addResult.Success || !addResult.Value)
            {
                Thread.Sleep(50);
                addResult = await orderHistory.AddAsync($"{orderId}/{userId}/{deviceId}/{userTel}/{DateTime.Now.Ticks}", orderId);
            }

            Dictionary <string, string> data = new Dictionary <string, string>();

            data["type"]       = "create";
            data["activityId"] = _activityId.ToString();
            data["userId"]     = userId.ToString();
            data["orderId"]    = orderId.ToString();
            data["deviceId"]   = deviceId;
            data["userTel"]    = userTel;
            TuhuNotification.SendNotification("notification.baoyangfixedprice.createorder", data);

            return(addResult.Success && addResult.Value);
        }
        private void DoJob()
        {
            var count = DalTask.GetAuthenticationUserCount();

            if (count == 0)
            {
                Logger.Warn("查询车型认证任务初始化用户数量为0");
                return;
            }
            var step  = 10000;
            var start = 0;

            Logger.Info($"查询车型认证任务初始化数据为{count}条,每批{step}条,共{count / step + 1}批");
            var watcher = new Stopwatch();

            while (start < count)
            {
                watcher.Start();
                var data = DalTask.GetAuthenticationUserList(start, step);
                if (data.Any())
                {
                    foreach (var item in data)
                    {
                        TuhuNotification.SendNotification("notification.TaskActionQueue", new Dictionary <string, string>
                        {
                            ["UserId"]     = item.ToString("D"),
                            ["ActionName"] = "7Authentication"
                        });
                        Thread.Sleep(100);
                    }
                }
                watcher.Stop();
                Logger.Info($"车型认证任务初始化,第{start / step + 1}批数据,用时{watcher.ElapsedMilliseconds}毫秒");
                watcher.Reset();
                start += step;
            }
            watcher.Stop();
        }
Exemple #15
0
        public void Execute(IJobExecutionContext context)
        {
            var curDateTime = DateTime.Now;

            Logger.Info($"发送产品标签更新通知:{curDateTime}");
            TuhuNotification.SendNotification("notification.productModify.ProductCommonTag", new
            {
                type     = "RefreshInterval",
                timespan = curDateTime
            });


            if (curDateTime.Hour == 8 && curDateTime.Minute == 20) //8点20分
            {
                Logger.Info($"notification.productmatch.modify.RebuildActivity=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildActivity" });
            }
            if (curDateTime.Hour == 16 && curDateTime.Minute == 30) //16点30分
            {
                Logger.Info($"notification.productmatch.modify.RebuildActivity=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildActivity" });
            }
            if (curDateTime.Hour >= 4 && curDateTime.Hour <= 23 && curDateTime.Minute == 13) //4点到23点 每隔1小时触发一次
            {
                Logger.Info($"notification.productmatch.modify.RebuildPerHourEsCache=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildPerHourEsCache" });
            }
            if (curDateTime.Hour == 2 && curDateTime.Minute == 16) //2点16分
            {
                Logger.Info($"ProductNodeCntRefreshJob刷新类目下的产品数量=>{curDateTime}");
                new ProductNodeCntRefreshJob().Execute(null);
            }
            if (curDateTime.Hour == 7 && curDateTime.Minute == 16) //7点16分
            {
                Logger.Info($"notification.ProductModify.ProductCacheModify.ProductLimit=>{curDateTime}");
                TuhuNotification.SendNotification("notification.ProductModify.ProductCacheModify", new { type = "ProductLimit" });
            }
        }
Exemple #16
0
        /// <summary>
        /// 调用MQ延迟推送
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task <OperationResult <bool> > CarFriendsGroupMqDelayPush(GetCarFriendsGroupPushInfoRequest request)
        {
            await Task.Yield();

            if (request.InfoType == 0 && request.PKID == 0)
            {
                return(OperationResult.FromError <bool>("-31", string.Format(Resource.ParameterError_NotZero, "PKID")));
            }
            if (string.IsNullOrWhiteSpace(request.OpenId))
            {
                return(OperationResult.FromError <bool>("-31", string.Format(Resource.ParameterError_NotNull, "OpenId")));
            }
            if ((request.InfoType != 0 && request.InfoType != 1) || request.UserId == Guid.Empty)
            {
                return(OperationResult.FromError <bool>("-31", Resource.ParameterError));
            }
            try
            {
                var data = new
                {
                    PKID            = request.PKID,
                    InfoType        = request.InfoType,
                    UserId          = request.UserId,
                    OpenId          = request.OpenId,
                    RandomNumberKey = Guid.NewGuid()
                };

                TuhuNotification.SendNotification("notification.CarFriendsGroupPushInfoQueue", data, 3000);
                TuhuNotification.SendNotification("notification.CarFriendsGroupPushInfoQueue", data, 10000);
                return(OperationResult.FromResult(true));
            }
            catch (Exception e)
            {
                Logger.Error($"车友群推送调用MQ失败 -> {JsonConvert.SerializeObject(request)}", e);
                throw;
            }
        }
Exemple #17
0
        public void Execute(IJobExecutionContext context)
        {
            var curDateTime = DateTime.Now;

            Logger.Info($"发送产品标签更新通知:{curDateTime}");
            TuhuNotification.SendNotification("notification.productModify.ProductCommonTag", new
            {
                type     = "RefreshInterval",
                timespan = curDateTime
            });


            if (curDateTime.Hour == 8 && curDateTime.Minute == 20) //8点20分
            {
                Logger.Info($"notification.productmatch.modify.RebuildActivity=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildActivity" });
            }
            if (curDateTime.Hour == 16 && curDateTime.Minute == 30) //16点30分
            {
                Logger.Info($"notification.productmatch.modify.RebuildActivity=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildActivity" });
            }
            if (curDateTime.Hour >= 4 && curDateTime.Hour <= 23 && curDateTime.Minute == 13) //4点到23点 每隔1小时触发一次
            {
                Logger.Info($"notification.productmatch.modify.RebuildPerHourEsCache=>{curDateTime}");
                TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildPerHourEsCache" });
            }
            if (curDateTime.Hour == 2 && curDateTime.Minute == 16) //2点16分
            {
                Logger.Info($"ProductNodeCntRefreshJob刷新类目下的产品数量=>{curDateTime}");
                new ProductNodeCntRefreshJob().Execute(null);
            }
            if (curDateTime.Hour == 7 && curDateTime.Minute == 16) //7点16分
            {
                Logger.Info($"notification.ProductModify.ProductCacheModify.ProductLimit=>{curDateTime}");
                TuhuNotification.SendNotification("notification.ProductModify.ProductCacheModify", new { type = "ProductLimit" });
            }
            if (curDateTime.Minute % 10 == 0) //每十分钟刷新一次
            {
                #region 刷新所有缓存
                Logger.Info($"开始刷新所有活动缓存");
                var sw = new Stopwatch();
                sw.Start();
                try
                {
                    using (var client = new CacheClient())
                    {
                        var result = client.RefreshProductSaleActivityCache();
                        if (!result.Success)
                        {
                            Logger.Error("刷新所有活动失败RefreshProductSaleActivityCache");
                        }
                    }

                    sw.Stop();
                }
                catch (Exception e)
                {
                    Logger.Error("调用刷新所有活动失败RefreshProductSaleActivityCache" + e.InnerException + e.Message);
                }

                Logger.Info($"刷新所有活动缓存耗时{sw.ElapsedMilliseconds}");
                #endregion
                #region  pid刷新缓存
                sw.Restart();
                Logger.Info($"开始按pid刷新所有活动缓存");
                try
                {
                    var datas = ProductCacheDal.SelectAllSaleActivity();
                    var pids  = datas.Select(r => r.PID).ToList();
                    using (var client = new CacheClient())
                    {
                        var result = client.RefreshProductSaleActivityCacheByPids(pids);
                        if (!result.Success)
                        {
                            Logger.Error("按pid刷新所有活动失败RefreshProductSaleActivityCache");
                        }
                    }

                    sw.Stop();
                }
                catch (Exception e)
                {
                    Logger.Error("调用按pid刷新所有活动失败RefreshProductSaleActivityCache" + e.InnerException + e.Message);
                }

                Logger.Info($"按pid刷新所有活动缓存耗时{sw.ElapsedMilliseconds}");
                #endregion
            }
        }
        private static void DoJob(bool isDay, string startTime, string endTime)
        {
            var watcher = new Stopwatch();

            watcher.Start();

            if ((string.IsNullOrEmpty(startTime) || string.IsNullOrEmpty(endTime)) && isDay)
            {
                Logger.Warn("配置时间读取失败");
                return;
            }

            var start = 21000;

            if (isDay)
            {
                startTime = (DateTime.Now - TimeSpan.FromDays(3)).ToLocalTime().ToString("yyyy-MM-dd");
                endTime   = DateTime.Now.ToLocalTime().ToString("yyyy-MM-dd");
                start     = 0;
            }

            var step         = 1000;
            var commentCount = DalShopCommentSync.GetShopCommentCount(startTime, endTime);

            if (commentCount <= 0)
            {
                Logger.Warn("门店评论审核数据同步,待同步数据==>0条");
                return;
            }

            Logger.Info($"门店评论审核数据同步,待同步数据==>{commentCount}条,共{(commentCount / step) + 1}批");
            var sw = new Stopwatch();

            while (start < commentCount)
            {
                try
                {
                    sw.Start();
                    var commentIds = DalShopCommentSync.GetShopCommentId(startTime, endTime, start, step);
                    start += step;
                    foreach (var commentId in commentIds)
                    {
                        TuhuNotification.SendNotification("ShopCommentApproved", new Dictionary <string, object>
                        {
                            ["type"] = "shop",
                            ["id"]   = commentId
                        });
                        Thread.Sleep(200);
                    }

                    sw.Stop();
                    Logger.Info(
                        $"门店评论审核数据同步,第{(start / step) + 1}批数据,共{(commentCount / step) + 1}批数据,用时{sw.ElapsedMilliseconds}毫秒");
                    sw.Reset();
                }
                catch (Exception ex)
                {
                    Logger.Warn($"第{start / step + 1}批数据异常/{ex.Message}/{ex.InnerException}/{ex.Source}");
                    Thread.Sleep(20000);
                    //start -= step;
                }
            }

            watcher.Stop();
            Logger.Info($"门店评论审核数据同步结束,从{startTime}到{endTime},共{commentCount}条数据,用时{watcher.ElapsedMilliseconds}毫秒");
        }
Exemple #19
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                List <int> shopIds;
                using (var cmd = new SqlCommand(@"SELECT S.PKID FROM Shops AS S WITH(NOLOCK)"))
                {
                    shopIds = DbHelper.ExecuteQuery(true, cmd, (dt) =>
                    {
                        return
                        (Enumerable.Select(dt.AsEnumerable(),
                                           row => !row.IsNull("PKID") ? Convert.ToInt32(row.GetValue("PKID")) : -1)
                         .Where(shopId => shopId > 0)
                         .ToList());
                    });
                }
                shopLog.Info("开始刷新门店缓存");
                if (shopIds != null && shopIds.Any())
                {
                    var shopIdArry = shopIds.ToArray();
                    var batchNum   = (shopIdArry.Length + 127) / 128;
                    for (var index = 0; index < batchNum; index++)
                    {
                        var batchArry = shopIdArry.Skip(index * 128).Take(128).ToArray();
                        foreach (var shopId in batchArry)
                        {
                            try
                            {
                                TuhuNotification.SendNotification("ShopChange", new Dictionary <string, object>()
                                {
                                    ["ShopId"] = shopId
                                });
                            }
                            catch (Exception ex)
                            {
                                shopLog.Info($"向刷门店mq发消息失败,ShopId:{shopId},ErrorMsg:{ex.Message}");
                            }
                        }
                        using (var client = new ShopClient())
                        {
                            foreach (var shopId in batchArry)
                            {
                                client.SendBeautyShopChangeQueue(shopId, 0);
                            }
                        }
                        shopLog.Info("成功向MQ发送第" + index + "批shopId");
                        Thread.Sleep(5000);
                    }
                }


                List <int> regionIds = null;
                using (var cmd = new SqlCommand(@"
                     SELECT R1.PKID FROM Gungnir..tbl_region R1 (NOLOCK) WHERE ParentID=0 OR EXISTS(SELECT 1 FROM Gungnir..tbl_region R2 (NOLOCK) WHERE R2.ParentID=R1.PKID)"))
                {
                    regionIds = DbHelper.ExecuteQuery(true, cmd, (dt) =>
                    {
                        return
                        (Enumerable.Select(dt.AsEnumerable(),
                                           row => !row.IsNull("PKID") ? Convert.ToInt32(row.GetValue("PKID")) : -1)
                         .Where(regionId => regionId > 0)
                         .ToList());
                    });
                }
                shopLog.Info("开始刷新地区门店缓存");
                if (regionIds != null && regionIds.Any())
                {
                    using (var client = new ShopClient())
                    {
                        foreach (var regionId in regionIds)
                        {
                            client.UpdateShopDetailsByRegionId(regionId);
                            shopLog.Info("成功刷新地区id为" + regionId + "门店缓存");
                            Thread.Sleep(10);
                        }
                    }
                }
                shopLog.Info("地区门店缓存刷新成功");
            }
            catch (Exception ex)
            {
                shopLog.Error("刷门店缓存异常" + ex);
            }
        }
        private async Task <OperationResult <bool> > CreatePackageInfo(BigBrandRewardPoolModel page)
        {
            List <BigBrandRealLogModel> realList = new List <BigBrandRealLogModel>();
            Guid tip = Guid.NewGuid();

            if (page.PartItem == null)
            {
                throw new Exception("奖励礼包为空");
            }

            foreach (var info in page.PartItem)
            {
                if (page.RewardType == 1)
                {
                    //发放优惠券
                    if (this.UserId != Guid.Empty)
                    {
                        using (var client = new Tuhu.Service.Member.PromotionClient())
                        {
                            var result = await client.CreatePromotionNewAsync(new CreatePromotionModel()
                            {
                                Author         = this.UserId.ToString(),
                                GetRuleGUID    = Guid.Parse(info.CouponGuid),
                                UserID         = this.UserId,
                                Channel        = this.Channel + "大翻盘",
                                DeviceID       = this.DeviceId,
                                Operation      = "大翻盘抽奖",
                                Referer        = this.Refer,
                                IssueChannle   = "幸运大翻牌",
                                IssueChannleId = this.entity.HashKeyValue,
                                Issuer         = string.IsNullOrWhiteSpace(this.entity.UpdateUserName) == true ? this.entity.CreateUserName : this.entity.UpdateUserName
                            });

                            result.ThrowIfException(true);
                            if (result.Result.IsSuccess)
                            {
                                page.PromotionCodePKIDs += result.Result?.PromotionId.ToString() + ",";
                            }
                            else
                            {
                                return(OperationResult.FromError <bool>(result.Result.ErrorCode.ToString(), result.Result.ErrorMessage));
                            }
                        }
                    }
                    else if (!string.IsNullOrEmpty(this.UnionId))  //如果用户id为空,根据unionid发券
                    {
                        using (var client = new Tuhu.Service.Member.ThirdPartyPromotionClient())
                        {
                            var result = await client.InsertUserCardInfoAsync(new UserCardInfo()
                            {
                                Channel        = this.Channel + "大翻盘",
                                CreatedTime    = DateTime.Now,
                                DeviceID       = this.DeviceId,
                                EventTime      = DateTime.Now,
                                GetRuleId      = Guid.Parse(info.CouponGuid),
                                IssueChannle   = "幸运大翻盘",
                                UnionId        = this.UnionId,
                                OpenId         = this.OpenId,
                                IssueChannleId = this.entity.HashKeyValue,
                                Issuer         = string.IsNullOrWhiteSpace(this.entity.UpdateUserName) == true
                                    ? this.entity.CreateUserName
                                    : this.entity.UpdateUserName,
                                UpdatedTime = DateTime.Now
                            });

                            if (!result.Success)
                            {
                                return(OperationResult.FromError <bool>(result.ErrorCode.ToString(), result.ErrorMessage));
                            }
                        }
                    }
                }
                else if (page.RewardType == 2)
                {
                    //积分抽奖
                    using (var client = new Tuhu.Service.Member.UserIntegralClient())
                    {
                        ///规则guid
                        var integralRuleId = new Guid("04E70162-9588-4329-BCED-E149E22D7DCE");
                        Service.Member.Models.UserIntegralDetailModel integralDetailModel = new Service.Member.Models.UserIntegralDetailModel();
                        integralDetailModel.TransactionIntegral = info.Integral.Value;
                        integralDetailModel.TransactionChannel  = "H5";
                        integralDetailModel.Versions            = "1.0.0";
                        integralDetailModel.TransactionRemark   = "大翻盘积分抽奖";
                        integralDetailModel.IntegralRuleID      = integralRuleId;
                        var result = await client.UserIntegralChangeByUserIDAsync(this.UserId, integralDetailModel, null, 0);

                        result.ThrowIfException(true);
                    }
                }
                else if (page.RewardType == 4)
                {
                    this.RealTip = tip;
                    BigBrandRealLogModel real = new BigBrandRealLogModel()
                    {
                        CreateDateTime   = DateTime.Now,
                        FKBigBrandID     = this.entity.PKID,
                        FKBigBrandPoolID = page.PKID,
                        Prize            = info.RealProductName,
                        Tip                = tip,
                        UserId             = this.UserId,
                        LastUpdateDateTime = DateTime.Now
                    };
                    realList.Add(real);
                }
                else if (page.RewardType == 5)//抽中的是微信红包,给用户发微信红包
                {
                    //using (var client = new Pay.PayClient())
                    //{
                    //    var sendResponse = await client.Wx_SendRedBagAsync(new Pay.Models.WxSendRedBagRequest()
                    //    {
                    //        OpenId = this.OpenId,
                    //        Channel = this.Channel + "大翻盘",
                    //        ActName = "大翻盘抽奖",
                    //        Remark = this.entity.HashKeyValue,
                    //        Wishing = "新年大吉",
                    //        Money = (info.WxRedBagAmount ?? 0) * 100
                    //    });
                    //    sendResponse.ThrowIfException(true);
                    //}
                    //发红包改为发消息队列,从消息队列里慢慢发
                    TuhuNotification.SendNotification("notification.WxSendRedBag", new Pay.Models.WxSendRedBagRequest()
                    {
                        OpenId  = this.OpenId,
                        Channel = this.Channel + "大翻盘",
                        ActName = "大翻盘抽奖",
                        Remark  = this.entity.HashKeyValue,
                        Wishing = "新年大吉",
                        Money   = (info.WxRedBagAmount ?? 0) * 100
                    });
                }
                else
                {
                    //空奖
                }
            }

            if (page.RewardType == 4)
            {
                //实物奖励
                DalBigBrand.AddBigBrandRealLog(realList);
            }
            if (this.entity.BigBrandType == 1)
            {
                this.TimeCount -= 1;
            }
            if (this.entity.BigBrandType == 3)
            {
                this.TimeCount -= 1;
                await ActivityManager.UpdateLuckyWheelUserlotteryCountAsync(this.UserId, Guid.Empty,
                                                                            this.entity.HashKeyValue);
            }
            return(OperationResult.FromResult(true));
        }
Exemple #21
0
        public static async Task <int> SubmitZeroActivityApplicationAsync(ZeroActivityRequest requestModel)
        {
            try
            {
                var activityDetail = await FetchZeroActivityDetailAsync(requestModel.Period);

                if (activityDetail == null)
                {
                    return(-2);
                }
                else if (activityDetail.StatusOfActivity != 1)
                {
                    return(-3);
                }
                else if (activityDetail.PID == null || activityDetail.ProductName == null)
                {
                    return(-4);
                }
                if (await DalZeroActivity.HasZeroActivityApplicationSubmittedAsync(requestModel.UserId, requestModel.Period))
                {
                    return(-1);
                }
                string userMobile = "";

                using (var uClient = new UserAccountClient())
                {
                    var result = await uClient.GetUserByIdAsync(requestModel.UserId);

                    if (result.Success && !string.IsNullOrWhiteSpace(result.Result?.MobileNumber) && result.Result.MobileNumber.Length <= 30)
                    {
                        userMobile = result.Result.MobileNumber;
                    }
                }
                var count = await DalZeroActivity.SubmitZeroActivityApplicationAsync(requestModel, activityDetail, userMobile);

                if (count > 0)
                {
                    var actionQueueDic = new Dictionary <string, string>();
                    actionQueueDic["UserId"]     = requestModel.UserId.ToString("B");
                    actionQueueDic["ActionName"] = "12PublicTest";
                    TuhuNotification.SendNotification("notification.TaskActionQueue", actionQueueDic);
                    using (var client = CacheHelper.CreateCacheClient(DefaultClientName))
                    {
                        var existenceResult = await client.ExistsAsync(GlobalConstant.MyZeroApplyApplications + requestModel.UserId.ToString("B") + "/0/");

                        if (existenceResult.Success)
                        {
                            var removeResult = await client.RemoveAsync(GlobalConstant.MyZeroApplyApplications + requestModel.UserId.ToString("B") + "/0/");

                            if (!removeResult.Success)
                            {
                                Logger.Warn($"删除用户众测申请列表(申请中)缓存redis失败MyZeroApplyApplications:{GlobalConstant.MyZeroApplyApplications + requestModel.UserId.ToString("B") + "/0/"};Error:{removeResult.Message}", removeResult.Exception);
                            }
                        }
                    }
                }
                return(count);
            }
            catch (Exception ex)
            {
                Logger.ErrorException("SubmitZeroActivityApplication逻辑进行中出现异常", ex);
                return(0);
            }
        }
        /// <summary>
        /// 编辑团购信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public Tuple <bool, string> UpsertGroupBuyingConfig(GroupBuyingProductGroupConfigEntity data)
        {
            var result = false;
            var msg    = "操作失败";
            GroupBuyingProductGroupConfigEntity oldData = null;

            try
            {
                dbScopeManager.CreateTransaction(conn =>
                {
                    if (string.IsNullOrWhiteSpace(data.ProductGroupId))
                    {
                        data.ProductGroupId = $"PT{DateTime.Now.GetHashCode()}".Substring(0, 10);
                        if (DalGroupBuyingProductGroupConfig.IsExistProductGroupId(conn, data.ProductGroupId) > 0)
                        {
                            data.ProductGroupId = $"PT{DateTime.Now.GetHashCode()}".Substring(0, 10);
                        }
                        DalGroupBuyingProductGroupConfig.InsertGroupBuyingGroupConfig(conn, data);
                        foreach (var item in data.GroupProductDetails)
                        {
                            item.ProductGroupId = data.ProductGroupId;
                            item.Creator        = data.Creator;
                            DalGroupBuyingProductGroupConfig.InsertGroupBuyingProductConfig(conn, item);
                        }
                    }
                    else
                    {
                        oldData = DalGroupBuyingProductGroupConfig.GetGroupBuyingV2ConfigByGroupId(conn, data.ProductGroupId);
                        if (oldData != null)
                        {
                            oldData.GroupProductDetails = DalGroupBuyingProductGroupConfig.GetGroupBuyingV2ProductConfigByGroupId(conn, new List <string> {
                                data.ProductGroupId
                            });
                        }

                        DalGroupBuyingProductGroupConfig.UpdateGroupBuyingGroupConfig(conn, data);
                        DalGroupBuyingProductGroupConfig.DeleteGroupBuyingProductConfig(conn, data.ProductGroupId);
                        foreach (var item in data.GroupProductDetails)
                        {
                            item.ProductGroupId = data.ProductGroupId;
                            item.Creator        = data.Creator;
                            DalGroupBuyingProductGroupConfig.InsertGroupBuyingProductConfig(conn, item);
                        }
                    }
                    result = true;
                });
            }
            catch (Exception ex)
            {
                msg = "系统异常";
                logger.Error(ex);
            }
            if (result)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    foreach (var item in data.GroupProductDetails)
                    {
                        TuhuNotification.SendNotification("#.PinTuanProductStatusSyncQueue.#",
                                                          new Dictionary <string, object>
                        {
                            ["PId"]            = item.PID,
                            ["ProductGroupId"] = data.ProductGroupId
                        }, 3000);
                    }
                    InsertLog(data.ProductGroupId, "GroupBuyingProductConfig", "UpsertGroupBuyingConfig", result ? "操作成功" : msg, JsonConvert.SerializeObject(oldData), JsonConvert.SerializeObject(data), data.Creator);
                    ActivityService.RefrestPTCache(data.ProductGroupId);
                });
            }
            return(Tuple.Create(result, msg));
        }
Exemple #23
0
        public static async Task <CreateOrderResult> FlashSaleCreateOrder(Order.Request.CreateOrderRequest request)
        {
            var flashrequest = new FlashSaleOrderRequest()
            {
                Products = new List <OrderItems>()
            };
            var pintuanFlag           = false;
            var pintuanProductGroupId = "";
            var pintuanPid            = "";
            var pintuanCount          = 0;

            try
            {
                if (request.Items != null && request.Items.Any())
                {
                    foreach (var item in request.Items)
                    {
                        if (item.ActivityId.HasValue)
                        {
                            var activityTypeModel = new ActivityTypeModel();
                            // 增加拼团校验逻辑
                            if (item.ActivityId != null &&
                                await GroupBuyingManager.CheckProductGroupId(item.ActivityId.Value))
                            {
                                activityTypeModel =
                                    new ActivityTypeModel {
                                    ActivityId = item.ActivityId.Value, Type = 7
                                };
                            }
                            else
                            {
                                // 不是拼团ActivityId
                                activityTypeModel = ActivityManager.SelectActivityTypeByActivityIds(new List <Guid>
                                {
                                    item.ActivityId.Value
                                }).FirstOrDefault();
                            }

                            if (activityTypeModel != null)
                            {
                                var temp = flashrequest.Products.ToList();
                                temp.Add(
                                    new OrderItems
                                {
                                    ActivityId = item.ActivityId,
                                    Num        = item.Num,
                                    PID        = item.Pid,
                                    Type       = activityTypeModel.Type
                                });
                                flashrequest.Products = temp;
                                if (activityTypeModel.Type == 1)
                                {
                                    //用来控制下单是否走老逻辑
                                    item.IsVerifyActivity = false;
                                }

                                if (activityTypeModel.Type == 5)
                                {
                                    item.IsVerifyActivity = false;
                                }

                                //砍价
                                if (activityTypeModel.Type == 9)
                                {
                                    item.IsVerifyActivity = false;
                                }

                                //拼团
                                if (activityTypeModel.Type == 7)
                                {
                                    request.Status        = "0NewPingTuan";
                                    item.IsVerifyActivity = false;
                                    var buyLimitInfo =
                                        await GroupBuyingManager.GetBuyLimitInfo(item.ActivityId.Value, item.Pid,
                                                                                 request.Customer.UserId);

                                    if (string.IsNullOrWhiteSpace(buyLimitInfo?.PID))
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "未找到该拼团产品!"
                                        });
                                    }

                                    if (buyLimitInfo.BuyLimitCount > 0 &&
                                        buyLimitInfo.BuyLimitCount <= buyLimitInfo.CurrentOrderCount)
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "已达到限购单数!"
                                        });
                                    }

                                    if (item.Num > buyLimitInfo.UpperLimitPerOrder && buyLimitInfo.UpperLimitPerOrder != 0)
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "购买数量不符合要求!"
                                        });
                                    }
                                    using (var client = new PinTuanClient())
                                    {
                                        var result = await client.IncreaseSoldCountAsync(buyLimitInfo.ProductGroupId, buyLimitInfo.PID, item.Num);

                                        if (!(result.Success && result.Result.Code == 1))
                                        {
                                            return(new CreateOrderResult
                                            {
                                                ErrorCode = -1000,
                                                ErrorMessage = result.Result?.Info ?? "出现异常"
                                            });
                                        }
                                        pintuanFlag           = true;
                                        pintuanPid            = buyLimitInfo.PID;
                                        pintuanProductGroupId = buyLimitInfo.ProductGroupId;
                                        pintuanCount          = item.Num;
                                    }
                                }
                            }
                        }
                    }
                }

                flashrequest.DeviceId = request.DeviceID;
                flashrequest.UseTel   = request.Customer.UserTel;
                flashrequest.UserId   = request.Customer.UserId;

                ICounter counter = null;

                #region 限时抢购校验

                var fsRequest       = new FlashSaleOrderRequest();
                var isCheckFlash    = false;
                var flashSaleResult = new List <CheckFlashSaleResponseModel>();
                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var fsItems      = flashrequest.Products.Where(r => r.Type == 1);
                    var orderItemses = fsItems as OrderItems[] ?? fsItems.ToArray();
                    if (orderItemses.Any())
                    {
                        isCheckFlash       = true;
                        fsRequest.DeviceId = flashrequest.DeviceId;
                        fsRequest.UseTel   = flashrequest.UseTel;
                        fsRequest.UserId   = flashrequest.UserId;
                        fsRequest.Products = orderItemses;

                        flashSaleResult = await ActivityValidator.CheckFlashSaleAsync(fsRequest);

                        if (flashSaleResult.Any(r => r.Code != Model.CheckFlashSaleStatus.Succeed))
                        {
                            return(new CreateOrderResult
                            {
                                ErrorCode = (int)flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault(),
                                ErrorMessage = flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault().GetRemark()
                            });
                        }
                        flashrequest.Products = orderItemses.Select(r =>
                        {
                            r.AllPlaceLimitId =
                                flashSaleResult.Where(p => p.PID == r.PID)
                                .Select(_ => _.AllPlaceLimitId)
                                .FirstOrDefault();
                            return(r);
                        });
                    }
                }


                #endregion
                #region 保养校验

                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var byRequest  = flashrequest.Products.Where(r => r.Type == 5);
                    var activityId = byRequest.FirstOrDefault(o => o.ActivityId != Guid.Empty)?.ActivityId;
                    if (activityId != null)
                    {
                        List <BaoYang.Models.BaoYangVehicleFivePropertyModel> propertiesList = null;
                        if (request.Car != null && request.Car.ExtCol != null &&
                            request.Car.ExtCol.ContainsKey("Properties") &&
                            request.Car.ExtCol["Properties"] != null)
                        {
                            string         properties = request.Car.ExtCol["Properties"].ToString();
                            List <dynamic> list       = JsonConvert.DeserializeObject <List <dynamic> >(properties);
                            propertiesList = list.Select(o => new BaoYang.Models.BaoYangVehicleFivePropertyModel()
                            {
                                Property      = o.propertyKey,
                                PropertyValue = o.propertyValue
                            }).ToList();
                        }
                        ValidateOrderRequest validateRequest = new ValidateOrderRequest()
                        {
                            ActivityId = activityId.Value,
                            UserId     = flashrequest.UserId,
                            Products   =
                                request.Items.Where(
                                    o => o.ActivityId != null && o.ActivityId.HasValue && !o.Pid.StartsWith("FU-") && !o.Pid.StartsWith("TR-"))
                                .Select(o => new OrderProduct()
                            {
                                ProductId   = o.Pid,
                                Count       = o.Num,
                                ActivityId  = o.ActivityId.Value,
                                Price       = o.Price,
                                ProductType = "Product"
                            }).ToList(),
                            ShopId      = request.Delivery.InstallShopId ?? 0,
                            Channel     = request.OrderChannel,
                            InstallType = request.Delivery.InstallType,
                            Vehicle     = new BaoYang.Models.VehicleRequestModel()
                            {
                                VehicleId  = request.Car.VehicleId,
                                PaiLiang   = request.Car.PaiLiang,
                                Nian       = request.Car.Nian,
                                Tid        = request.Car.Tid,
                                Properties = propertiesList
                            },
                            RegionId = 1
                        };
                        using (var client = new BaoYangClient())
                        {
                            var baoyangResult = await client.ValidateFixedPriceActivityOrderAsync(validateRequest);

                            if (!baoyangResult.Success || !baoyangResult.Result)
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = (int)CreateOrderErrorCode.ProductValidateFailed,
                                    ErrorMessage =
                                        CreateOrderMessageDic.GetMessage(CreateOrderErrorCode.ProductValidateFailed)
                                });
                            }
                        }
                        // 验证活动状态
                        var validateResult = await ActivityValidator.ValidateBaoyang(activityId.Value);

                        if (validateResult.Item1 == Model.CreateOrderErrorCode.ActivitySatisfied)
                        {
                            // 验证限购数量
                            counter = new BaoYangCounter(activityId.Value, validateResult.Item2, validateResult.Item3,
                                                         validateResult.Item4);
                            var countResult = await counter.CanPurchaseAndIncreaseCount(flashrequest.UserId,
                                                                                        flashrequest.DeviceId, flashrequest.UseTel);

                            if (countResult.Code != Model.CreateOrderErrorCode.ActivitySatisfied)
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = (int)countResult.Code,
                                    ErrorMessage = CreateOrderMessageDic.GetMessage(countResult.Code)
                                });
                            }
                        }
                        else
                        {
                            return(new CreateOrderResult()
                            {
                                ErrorCode = (int)validateResult.Item1,
                                ErrorMessage = CreateOrderMessageDic.GetMessage(validateResult.Item1)
                            });
                        }
                    }
                }

                #endregion
                #region 分享砍价活动
                bool   bargainflag = false;
                Guid   ownerId     = new Guid();
                string pid         = "";
                var    parameters  = new List <BuyLimitDetailModel>();
                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var item = flashrequest.Products.FirstOrDefault(g => g.Type == 9);
                    if (item != null)
                    {
                        ownerId = flashrequest.UserId;
                        pid     = item.PID;
                        parameters.Add(new BuyLimitDetailModel
                        {
                            ModuleName    = "sharebargain",
                            LimitObjectId = ownerId.ToString("D"),
                            ObjectType    = LimitObjectTypeEnum.UserId.ToString(),
                            Remark        = "砍价实物商品下单"
                        });
                        if (!string.IsNullOrWhiteSpace(flashrequest.DeviceId))
                        {
                            parameters.Add(new BuyLimitDetailModel
                            {
                                ModuleName    = "sharebargain",
                                LimitObjectId = flashrequest.DeviceId,
                                ObjectType    = LimitObjectTypeEnum.DeviceId.ToString(),
                                Remark        = "砍价实物商品下单"
                            });
                        }
                        var val = await DalBargain.CheckBargainProductStatusByPID(ownerId, pid);

                        if (!val)
                        {
                            return(new CreateOrderResult()
                            {
                                ErrorCode = -1000,
                                ErrorMessage = "您当前没有资格享受该优惠!"
                            });
                        }
                        bargainflag = true;
                    }
                }
                #endregion
                try
                {
                    using (var client = new CreateOrderClient())
                    {
                        var result = await client.CreateOrderAsync(request);

                        result.ThrowIfException();
                        if (result.Success)
                        {
                            if (counter != null)
                            {
                                await counter.AddOrderRecord(result.Result.OrderId, flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                            }
                            if (bargainflag)
                            {
                                var tal = await DalBargain.BuyBargainProductAsync(ownerId, pid, result.Result.OrderId);

                                if (tal > 0)
                                {
                                    parameters.ForEach(g => { g.ModuleProductId = tal.ToString(); g.Reference = result.Result.OrderId.ToString(); });
                                    await LimitBuyManager.AddBuyLimitInfo(parameters);

                                    Logger.Info($"UserId为{ownerId}的用户享受砍价优惠,已购买pid为{pid}的商品");
                                }
                                else
                                {
                                    Logger.Error($"UserId为{ownerId}的用户享受砍价优惠,购买pid为{pid}的商品,修改购买状态时出错");
                                }
                            }
                            flashrequest.OrderId = result.Result.OrderId;
                            if (isCheckFlash)
                            {
                                Logger.Info($"下单成功订单号=>{flashrequest.OrderId}发送消息");
                                try
                                {
                                    TuhuNotification.SendNotification(".FlashSaleCreateOrder.", flashrequest);
                                }
                                catch (Exception ex)
                                {
                                    var str = "";
                                    try
                                    {
                                        str = JsonConvert.SerializeObject(flashrequest);
                                    }
                                    catch (Exception)
                                    {
                                        str = result.Result.OrderId.ToString();
                                    }

                                    Logger.Error($"request-->{str}-->mq发送失败", ex);
                                }
                            }
                            return(new CreateOrderResult
                            {
                                OrderId = result.Result.OrderId,
                                OrderNo = result.Result.OrderNo
                            });
                        }
                        else
                        {
                            // 拼团下单失败,修改虚拟库存
                            if (pintuanFlag)
                            {
                                using (var client2 = new PinTuanClient())
                                {
                                    var result2 = await client2.DecrementSoldCountAsync(pintuanProductGroupId, pintuanPid, pintuanCount);

                                    if (!(result2.Success && result2.Result.Code == 1))
                                    {
                                        Logger.Error($"拼团产品下单失败,虚拟库存修改失败-->{pintuanProductGroupId}/{pintuanPid}/{pintuanCount}");
                                    }
                                }
                            }


                            if (counter != null)
                            {
                                await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                            }
                            Logger.Info("调用下单接口失败" + result.ErrorCode + result.ErrorMessage);
                            if (isCheckFlash)
                            {
                                await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult);
                            }
                            if (result.ErrorCode == "Order_FlashSale_Error")
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = -1000,
                                    ErrorMessage = CreateOrderMessageDic.GetFlashSaleErrorMessage(result.ErrorMessage)
                                });
                            }
                            if (result.ErrorCode == "Invalid_PromotionCode")
                            {
                                return new CreateOrderResult()
                                       {
                                           ErrorCode    = -1000,
                                           ErrorMessage = "优惠券无效!"
                                       }
                            }
                            ;
                            else
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = -1000,
                                    ErrorMessage = "下单失败!"
                                });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (counter != null)
                    {
                        await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                    }
                    if (isCheckFlash)
                    {
                        await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult);
                    }
                    Logger.Error("调用下单接口失败" + ex.Message + ex.InnerException);
                    return(new CreateOrderResult()
                    {
                        ErrorCode = -1000,
                        ErrorMessage = "下单失败"
                    });
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(new CreateOrderResult()
                {
                    ErrorCode = -1000,
                    ErrorMessage = "下单失败"
                });
            }
        }
        public static async Task <CreateOrderResult> FlashSaleCreateOrder(Order.Request.CreateOrderRequest request)
        {
            var flashrequest = new FlashSaleOrderRequest()
            {
                Products = new List <OrderItems>()
            };
            var pintuanFlag           = false;
            var pintuanProductGroupId = "";
            var pintuanPid            = "";
            var pintuanCount          = 0;

            try
            {
                if (request.Items != null && request.Items.Any())
                {
                    foreach (var item in request.Items)
                    {
                        if (item.ActivityId.HasValue)
                        {
                            var activityTypeModel = new ActivityTypeModel();
                            // 增加拼团校验逻辑
                            if (item.ActivityId != null &&
                                await GroupBuyingManager.CheckProductGroupId(item.ActivityId.Value))
                            {
                                activityTypeModel =
                                    new ActivityTypeModel {
                                    ActivityId = item.ActivityId.Value, Type = 7
                                };
                            }
                            else if ((await DalSalePromotion.CheckActivityIsEffictive(item.ActivityId.Value.ToString())))///黎先攀的打折活动
                            {
                                activityTypeModel =
                                    new ActivityTypeModel {
                                    ActivityId = item.ActivityId.Value, Type = 11
                                };
                            }
                            else
                            {
                                // 不是拼团ActivityId
                                activityTypeModel = ActivityManager.SelectActivityTypeByActivityIds(new List <Guid>
                                {
                                    item.ActivityId.Value
                                }).FirstOrDefault();
                            }

                            if (activityTypeModel != null)
                            {
                                var temp = flashrequest.Products.ToList();
                                temp.Add(
                                    new OrderItems
                                {
                                    ActivityId = item.ActivityId,
                                    Num        = item.Num,
                                    PID        = item.Pid,
                                    Type       = activityTypeModel.Type,
                                    Price      = item.Price,
                                    ListPrice  = item.ListPrice
                                });
                                flashrequest.Products = temp;

                                if (activityTypeModel.Type == 1)
                                {
                                    //用来控制下单是否走老逻辑
                                    item.IsVerifyActivity = false;
                                }

                                if (activityTypeModel.Type == 5)
                                {
                                    item.IsVerifyActivity = false;
                                }

                                //砍价
                                if (activityTypeModel.Type == 9)
                                {
                                    item.IsVerifyActivity = false;
                                }
                                if (activityTypeModel.Type == 11)
                                {
                                    item.IsVerifyActivity = false;
                                }
                                //拼团
                                if (activityTypeModel.Type == 7)
                                {
                                    request.Status        = "0NewPingTuan";
                                    item.IsVerifyActivity = false;
                                    var buyLimitInfo =
                                        await GroupBuyingManager.GetBuyLimitInfo(item.ActivityId.Value, item.Pid,
                                                                                 request.Customer.UserId);

                                    if (string.IsNullOrWhiteSpace(buyLimitInfo?.PID))
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "未找到该拼团产品!"
                                        });
                                    }

                                    if (buyLimitInfo.BuyLimitCount > 0 &&
                                        buyLimitInfo.BuyLimitCount <= buyLimitInfo.CurrentOrderCount)
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "已达到限购单数!"
                                        });
                                    }

                                    if (item.Num > buyLimitInfo.UpperLimitPerOrder && buyLimitInfo.UpperLimitPerOrder != 0)
                                    {
                                        return(new CreateOrderResult
                                        {
                                            ErrorCode = -1000,
                                            ErrorMessage = "购买数量不符合要求!"
                                        });
                                    }
                                    using (var client = new PinTuanClient())
                                    {
                                        var result = await client.IncreaseSoldCountAsync(buyLimitInfo.ProductGroupId, buyLimitInfo.PID, item.Num);

                                        if (!(result.Success && result.Result.Code == 1))
                                        {
                                            return(new CreateOrderResult
                                            {
                                                ErrorCode = -1000,
                                                ErrorMessage = result.Result?.Info ?? "出现异常"
                                            });
                                        }
                                        pintuanFlag           = true;
                                        pintuanPid            = buyLimitInfo.PID;
                                        pintuanProductGroupId = buyLimitInfo.ProductGroupId;
                                        pintuanCount          = item.Num;
                                    }
                                }


                                //锦湖轮胎
                                if (item.Pid.StartsWith("TR-", StringComparison.OrdinalIgnoreCase) &&
                                    !await CheckIsPassKumhoTireFlashSale(item.ActivityId?.ToString(), request.Customer.UserId))
                                {
                                    return(new CreateOrderResult()
                                    {
                                        ErrorCode = -1000,
                                        ErrorMessage = "此价格为企业客户专享,无法生成订单"
                                    });
                                }
                            }
                        }
                    }
                }

                flashrequest.DeviceId = request.DeviceID;
                flashrequest.UseTel   = request.Customer.UserTel;
                flashrequest.UserId   = request.Customer.UserId;

                ICounter counter = null;

                #region 限时抢购校验

                var fsRequest       = new FlashSaleOrderRequest();
                var isCheckFlash    = false;
                var flashSaleResult = new List <CheckFlashSaleResponseModel>();
                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var fsItems      = flashrequest.Products.Where(r => r.Type == 1);
                    var orderItemses = fsItems as OrderItems[] ?? fsItems.ToArray();
                    if (orderItemses.Any())
                    {
                        isCheckFlash       = true;
                        fsRequest.DeviceId = flashrequest.DeviceId;
                        fsRequest.UseTel   = flashrequest.UseTel;
                        fsRequest.UserId   = flashrequest.UserId;
                        fsRequest.Products = orderItemses;

                        flashSaleResult = await ActivityValidator.CheckFlashSaleAsync(fsRequest);

                        if (flashSaleResult.Any(r => r.Code != Model.CheckFlashSaleStatus.Succeed))
                        {
                            return(new CreateOrderResult
                            {
                                ErrorCode = (int)flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault(),
                                ErrorMessage = flashSaleResult.Where(r => r.Code != Model.CheckFlashSaleStatus.Succeed).Select(c => c.Code).FirstOrDefault().GetRemark()
                            });
                        }
                        flashrequest.Products = orderItemses.Select(r =>
                        {
                            r.AllPlaceLimitId =
                                flashSaleResult.Where(p => p.PID == r.PID)
                                .Select(_ => _.AllPlaceLimitId)
                                .FirstOrDefault();
                            return(r);
                        });
                    }
                }


                #endregion
                #region 保养校验

                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var byRequest  = flashrequest.Products.Where(r => r.Type == 5);
                    var activityId = byRequest.FirstOrDefault(o => o.ActivityId != Guid.Empty)?.ActivityId;
                    if (activityId != null)
                    {
                        ValidateOrderRequest validateRequest = new ValidateOrderRequest()
                        {
                            ActivityId = activityId.Value,
                            UserId     = flashrequest.UserId,
                            Products   =
                                request.Items.Where(
                                    o => o.ActivityId != null && o.ActivityId.HasValue && !o.Pid.StartsWith("FU-") && !o.Pid.StartsWith("TR-"))
                                .Select(o => new OrderProduct()
                            {
                                ProductId   = o.Pid,
                                Count       = o.Num,
                                ActivityId  = o.ActivityId.Value,
                                Price       = o.Price,
                                ProductType = "Product"
                            }).ToList(),
                            ShopId      = request.Delivery.InstallShopId ?? 0,
                            Channel     = request.OrderChannel,
                            InstallType = request.Delivery.InstallType,
                            Vehicle     = Converter.Convert(request.Car),
                            RegionId    = 1
                        };
                        using (var client = new BaoYangClient())
                        {
                            var baoyangResult = await client.ValidateFixedPriceActivityOrderAsync(validateRequest);

                            if (!baoyangResult.Success || !baoyangResult.Result)
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = (int)CreateOrderErrorCode.ProductValidateFailed,
                                    ErrorMessage =
                                        CreateOrderMessageDic.GetMessage(CreateOrderErrorCode.ProductValidateFailed)
                                });
                            }
                        }
                        // 验证活动状态
                        var validateResult = await ActivityValidator.ValidateBaoyang(activityId.Value);

                        if (validateResult.Item1 == Model.CreateOrderErrorCode.ActivitySatisfied)
                        {
                            // 验证限购数量
                            counter = new BaoYangCounter(activityId.Value, validateResult.Item2, validateResult.Item3,
                                                         validateResult.Item4);
                            var countResult = await counter.CanPurchaseAndIncreaseCount(flashrequest.UserId,
                                                                                        flashrequest.DeviceId, flashrequest.UseTel);

                            if (countResult.Code != Model.CreateOrderErrorCode.ActivitySatisfied)
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = (int)countResult.Code,
                                    ErrorMessage = CreateOrderMessageDic.GetMessage(countResult.Code)
                                });
                            }
                        }
                        else
                        {
                            return(new CreateOrderResult()
                            {
                                ErrorCode = (int)validateResult.Item1,
                                ErrorMessage = CreateOrderMessageDic.GetMessage(validateResult.Item1)
                            });
                        }
                    }
                }

                #endregion
                #region 分享砍价活动
                bool   bargainflag = false;
                Guid   ownerId     = new Guid();
                string pid         = "";
                var    parameters  = new List <BuyLimitDetailModel>();
                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    var item = flashrequest.Products.FirstOrDefault(g => g.Type == 9);
                    if (item != null)
                    {
                        ownerId = flashrequest.UserId;
                        pid     = item.PID;
                        parameters.Add(new BuyLimitDetailModel
                        {
                            ModuleName    = "sharebargain",
                            LimitObjectId = ownerId.ToString("D"),
                            ObjectType    = LimitObjectTypeEnum.UserId.ToString(),
                            Remark        = "砍价实物商品下单"
                        });
                        if (!string.IsNullOrWhiteSpace(flashrequest.DeviceId))
                        {
                            parameters.Add(new BuyLimitDetailModel
                            {
                                ModuleName    = "sharebargain",
                                LimitObjectId = flashrequest.DeviceId,
                                ObjectType    = LimitObjectTypeEnum.DeviceId.ToString(),
                                Remark        = "砍价实物商品下单"
                            });
                        }
                        var val = await DalBargain.CheckBargainProductStatusByPID(ownerId, pid);

                        if (!val)
                        {
                            return(new CreateOrderResult()
                            {
                                ErrorCode = -1000,
                                ErrorMessage = "您当前没有资格享受该优惠!"
                            });
                        }
                        bargainflag = true;
                    }
                }
                #endregion

                IEnumerable <OrderItems> discountProducts = null;
                #region 黎先攀的打折活动
                if (flashrequest.Products != null && flashrequest.Products.Any())
                {
                    discountProducts = flashrequest.Products.Where(r => r.Type == 11);///打折活动商品
                    if (discountProducts.Any())
                    {
                        var productHitDiscountManager = new ProductHitDiscountManager(discountProducts.Select(s => new DiscountActivityRequest()
                        {
                            Pid   = s.PID,
                            Num   = s.Num,
                            Price = s.ListPrice
                        }).ToList(), request.Customer.UserId.ToString(), false, true);
                        var realProductDiscounts = (await productHitDiscountManager.GetProductHitDiscountInfo()).ToList();//实时产品折扣信息
                        var effictiveDiscountNum = discountProducts.Join(realProductDiscounts, x => x.PID, y => y.Pid, (x, y) =>
                        {
                            return(y.IsHit && string.Equals(y.DiscountRule?.ActivityId, x.ActivityId.ToString()) && Convert.ToInt32(y.DiscountPrice) == Convert.ToInt32(x.Price));
                        }).Where(s => s).Count();
                        if (effictiveDiscountNum != discountProducts.Count())
                        {
                            var firtNotHitProduct = realProductDiscounts.FirstOrDefault(s => !s.IsHit);
                            foreach (var item in discountProducts)
                            {
                                if (item.ActivityId != null && item.ActivityId != Guid.Empty)
                                {
                                    TuhuNotification.SendNotification("DiscountActivityCreateOrder", new DiscountCreateOrderRequest()
                                    {
                                        ActivityId = item.ActivityId.ToString(),
                                        Num        = item.Num,
                                        Pid        = item.PID,
                                        UserId     = request.Customer.UserId.ToString()
                                    });
                                }
                            }
                            var errorMsg = firtNotHitProduct != null ? firtNotHitProduct.FailMessage : "打折规则已变更";
                            Logger.Info($"打折活动下单失败:{errorMsg},discountProducts:{JsonConvert.SerializeObject(discountProducts)}," +
                                        $"realProductDiscounts:{JsonConvert.SerializeObject(realProductDiscounts)}");
                            return(new CreateOrderResult()
                            {
                                ErrorCode = -1000,
                                ErrorMessage = errorMsg
                            });
                        }
                    }
                }
                #endregion
                try
                {
                    using (var client = new CreateOrderClient())
                    {
                        var result = await client.CreateOrderAsync(request);

                        result.ThrowIfException();
                        if (result.Success)
                        {
                            if (counter != null)
                            {
                                await counter.AddOrderRecord(result.Result.OrderId, flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                            }
                            if (bargainflag)
                            {
                                var tal = await DalBargain.BuyBargainProductAsync(ownerId, pid, result.Result.OrderId);

                                if (tal > 0)
                                {
                                    parameters.ForEach(g => { g.ModuleProductId = tal.ToString(); g.Reference = result.Result.OrderId.ToString(); });
                                    await LimitBuyManager.AddBuyLimitInfo(parameters);

                                    Logger.Info($"UserId为{ownerId}的用户享受砍价优惠,已购买pid为{pid}的商品");
                                }
                                else
                                {
                                    Logger.Error($"UserId为{ownerId}的用户享受砍价优惠,购买pid为{pid}的商品,修改购买状态时出错");
                                }
                            }
                            flashrequest.OrderId = result.Result.OrderId;
                            if (isCheckFlash)
                            {
                                Logger.Info($"下单成功订单号=>{flashrequest.OrderId}发送消息");
                                try
                                {
                                    TuhuNotification.SendNotification(".FlashSaleCreateOrder.", flashrequest);
                                }
                                catch (Exception ex)
                                {
                                    var str = "";
                                    try
                                    {
                                        str = JsonConvert.SerializeObject(flashrequest);
                                    }
                                    catch (Exception)
                                    {
                                        str = result.Result.OrderId.ToString();
                                    }

                                    Logger.Error($"request-->{str}-->mq发送失败", ex);
                                }
                            }
                            if (discountProducts != null && discountProducts.Any())//如果是黎先攀的打折活动
                            {
                                foreach (var item in discountProducts)
                                {
                                    if (item.ActivityId != null && item.ActivityId != Guid.Empty)
                                    {
                                        TuhuNotification.SendNotification("DiscountActivityCreateOrder", new DiscountCreateOrderRequest()
                                        {
                                            ActivityId = item.ActivityId.ToString(),
                                            Num        = item.Num,
                                            OrderId    = result.Result.OrderId,
                                            Pid        = item.PID,
                                            UserId     = request.Customer.UserId.ToString()
                                        });
                                    }
                                }
                            }
                            return(new CreateOrderResult
                            {
                                OrderId = result.Result.OrderId,
                                OrderNo = result.Result.OrderNo
                            });
                        }
                        else
                        {
                            // 拼团下单失败,修改虚拟库存
                            if (pintuanFlag)
                            {
                                using (var client2 = new PinTuanClient())
                                {
                                    var result2 = await client2.DecrementSoldCountAsync(pintuanProductGroupId, pintuanPid, pintuanCount);

                                    if (!(result2.Success && result2.Result.Code == 1))
                                    {
                                        Logger.Error($"拼团产品下单失败,虚拟库存修改失败-->{pintuanProductGroupId}/{pintuanPid}/{pintuanCount}");
                                    }
                                }
                            }


                            if (counter != null)
                            {
                                await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                            }
                            Logger.Info("调用下单接口失败" + result.ErrorCode + result.ErrorMessage);
                            if (isCheckFlash)
                            {
                                await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult);
                            }
                            if (result.ErrorCode == "Order_FlashSale_Error")
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = -1000,
                                    ErrorMessage = CreateOrderMessageDic.GetFlashSaleErrorMessage(result.ErrorMessage)
                                });
                            }
                            if (result.ErrorCode == "Invalid_PromotionCode")
                            {
                                return new CreateOrderResult()
                                       {
                                           ErrorCode    = -1000,
                                           ErrorMessage = "优惠券无效!"
                                       }
                            }
                            ;
                            else
                            {
                                return(new CreateOrderResult()
                                {
                                    ErrorCode = -1000,
                                    ErrorMessage = "下单失败!"
                                });
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (counter != null)
                    {
                        await counter.DecreasePurchaseCount(flashrequest.UserId, flashrequest.DeviceId, flashrequest.UseTel);
                    }
                    if (isCheckFlash)
                    {
                        await FlashSaleCounter.DecrementAllFlashCount(fsRequest, flashSaleResult);
                    }
                    Logger.Error("调用下单接口失败" + ex.Message + ex.InnerException);
                    return(new CreateOrderResult()
                    {
                        ErrorCode = -1000,
                        ErrorMessage = "下单失败"
                    });
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                return(new CreateOrderResult()
                {
                    ErrorCode = -1000,
                    ErrorMessage = "下单失败"
                });
            }
        }