Exemple #1
0
        //检查优惠券id是否可用
        public static CheckPidResult CheckCouponPid(string PID, DateTime beginDateTime, DateTime endDateTime)
        {
            var result = new CheckPidResult();
            var dat    = DALShareBargain.CheckBargainProductByPid(PID, beginDateTime, endDateTime);

            if (dat)
            {
                result.Code = 2;
                result.Info = "该优惠券已在活动中";
            }
            else
            {
                using (var memberClient = new Tuhu.Service.Member.PromotionClient())
                {
                    if (!Guid.TryParse(PID, out Guid rr))
                    {
                        result.Code = 4;
                        result.Info = "优惠券pid格式错误";
                        return(result);
                    }

                    var couponInfo = memberClient.GetCouponRule(new Guid(PID));
                    if (!couponInfo.Success)
                    {
                        result.Code = 3;
                        result.Info = "获取优惠券信息失败";
                        return(result);
                    }

                    result.Code = 1;
                    result.Info = couponInfo.Result.PromotionName;
                }
            }
            return(result);
        }
        /// <summary>
        /// 发送优惠券
        /// </summary>
        /// <param name="fightGroupsIdentity"></param>
        /// <returns></returns>
        public static async Task <FightGroupsPacketsProvideResponse> CreateFightGroupsPacketByPromotion(Guid fightGroupsIdentity)
        {
            using (var client = CacheHelper.CreateCacheClient(FightGroupPacketsListRedisKey))
            {
                List <FightGroupsPacketsLogModel> list = null;
                var result = await client.GetOrSetAsync <List <FightGroupsPacketsLogModel> >(fightGroupsIdentity.ToString(), async() => await DalFightGroupsPacketsLog.GetFightGroupsPacketsList(fightGroupsIdentity), TimeSpan.FromDays(1));

                list = result?.Value;
                if (list == null)
                {
                    list = await DalFightGroupsPacketsLog.GetFightGroupsPacketsList(fightGroupsIdentity);
                }
                if (list?.Where(_ => _.UserId == null)?.Count() <= 0 && list?.Where(_ => _.PromotionPKID != null)?.Count() <= 0)
                {
                    using (var memberClient = new Tuhu.Service.Member.PromotionClient())
                    {
                        List <CreatePromotionModel> promotionModelList = new List <CreatePromotionModel>();
                        foreach (var item in list)
                        {
                            promotionModelList.Add(new CreatePromotionModel()
                            {
                                Author         = item.UserId.ToString(),
                                GetRuleGUID    = item.GetRuleGuid,
                                UserID         = item.UserId,
                                Channel        = "小程序分享红包",
                                DeviceID       = "",
                                Operation      = "小程序分享红包",
                                IssueChannle   = "小程序分享红包",
                                IssueChannleId = fightGroupsIdentity.ToString(),
                                Issuer         = "李维童"
                            });
                        }
                        var memberResult = await memberClient.CreatePromotionsNewAsync(promotionModelList);

                        if (memberResult.Result.IsSuccess)
                        {
                            for (int i = 0; i < list?.Count; i++)
                            {
                                if (memberResult?.Result?.promotionIds?.Count > i)
                                {
                                    list[i].PromotionPKID = memberResult?.Result?.promotionIds[i];
                                }
                            }
                            await DalFightGroupsPacketsLog.UpdateCreatePromotionPKID(list);

                            // 先注释掉,因为读写库原因,删掉之后,下次从数据库读取不到
                            //using (var reditClient = CacheHelper.CreateCacheClient(FightGroupPacketsListRedisKey))
                            //{
                            //    reditClient.Remove(list?.Where(_ => _.IsLeader == true)?.FirstOrDefault()?.UserId.ToString());
                            //    reditClient.Remove(fightGroupsIdentity.ToString());
                            //}


                            using (var pushClient = new Tuhu.Service.Push.TemplatePushClient())
                            {
                                foreach (var item in list)
                                {
                                    using (var userClient = new Tuhu.Service.UserAccount.UserAccountClient())
                                    {
                                        var userResult = await userClient.GetUserByIdAsync(item.UserId.Value);

                                        var pushResult = await pushClient.PushByUserIDAndBatchIDAsync(new List <string>() { item.UserId.Value.ToString() }, 1643, new Service.Push.Models.Push.PushTemplateLog()
                                        {
                                            Replacement = Newtonsoft.Json.JsonConvert.SerializeObject(new Dictionary <string, string>()
                                            {
                                                { "{{nickname}}", userResult.Result.Profile.NickName },
                                                { "{{packetgroupno}}", item.FightGroupsIdentity.ToString() }
                                            })
                                        });

                                        if (!pushResult.Success || !pushResult.Result)
                                        {
                                            Logger.ErrorException("拆红包推送失败", pushResult.Exception);
                                        }
                                    }
                                }
                            }

                            return(new FightGroupsPacketsProvideResponse()
                            {
                                IsSuccess = memberResult.Result.IsSuccess, Msg = "优惠券领取成功"
                            });
                        }
                        else
                        {
                            return(new FightGroupsPacketsProvideResponse()
                            {
                                IsSuccess = memberResult.Result.IsSuccess, Msg = memberResult?.Result?.ErrorMessage
                            });
                        }
                    }
                }
                else
                {
                    return new FightGroupsPacketsProvideResponse()
                           {
                               IsSuccess = false, Msg = string.Format("分享红包组没有拼组完成还差{0}个或者已经发放过", list?.Where(_ => _.UserId == null)?.Count())
                           }
                };
            }
        }
        /// <summary>
        /// 根据礼包
        /// </summary>
        /// <param name="pkid"></param>
        /// <returns></returns>
        public async Task <IEnumerable <CouponRule> > GetCouponRuleItems(int pkid, DateTime logDateTime)
        {
            List <Guid> guids = new List <Guid>();

            foreach (var item in this.entity.ItemPools)
            {
                if (item?.PartItem?.Where(_ => _.PKID == pkid)?.Count() > 0)
                {
                    foreach (var coupon in item?.PartItem?.Where(_ => _.PKID == pkid)?.FirstOrDefault()?.PartItem)
                    {
                        if (!string.IsNullOrWhiteSpace(coupon.CouponGuid))
                        {
                            guids.Add(Guid.Parse(coupon.CouponGuid));
                        }
                    }

                    break;
                }
            }
            if (guids.Count > 0)
            {
                using (var client = new Tuhu.Service.Member.PromotionClient())
                {
                    var result = await client.GetCouponRulesAsync(guids);

                    result.ThrowIfException(true);
                    List <CouponRule> list = new List <CouponRule>();
                    foreach (var _ in result?.Result)
                    {
                        var model = new CouponRule()
                        {
                            DeadLineDate   = _.DeadLineDate,
                            Description    = _.Description,
                            Discount       = _.Discount,
                            MinMoney       = _.MinMoney,
                            PromotionName  = _.PromotionName,
                            Term           = _.Term,
                            ValiEndDate    = _.ValiEndDate,
                            ValiStartDate  = _.ValiStartDate,
                            CreateDateTime = logDateTime,
                        };
                        model.DateNumber = model.GetDateNumber();
                        #region 设置优惠券使用状态
                        if (this.PromotionCodes != null && this.PromotionCodes?.Length > 0)
                        {
                            using (var promotionClient = new Tuhu.Service.Member.PromotionClient())
                            {
                                var resultPromotion = await promotionClient.GetPromotionCodeForUserCenterAsync(new GetPromotionCodeRequest()
                                {
                                    UserID = this.UserId,
                                    Type   = PromotionStatus.AlreadyUsed
                                }, new Tuhu.Models.PagerModel()
                                {
                                    PageSize = 50
                                });

                                if (resultPromotion.Success && resultPromotion?.Result?.Where(p => p.Pkid == Convert.ToInt64(this.PromotionCodes[0].Split(',')[0]))?.Count() > 0)
                                {
                                    model.DateNumber = -2;
                                }
                            }
                        }
                        #endregion
                        list.Add(model);
                    }

                    return(list);
                }
            }
            else
            {
                return(null);
            }
        }
        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));
        }
        public async Task <OperationResult <BigBrandCanResponse> > SelectCanPackerAsync(Guid userId, string deviceId, string Channal, string hashKey, string phone, string refer, string openId = default(string))
        {
            if (string.IsNullOrWhiteSpace(hashKey))
            {
                return(OperationResult.FromResult(new BigBrandCanResponse()
                {
                    Code = -1, Msg = "Hash不能为空"
                }));
            }

            Regex regex = new Regex("^([0-9]|[a-z]|[A-Z]){7}([0-9]|[a-z]|[A-Z])$");

            if (!regex.IsMatch(hashKey))
            {
                return(OperationResult.FromResult(new BigBrandCanResponse()
                {
                    Code = -1, Msg = "Hash不匹配"
                }));
            }


            if (userId == Guid.Empty && string.IsNullOrEmpty(openId))
            {
                return(OperationResult.FromResult(new BigBrandCanResponse()
                {
                    Code = -1, Msg = "用户UserId和OpenId不能都为空"
                }));
            }

            BigBrandLogic bigBrand = new BigBrandLogic(hashKey, userId, phone, deviceId, Channal, openId);

            bigBrand.Refer = refer;
            var result = await bigBrand.IsSelectCanPackage();

            if (GlobalConstant.HashKey_VehicleTypeCertificationRights.Contains(hashKey))
            {
                bigBrand.GetRandomPageckagePKID();
            }

            if (result.Result)
            {
                return(OperationResult.FromResult(new BigBrandCanResponse()
                {
                    Code = 1,
                    IsShare = bigBrand.IsShare,
                    Item = string.Empty,
                    Msg = "今天还有" + bigBrand.TimeCount + "次机会",
                    Times = bigBrand.TimeCount,
                    DefaultPool = bigBrand.DefaultPool, //只对 23338FF5 870F1F2E活动有效
                    ShareTimes = bigBrand.ShareTimes
                }));
            }
            else
            {
                if (!string.IsNullOrEmpty(result.ErrorMessage))
                {
                    return(OperationResult.FromError <BigBrandCanResponse>(result.ErrorCode, result.ErrorMessage));
                }
                else
                {
                    var model = new BigBrandCanResponse()
                    {
                        Code    = 0,
                        IsShare = bigBrand.IsShare,
                        // Item = hashKey == "23338FF5" || hashKey == "870F1F2E" ? Newtonsoft.Json.JsonConvert.SerializeObject(bigBrand.GetRewardInfoLast(userId)) : "",
                        Msg         = "今天还有" + bigBrand.TimeCount ?? 0 + "次机会",
                        Times       = bigBrand.TimeCount,
                        DefaultPool = bigBrand.DefaultPool, //只对 23338FF5 870F1F2E活动有效
                        ShareTimes  = bigBrand.ShareTimes
                    };
                    if (GlobalConstant.HashKey_VehicleTypeCertificationRights.Contains(hashKey))
                    {
                        //bigBrand.PromotionCodes
                        var package = bigBrand.GetRewardInfoLast(userId);
                        model.Item = Newtonsoft.Json.JsonConvert.SerializeObject(package);
                        if (package != null)
                        {
                            model.CouponRuleItems = await bigBrand.GetCouponRuleItems(package.PKID, package.DateTimeLog.Value);
                        }
                        if (package != null && bigBrand?.PromotionCodes?.Count() > 0)
                        {
                            using (var memberClient = new Tuhu.Service.Member.PromotionClient())
                            {
                                var memberResult = await memberClient.FetchPromotionCodeByIDAsync(new Member.Request.FetchPromotionCodeRequest()
                                {
                                    PKID = Convert.ToInt32(bigBrand.PromotionCodes[0])
                                });

                                if (memberResult.Success)
                                {
                                    var couponRuleModel = model.CouponRuleItems?.FirstOrDefault();
                                    couponRuleModel.CreateDateTime = Convert.ToDateTime(memberResult.Result.StartTime);
                                    couponRuleModel.ValiStartDate  = Convert.ToDateTime(memberResult.Result.StartTime);
                                    couponRuleModel.ValiEndDate    = Convert.ToDateTime(memberResult.Result.EndTime);
                                    couponRuleModel.Term           = null;
                                    couponRuleModel.DateNumber     = memberResult.Result.Status == 0 ? couponRuleModel.GetDateNumber() : -2;
                                }
                            }
                        }
                    }
                    return(OperationResult.FromResult(model));
                }
            }
        }