Exemplo n.º 1
0
        protected override EmptyResponseData ProcessRequest(APIRequest <EmptyRequestParameter> pRequest)
        {
            EmptyResponseData rd = new EmptyResponseData();
            var vipAmountBll     = new VipAmountBLL(CurrentUserInfo);

            if (!string.IsNullOrEmpty(pRequest.UserID))
            {
                var vipAmountEntity = vipAmountBll.QueryByEntity(new VipAmountEntity()
                {
                    VipId = pRequest.UserID
                }, null).FirstOrDefault();
                if (vipAmountEntity != null || vipAmountEntity.EndAmount == 0)
                {
                    if (vipAmountEntity.PayPassword == null)
                    {
                        throw new APIException("客户尚未设置密码,请提示客户到会员中心设置密码")
                              {
                                  ErrorCode = 100
                              };
                    }
                }
            }
            return(rd);
        }
Exemplo n.º 2
0
        const int MEMBER_HAVECARDNOTIPS    = 320; //领取成功 不提示 但跳到实体卡
        #endregion

        protected override AuthCodeLoginRD ProcessRequest(DTO.Base.APIRequest <AuthCodeLoginRP> pRequest)
        {
            var vipCardVipMappingBLL = new VipCardVipMappingBLL(CurrentUserInfo);

            //参数验证
            if (string.IsNullOrEmpty(pRequest.Parameters.Mobile))
            {
                throw new APIException("请求参数中缺少Mobile或值为空.")
                      {
                          ErrorCode = ERROR_LACK_MOBILE
                      };
            }
            if (pRequest.Parameters.VipSource.HasValue == false)
            {
                pRequest.Parameters.VipSource = 1;
                //throw new APIException("请求参数中缺少VipSource或值为空.") { ErrorCode = ERROR_LACK_VIP_SOURCE };
            }
            //
            AuthCodeLoginRD rd         = new AuthCodeLoginRD();
            var             bll        = new VipBLL(this.CurrentUserInfo);
            var             codebll    = new RegisterValidationCodeBLL(base.CurrentUserInfo);
            VipEntity       vipByID    = null; //根据VIP ID查找出来的VIP记录
            VipEntity       vipByPhone = null; //根据手机号查找出来的VIP记录


            //var list = codebll.QueryByEntity(new RegisterValidationCodeEntity()
            //{
            //    Mobile = pRequest.Parameters.Mobile
            //}, null);
            //bool b = false;
            //if (list != null)
            //{
            //    foreach (var entity in list)
            //    {
            //        if (entity == null)
            //            throw new APIException("未找到此手机的验证信息") {ErrorCode = ERROR_AUTHCODE_NOTEXISTS};
            //        //if (entity.IsValidated.Value == 1)
            //        //    throw new APIException("此验证码已被使用") {ErrorCode = ERROR_AUTHCODE_WAS_USED};
            //        //if (entity.Expires.Value < DateTime.Now)
            //        //    throw new APIException("此验证码已失效") {ErrorCode = ERROR_AUTHCODE_INVALID};
            //        if (entity.Code == pRequest.Parameters.AuthCode)
            //            b = true;
            //    }
            //}
            //if (!b)
            //{
            //    throw new APIException("验证码不正确.") { ErrorCode = ERROR_AUTHCODE_NOT_EQUALS };
            //}

            #region 验证验证码
            var entity = codebll.GetByMobile(pRequest.Parameters.Mobile);
            if (entity == null)
            {
                throw new APIException("未找到此手机的验证信息")
                      {
                          ErrorCode = ERROR_AUTHCODE_NOTEXISTS
                      }
            }
            ;
            if (entity.IsValidated.Value == 1)
            {
                throw new APIException("此验证码已被使用")
                      {
                          ErrorCode = ERROR_AUTHCODE_WAS_USED
                      }
            }
            ;
            if (entity.Expires.Value < DateTime.Now)
            {
                throw new APIException("此验证码已失效")
                      {
                          ErrorCode = ERROR_AUTHCODE_INVALID
                      }
            }
            ;
            if (entity.Code != pRequest.Parameters.AuthCode)
            {
                throw new APIException("验证码不正确.")
                      {
                          ErrorCode = ERROR_AUTHCODE_NOT_EQUALS
                      }
            }
            ;
            #endregion

            #region 获取会员权益
            var customerBasicSettingBll = new CustomerBasicSettingBLL(CurrentUserInfo);
            var memberBenefit           = customerBasicSettingBll.GetMemberBenefits(pRequest.CustomerID);
            var bllPrize = new LPrizesBLL(CurrentUserInfo);
            #endregion
            //自定义没有实体卡,有实体卡时变为1
            int HaveVipcard = 0;
            //要发送给rabbitmq的信息
            var           eventService = new EventService();
            EventContract vipMsg       = null;

            switch (pRequest.Parameters.VipSource.Value)
            {
            case 3:     //来源是微信时,做自动合并
            {
                #region 根据手机号查找下,看下是否存在同样手机号的VIP记录
                {
                    List <IWhereCondition> wheres = new List <IWhereCondition>();
                    wheres.Add(new MoreThanCondition()
                        {
                            FieldName = "status", Value = 0, IncludeEquals = false
                        });                                                                                                //潜在或者正式会员
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "phone", Value = pRequest.Parameters.Mobile
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "clientid", Value = pRequest.CustomerID
                        });
                    var result = bll.Query(wheres.ToArray(), null);
                    if (result != null && result.Length > 0)
                    {
                        vipByPhone = result[0];
                    }
                    if (vipByPhone != null && vipByPhone.VipSourceId == "3" && vipByPhone.Status.Value >= 2)
                    {
                        throw new APIException("会员已经注册")
                              {
                                  ErrorCode = ERROR_MEMBER_REGISTERED
                              };
                    }
                }
                #endregion

                #region 根据VIP ID查找下,看下是否存在该VIP的记录
                if (!string.IsNullOrEmpty(pRequest.UserID))
                {
                    List <IWhereCondition> wheres = new List <IWhereCondition>();
                    //wheres.Add(new MoreThanCondition() { FieldName = "status", Value = 0, IncludeEquals = false });
                    wheres.Add(new MoreThanCondition()
                        {
                            FieldName = "status", Value = 0, IncludeEquals = true
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "vipid", Value = pRequest.UserID
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "clientid", Value = pRequest.CustomerID
                        });
                    var result = bll.Query(wheres.ToArray(), null);
                    if (result != null && result.Length > 0)
                    {
                        vipByID = result[0];
                    }
                }
                else
                {        //如果前端未指定VIP ID则后台指定
                    pRequest.UserID = Guid.NewGuid().ToString("N");
                }
                //判断用户是从点击领取过来的 还是从点击绑定实体卡过来的
                int?RegisterType = 0;
                if (pRequest.Parameters.registerType != null)
                {
                    RegisterType = pRequest.Parameters.registerType;
                }

                //当手机号不为空时需要查询是否存在实体卡
                if (!string.IsNullOrEmpty(pRequest.Parameters.Mobile) && (!string.IsNullOrEmpty(pRequest.UserID) || !string.IsNullOrEmpty(vipByPhone.VIPID)))
                {
                    List <IWhereCondition> wheres = new List <IWhereCondition>();
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "phone", Value = pRequest.Parameters.Mobile
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "clientid", Value = pRequest.CustomerID
                        });
                    wheres.Add(new DirectCondition("VipID!='" + pRequest.UserID + "'"));
                    var vipInfo = bll.Query(wheres.ToArray(), null);
                    //若是从绑定实体卡进入,进行实体卡的判断,并不注册成功
                    if (RegisterType == 2)
                    {
                        if (vipInfo == null || vipInfo.Length == 0)
                        {
                            throw new APIException("未检测到实体卡")
                                  {
                                      ErrorCode = MEMBER_HAVENOCARD
                                  };
                        }
                        else
                        {
                            vipCardVipMappingBLL.BindVipCard(vipByID.VIPID, vipByID.VipCode, vipByID.CouponInfo);
                            HaveVipcard = 1;        //需要给绑定实体卡的提示
                        }
                    }
                    else
                    {
                        vipCardVipMappingBLL.BindVipCard(vipByID.VIPID, vipByID.VipCode, vipByID.CouponInfo);
                        //若是从"点击领取"进入则进行判断有没有实体卡   有没有实体卡都进行领卡成功的提示
                        if (vipInfo != null && vipInfo.Length > 0)
                        {
                            HaveVipcard = 1;        //需要给绑定实体卡的提示
                        }
                        else
                        {
                            HaveVipcard = 2;        //注册成功但没有实体卡
                        }
                    }
                }

                if (vipByID == null && vipByPhone == null) //根据vipid查不出记录,并且根据手机号也查不出记录 新增一条vip
                {                                          //如果不存在则首先创建一条VIP记录,补充记录
                    vipByID = new VipEntity()
                    {
                        Phone            = pRequest.Parameters.Mobile,
                        VipName          = pRequest.Parameters.Mobile,
                        UserName         = pRequest.Parameters.Mobile,
                        VipRealName      = pRequest.Parameters.VipRealName,
                        VIPID            = pRequest.UserID,
                        Status           = 2,
                        ClientID         = pRequest.CustomerID,
                        VipCode          = "Vip" + bll.GetNewVipCode(pRequest.CustomerID),
                        VipSourceId      = pRequest.Parameters.VipSource.ToString(),
                        WeiXinUserId     = string.IsNullOrWhiteSpace(pRequest.UserID) ? Guid.NewGuid().ToString("N") : pRequest.UserID,
                        RegistrationTime = DateTime.Now
                    };
                    bll.Create(vipByID);
                    #region 注册会员触点活动奖励
                    //bllPrize.CheckIsWinnerForShare(CurrentUserInfo.UserID, "", "Reg");

                    RedisContactBLL redisContactBll = new RedisContactBLL();
                    redisContactBll.SetRedisContact(new RedisOpenAPIClient.Models.CC.CC_Contact()
                        {
                            CustomerId  = CurrentUserInfo.ClientID,
                            ContactType = "Reg",
                            VipId       = CurrentUserInfo.UserID
                        });

                    #endregion
                }
                else if (vipByID != null)
                {
                    VipEntity vipUpdateInfo       = new VipEntity();
                    List <IWhereCondition> wheres = new List <IWhereCondition>();
                    //wheres.Add(new MoreThanCondition() { FieldName = "status", Value = 0, IncludeEquals = false });
                    wheres.Add(new MoreThanCondition()
                        {
                            FieldName = "status", Value = 0, IncludeEquals = true
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "vipid", Value = pRequest.UserID
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "clientid", Value = pRequest.CustomerID
                        });
                    var result = bll.Query(wheres.ToArray(), null);
                    if (result != null && result.Length > 0)
                    {
                        vipUpdateInfo = result[0];
                    }
                    vipUpdateInfo.Phone = pRequest.Parameters.Mobile;
                    if (!string.IsNullOrEmpty(pRequest.Parameters.VipRealName))
                    {
                        vipUpdateInfo.VipRealName = pRequest.Parameters.VipRealName;
                    }
                    vipUpdateInfo.Status           = 2;
                    vipUpdateInfo.RegistrationTime = DateTime.Now;
                    bll.Update(vipUpdateInfo);
                    #region 注册会员触点活动奖励
                    //bllPrize.CheckIsWinnerForShare(CurrentUserInfo.UserID, "", "Reg");
                    RedisContactBLL redisContactBll = new RedisContactBLL();
                    redisContactBll.SetRedisContact(new RedisOpenAPIClient.Models.CC.CC_Contact()
                        {
                            CustomerId  = CurrentUserInfo.ClientID,
                            ContactType = "Reg",
                            VipId       = CurrentUserInfo.UserID
                        });
                    #endregion

                    #region 会员金矿、注册集客奖励
                    bll.SetOffActionReg(vipByID);
                    #endregion
                }

                #endregion

                #region 根据VIP ID及手机号查询出的结果,尝试自动合并会员 (因目前会员注册不自动绑卡,实现用户自行选择绑卡业务故将绑卡业务注释掉)
                //if (vipByPhone == null)
                //{//如果未有相同手机号的用户,则无须绑定,直接使用VIP ID对应的VIP记录作为当前注册用户的记录
                //    rd.MemberInfo = new MemberInfo()
                //    {
                //        Mobile = vipByID.Phone
                //        ,
                //        VipID = vipByID.VIPID
                //        ,
                //        Name = vipByID.UserName
                //        ,
                //        VipName = vipByID.VipName
                //        ,
                //        VipNo = vipByID.VipCode
                //        ,
                //        MemberBenefits = memberBenefit
                //        ,
                //        IsActivate = vipByID.IsActivate.HasValue && vipByID.IsActivate.Value == 1 ? true : false
                //    };
                //    //处理绑卡业务 add by Henry 2015/10/28
                //    vipCardVipMappingBLL.BindVipCard(vipByID.VIPID, vipByID.VipCode, vipByID.CouponInfo);
                //}
                //else
                //{//否则调用存储过程,做自动会员合并

                //    //如果会员已经注册过,并且来源是微信的则表示该帐号已经被注册过不能再次绑定
                //    if (vipByPhone.VipSourceId == "3" && vipByPhone.Status.Value >= 2)
                //    {
                //        throw new APIException("会员已经注册") { ErrorCode = ERROR_MEMBER_REGISTERED };
                //    }
                //    //否则做会员合并
                //    if (!bll.MergeVipInfo(pRequest.CustomerID, pRequest.UserID, pRequest.Parameters.Mobile))
                //    {
                //        throw new APIException("自动绑定会员信息失败") { ErrorCode = ERROR_AUTO_MERGE_MEMBER_FAILED };
                //    }

                //    //合并成功后重新读取信息
                //    List<IWhereCondition> wheres = new List<IWhereCondition>();
                //    wheres.Add(new MoreThanCondition() { FieldName = "status", Value = 0, IncludeEquals = false });
                //    wheres.Add(new EqualsCondition() { FieldName = "vipid", Value = pRequest.UserID });
                //    wheres.Add(new EqualsCondition() { FieldName = "clientid", Value = pRequest.CustomerID });
                //    var result = bll.Query(wheres.ToArray(), null);
                //    vipByID = result[0];
                //    rd.MemberInfo = new MemberInfo()
                //    {
                //        Mobile = vipByID.Phone
                //        ,
                //        VipID = vipByID.VIPID
                //        ,
                //        Name = vipByID.UserName
                //        ,
                //        VipName = vipByID.VipName
                //        ,
                //        VipNo = vipByID.VipCode
                //        ,
                //        MemberBenefits = memberBenefit
                //        ,
                //        IsActivate = vipByID.IsActivate.HasValue && vipByID.IsActivate.Value == 1 ? true : false
                //    };
                //    //处理绑卡业务 add by Henry 2015/10/28
                //    vipCardVipMappingBLL.BindVipCard(vipByID.VIPID, vipByID.VipCode, vipByID.CouponInfo);
                //}
                #endregion
            }
                //注册会员信息发布到rabbitmq
                vipMsg = new EventContract
                {
                    Operation  = OptEnum.Create,
                    EntityType = EntityTypeEnum.Vip,
                    Id         = pRequest.UserID
                };
                eventService.PublishMsg(vipMsg);

                break;

            default:    //其他来源则为自动注册
            {
                #region 根据手机号查找下,看下是否存在同样手机号的VIP记录
                {
                    List <IWhereCondition> wheres = new List <IWhereCondition>();
                    wheres.Add(new MoreThanCondition()
                        {
                            FieldName = "status", Value = 0, IncludeEquals = false
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "phone", Value = pRequest.Parameters.Mobile
                        });
                    wheres.Add(new EqualsCondition()
                        {
                            FieldName = "clientid", Value = pRequest.CustomerID
                        });
                    var result = bll.Query(wheres.ToArray(), null);
                    if (result != null && result.Length > 0)
                    {
                        vipByPhone = result[0];
                    }
                    if (vipByPhone != null && vipByPhone.Status.Value >= 2)
                    {
                        throw new APIException("会员已经注册")
                              {
                                  ErrorCode = ERROR_MEMBER_REGISTERED
                              };
                    }
                }
                #endregion

                #region 没有找到相同电话的会员则自动注册
                if (vipByPhone == null)
                {        //没有找到相同电话的会员则自动注册
                    vipByPhone = new VipEntity()
                    {
                        Phone            = pRequest.Parameters.Mobile,
                        VipName          = pRequest.Parameters.Mobile,
                        UserName         = pRequest.Parameters.Mobile,
                        VipRealName      = pRequest.Parameters.VipRealName,
                        VIPID            = string.IsNullOrWhiteSpace(pRequest.UserID) ? Guid.NewGuid().ToString("N") : pRequest.UserID,
                        Status           = 2, //状态为注册
                        VipCode          = "Vip" + bll.GetNewVipCode(pRequest.CustomerID),
                        ClientID         = pRequest.CustomerID,
                        VipSourceId      = pRequest.Parameters.VipSource.ToString(),
                        WeiXinUserId     = string.IsNullOrWhiteSpace(pRequest.UserID) ? Guid.NewGuid().ToString("N") : pRequest.UserID,
                        RegistrationTime = DateTime.Now
                    };
                    bll.Create(vipByPhone);
                    #region 注册会员触点活动奖励
                    //bllPrize.CheckIsWinnerForShare(CurrentUserInfo.UserID, "", "Reg");
                    RedisContactBLL redisContactBll = new RedisContactBLL();
                    redisContactBll.SetRedisContact(new RedisOpenAPIClient.Models.CC.CC_Contact()
                        {
                            CustomerId  = CurrentUserInfo.ClientID,
                            ContactType = "Reg",
                            VipId       = CurrentUserInfo.UserID
                        });
                    #endregion
                }
                #endregion

                #region

                decimal         EndAmount    = 0;
                VipAmountBLL    AmountBLL    = new VipAmountBLL(this.CurrentUserInfo);
                VipAmountEntity amountEntity = AmountBLL.GetByID(vipByPhone.VIPID);
                if (amountEntity != null)
                {
                    EndAmount = amountEntity.EndAmount.HasValue ? amountEntity.EndAmount ?? 0 : 0;
                }

                #endregion

                #region 返回用户信息
                rd.MemberInfo = new MemberInfo()
                {
                    Mobile = vipByPhone.Phone
                    ,
                    VipID = vipByPhone.VIPID
                    ,
                    Name = vipByPhone.UserName
                    ,
                    VipName = vipByPhone.VipName
                    ,
                    VipRealName = vipByPhone.VipRealName
                    ,
                    VipNo = vipByPhone.VipCode
                    ,
                    MemberBenefits = memberBenefit
                    ,
                    IsActivate = false
                    ,
                    Integration = vipByPhone.Integration ?? 0
                    ,
                    Balance = EndAmount
                };


                #endregion
            }

                //注册会员信息发布到rabbitmq
                vipMsg = new EventContract
                {
                    Operation  = OptEnum.Create,
                    EntityType = EntityTypeEnum.Vip,
                    Id         = rd.MemberInfo.VipID
                };
                eventService.PublishMsg(vipMsg);
                break;
            }



            T_LEventsRegVipLogBLL lEventRegVipLogBll = new T_LEventsRegVipLogBLL(CurrentUserInfo);
            if (!string.IsNullOrEmpty(pRequest.Parameters.CTWEventId))
            {
                lEventRegVipLogBll.CTWRegOrFocusLog(pRequest.Parameters.CTWEventId, pRequest.UserID, "", CurrentUserInfo, "Reg");
            }
            //如果是通过优惠券进来的就有couponId 新注册的需要加记录
            if (!string.IsNullOrEmpty(pRequest.Parameters.couponId))
            {
                lEventRegVipLogBll.CouponRegOrFocusLog(pRequest.Parameters.couponId, pRequest.UserID, "", CurrentUserInfo, "Reg");
            }

            //当手机号不为空时需要查询是否存在实体卡
            //if (!string.IsNullOrEmpty(pRequest.Parameters.Mobile) && (!string.IsNullOrEmpty(pRequest.UserID) || !string.IsNullOrEmpty(vipByPhone.VIPID)))
            //{
            //    List<IWhereCondition> wheres = new List<IWhereCondition>();
            //    wheres.Add(new EqualsCondition() { FieldName = "phone", Value = pRequest.Parameters.Mobile });
            //    wheres.Add(new EqualsCondition() { FieldName = "clientid", Value = pRequest.CustomerID });
            //    wheres.Add(new DirectCondition("VipID!='" + pRequest.UserID + "'"));
            //    var vipInfo = bll.Query(wheres.ToArray(), null);
            //    if (vipInfo != null && vipInfo.Length > 0)
            //    {
            //        throw new APIException("检测到会员相关实体卡") { ErrorCode = MEMBER_HAVECARD };
            //    }
            //    else
            //    {
            //        //如果会员当前没有实体卡,则默认绑定等级为1的卡
            //        vipCardVipMappingBLL.BindVipCard(vipByID.VIPID, vipByID.VipCode, vipByID.CouponInfo);
            //        throw new APIException("未检测到实体卡") { ErrorCode = MEMBER_HAVENOCARD };
            //    }
            //}
            //判定是否有可绑卡的定义  1=有可绑卡
            if (HaveVipcard == 1 || HaveVipcard == 2)
            {
                //有积分的话给相应领取成功的积分提示
                var contactEventBLL = new ContactEventBLL(CurrentUserInfo);
                int sendIntegral    = 0;
                if (!string.IsNullOrEmpty(pRequest.Parameters.CTWEventId))
                {
                    sendIntegral = contactEventBLL.GetContactEventIntegral(CurrentUserInfo.ClientID, "Reg", "Point", 1);
                }
                else
                {
                    sendIntegral = contactEventBLL.GetContactEventIntegral(CurrentUserInfo.ClientID, "Reg", "Point", 0);
                }
                if (sendIntegral > 0)
                {
                    if (pRequest.Parameters.registerType != 2 && HaveVipcard == 2)
                    {
                        throw new APIException("恭喜您领取成功并获得" + sendIntegral + "注册积分")
                              {
                                  ErrorCode = MEMBER_GETSUCCESS
                              };                                                                                       //领取成功不跳转跳转到实体卡
                    }
                    else if (pRequest.Parameters.registerType == 2 && HaveVipcard == 1)
                    {
                        throw new APIException("恭喜您领取成功并获得" + sendIntegral + "注册积分")
                              {
                                  ErrorCode = MEMBER_HAVECARD_Integral
                              };                                                                                              //检测到有相关实体卡前端不提示领取成功 并跳到实体卡列表
                    }
                    else
                    {
                        throw new APIException("恭喜您领取成功并获得" + sendIntegral + "注册积分")
                              {
                                  ErrorCode = MEMBER_HAVECARD
                              };                                                                                     //领取成功,提示领取成功,并跳到相关实体卡
                    }
                }
                else
                {
                    if (pRequest.Parameters.registerType != 2 && HaveVipcard == 2)
                    {
                        throw new APIException("领取成功")
                              {
                                  ErrorCode = MEMBER_GETSUCCESS
                              };                                                         //领取成功不跳转跳转到实体卡
                    }
                    else if (pRequest.Parameters.registerType == 2 && HaveVipcard == 1)
                    {
                        throw new APIException("检测到有相关实体卡")
                              {
                                  ErrorCode = MEMBER_HAVECARD
                              };                                                            //检测到有相关实体卡前端不提示领取成功 并跳到实体卡列表
                    }
                    else if (pRequest.Parameters.registerType != 2 && HaveVipcard == 1)
                    {
                        throw new APIException("领取成功")
                              {
                                  ErrorCode = MEMBER_HAVECARD
                              };                                                       //领取成功有实体卡,并跳转
                    }
                    else
                    {
                        throw new APIException("检测到有相关实体卡")
                              {
                                  ErrorCode = MEMBER_HAVECARD
                              };                                                            //领取成功,提示领取成功,并跳到相关实体卡
                    }
                }
            }

            #region 将验证码设置为已验证
            //entity.IsValidated = 1;
            //codebll.Update(entity);
            #endregion


            return(rd);

            //AuthCodeLoginRD rd = new AuthCodeLoginRD();
            //rd.MemberInfo = new MemberInfo();
            //var codebll = new RegisterValidationCodeBLL(base.CurrentUserInfo);
            //var entity = codebll.GetByMobile(pRequest.Parameters.Mobile);
            //if (entity == null)
            //    throw new APIException("未找到此手机的验证信息") { ErrorCode = ERROR_AUTHCODE_NOTEXISTS };
            //if (entity.IsValidated.Value == 1)
            //    throw new APIException("此验证码已失效") { ErrorCode = ERROR_AUTHCODE_FAILURE };
            //if (entity.Expires.Value < DateTime.Now)
            //    throw new APIException("此验证码已失效") { ErrorCode = ERROR_AUTHCODE_FAILURE };
            //var vipbll = new VipBLL(base.CurrentUserInfo);
            //var vipinfo = vipbll.GetByMobile(pRequest.Parameters.Mobile, pRequest.CustomerID);

            //#region VIP来源更新
            //switch (pRequest.Parameters.VipSource.Value)
            //{
            //    case 4:
            //    case 9:
            //        vipinfo.VipSourceId = pRequest.Parameters.VipSource.ToString();
            //        vipbll.Update(vipinfo);
            //        break;
            //}
            //#endregion

            //if (string.IsNullOrEmpty(vipinfo.ClientID))
            //{
            //    vipinfo.ClientID = pRequest.CustomerID;
            //    vipbll.Update(vipinfo);
            //}
            //rd.MemberInfo.Mobile = vipinfo.Phone;
            //rd.MemberInfo.Name = vipinfo.UserName;
            //rd.MemberInfo.VipID = vipinfo.VIPID;
            //rd.MemberInfo.VipName = vipinfo.VipName;
            //var customerBasicSettingBll = new CustomerBasicSettingBLL(CurrentUserInfo);
            //rd.MemberInfo.MemberBenefits = customerBasicSettingBll.GetMemberBenefits(pRequest.CustomerID);
            //entity.IsValidated = 1;
            //codebll.Update(entity);
            //return rd;
        }
    }
}
Exemplo n.º 3
0
        public HttpResponseMessage Password(string vipId, string password)
        {
            Loggers.Debug(new DebugLogInfo()
            {
                Message = $"[api/Vip/Password]接口,参数:\"vipId:{vipId}&&password:{password}\""
            });
            try
            {
                if (string.IsNullOrEmpty(password))
                {
                    throw new APIException("请求参数中缺少Password或值为空.")
                          {
                              ErrorCode = 121
                          };
                }
                if (string.IsNullOrEmpty(password))
                {
                    throw new APIException("请求参数中缺少Password或值为空.")
                          {
                              ErrorCode = 121
                          };
                }

                var rd = new EmptyResponseData();

                string customerid         = ConfigurationManager.AppSettings["CustomerId"].Trim();
                var    loggingSessionInfo = Default.GetLoggingSession(customerid, "1");

                var vipbll    = new VipBLL(loggingSessionInfo);
                var vipEntity = vipbll.GetByID(vipId);
                if (vipEntity == null)
                {
                    throw new APIException("无效的会员ID【VipId】")
                          {
                              ErrorCode = 121
                          };
                }


                var bll             = new VipAmountBLL(loggingSessionInfo);
                var vipAmountEntity = bll.GetByID(vipId);

                if (vipAmountEntity == null)
                {
                    throw new APIException("该会员暂无绑定账户")
                          {
                              ErrorCode = 121
                          };
                }
                else
                {
                    if (vipAmountEntity.PayPassword != password)
                    {
                        throw new APIException("密码不正确")
                              {
                                  ErrorCode = 122
                              };
                    }
                }

                var responseModel = new BaseResponeModel
                {
                    IsSucess = true
                };
                return(Request.CreateResponse(HttpStatusCode.OK, responseModel));
            }
            catch (Exception ex)
            {
                var responseModel = new BaseResponeModel
                {
                    IsSucess     = false,
                    ErrorMessage = ex.Message
                };
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, responseModel));
            }
        }
        protected override SetReceiveAmountOrderRD ProcessRequest(APIRequest <SetReceiveAmountOrderRP> pRequest)
        {
            SetReceiveAmountOrderRP rp = pRequest.Parameters;
            SetReceiveAmountOrderRD rd = new SetReceiveAmountOrderRD();

            var receiveAmountOrderBll = new ReceiveAmountOrderBLL(CurrentUserInfo);
            var sysVipCardGradeBLL    = new SysVipCardGradeBLL(CurrentUserInfo); //获取折扣表
            var vipBLL  = new VipBLL(CurrentUserInfo);
            var unitBLL = new t_unitBLL(CurrentUserInfo);
            var vipInfo = vipBLL.GetByID(pRequest.UserID); //获取会员信息

            if (vipInfo == null)
            {
                throw new APIException("没有会员信息")
                      {
                          ErrorCode = 101
                      };
            }
            var unitInfo = unitBLL.GetByID(rp.UnitId);

            if (unitInfo == null)
            {
                throw new APIException("没有服务门店信息")
                      {
                          ErrorCode = 101
                      };
            }
            decimal discountAmount = 0;               //抵扣金额汇总
            decimal couponAmount   = 0;               //优惠券抵用金额
            decimal endAmount      = rp.VipEndAmount; //余额
            decimal integralAmount = rp.Integral;
            //获取订单号
            TUnitExpandBLL serviceUnitExpand = new TUnitExpandBLL(CurrentUserInfo);
            string         orderNo           = serviceUnitExpand.GetUnitOrderNo();
            //折扣
            decimal discount = 1;

            if (rp.VipDiscount > 0)
            {
                discount = sysVipCardGradeBLL.GetVipDiscount() / 10;//会员折扣
            }
            decimal tempAmount = Math.Round((discount == 0 ? 1 : discount) * rp.TotalAmount, 2, MidpointRounding.AwayFromZero);
            Guid    orderId    = Guid.NewGuid();

            //积分处理
            if (rp.IntegralFlag == 1)
            {
                //加入折扣金额
                discountAmount = discountAmount + rp.IntegralAmount;
            }
            else
            {
                integralAmount = 0;
            }

            //使用优惠券
            if (rp.CouponFlag == 1)
            {
                #region 判断优惠券是否是该会员的

                var vipcouponMappingBll = new VipCouponMappingBLL(CurrentUserInfo);

                var vipcouponmappingList = vipcouponMappingBll.QueryByEntity(new VipCouponMappingEntity()
                {
                    VIPID    = vipInfo.VIPID,
                    CouponID = rp.CouponId
                }, null);

                if (vipcouponmappingList == null || vipcouponmappingList.Length == 0)
                {
                    throw new APIException("此张优惠券不是该会员的")
                          {
                              ErrorCode = 103
                          };
                }

                #endregion

                #region 判断优惠券是否有效

                var couponBll = new CouponBLL(CurrentUserInfo);

                var couponEntity = couponBll.GetByID(rp.CouponId);

                if (couponEntity == null)
                {
                    throw new APIException("无效的优惠券")
                          {
                              ErrorCode = 103
                          };
                }

                if (couponEntity.Status == 1)
                {
                    throw new APIException("优惠券已使用")
                          {
                              ErrorCode = 103
                          };
                }

                if (couponEntity.EndDate < DateTime.Now)
                {
                    throw new APIException("优惠券已过期")
                          {
                              ErrorCode = 103
                          };
                }
                var couponTypeBll    = new CouponTypeBLL(CurrentUserInfo);
                var couponTypeEntity = couponTypeBll.GetByID(couponEntity.CouponTypeID);

                if (couponTypeEntity == null)
                {
                    throw new APIException("无效的优惠券类型")
                          {
                              ErrorCode = 103
                          };
                }

                #endregion

                discountAmount = discountAmount + couponTypeEntity.ParValue ?? 0;
                couponAmount   = couponTypeEntity.ParValue ?? 0;

                //更新使用记录
                var couponUseBll    = new CouponUseBLL(CurrentUserInfo);
                var couponUseEntity = new CouponUseEntity()
                {
                    CouponUseID    = Guid.NewGuid(),
                    CouponID       = rp.CouponId,
                    VipID          = vipInfo.VIPID,
                    UnitID         = rp.UnitId,
                    OrderID        = orderId.ToString(),
                    Comment        = "商城使用电子券",
                    CustomerID     = CurrentUserInfo.ClientID,
                    CreateBy       = CurrentUserInfo.UserID,
                    CreateTime     = DateTime.Now,
                    LastUpdateBy   = CurrentUserInfo.UserID,
                    LastUpdateTime = DateTime.Now,
                    IsDelete       = 0
                };
                couponUseBll.Create(couponUseEntity);

                //更新CouponType数量
                var conponTypeBll    = new CouponTypeBLL(CurrentUserInfo);
                var conponTypeEntity = conponTypeBll.QueryByEntity(new CouponTypeEntity()
                {
                    CouponTypeID = new Guid(couponEntity.CouponTypeID), CustomerId = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                conponTypeEntity.IsVoucher += 1;
                conponTypeBll.Update(conponTypeEntity);

                //停用该优惠券
                couponEntity.Status = 1;
                couponBll.Update(couponEntity);
            }

            //使用余额
            if (rp.VipEndAmountFlag == 1)
            {
                var vipAmountBll       = new VipAmountBLL(CurrentUserInfo);
                var vipAmountDetailBll = new VipAmountDetailBLL(CurrentUserInfo);

                var vipAmountEntity = vipAmountBll.QueryByEntity(new VipAmountEntity()
                {
                    VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
                }, null).FirstOrDefault();
                if (vipAmountEntity != null)
                {
                    //判断该会员账户是否被冻结
                    if (vipAmountEntity.IsLocking == 1)
                    {
                        throw new APIException("账户已被冻结,请先解冻")
                              {
                                  ErrorCode = 103
                              }
                    }
                    ;

                    //判断该会员的账户余额是否大于本次使用的余额
                    if (vipAmountEntity.EndAmount < rp.VipEndAmount)
                    {
                        throw new APIException(string.Format("账户余额不足,当前余额为【{0}】", vipAmountEntity.EndAmount))
                              {
                                  ErrorCode = 103
                              }
                    }
                    ;

                    //所剩余额大于商品价格,扣除余额的数量为商品价格
                    if (tempAmount < rp.VipEndAmount)
                    {
                        rp.VipEndAmount = endAmount = Convert.ToDecimal(tempAmount);
                    }
                }
            }
            //不使用余额,余额为0
            else
            {
                endAmount = 0;
            }
            //实付金额
            decimal transAmount = tempAmount - discountAmount;
            //支付状态
            string payStatus = "0";
            //支付时间
            DateTime?PayDatetTime = null;

            //实付金额全是由余额支付,支付状态和支付时间全部更新,积分扣减、余额扣减、优惠券使用
            if (transAmount == endAmount || transAmount == 0)
            {
                payStatus    = "10";
                PayDatetTime = DateTime.Now;
                //处理积分抵扣
                if (rp.IntegralFlag == 1)
                {
                    var    vipIntegralBll = new VipIntegralBLL(CurrentUserInfo);
                    string sourceId       = "20"; //积分抵扣
                    var    IntegralDetail = new VipIntegralDetailEntity()
                    {
                        Integral         = -Convert.ToInt32(rp.Integral),
                        IntegralSourceID = sourceId,
                        ObjectId         = orderId.ToString()
                    };
                    if (IntegralDetail.Integral != 0)
                    {
                        //变动前积分
                        string OldIntegral = (vipInfo.Integration ?? 0).ToString();
                        //变动积分
                        string ChangeIntegral      = (IntegralDetail.Integral ?? 0).ToString();
                        var    vipIntegralDetailId = vipIntegralBll.AddIntegral(ref vipInfo, unitInfo, IntegralDetail, CurrentUserInfo);
                        //发送微信积分变动通知模板消息
                        if (!string.IsNullOrWhiteSpace(vipIntegralDetailId))
                        {
                            var CommonBLL = new CommonBLL();
                            CommonBLL.PointsChangeMessage(OldIntegral, vipInfo, ChangeIntegral, vipInfo.WeiXinUserId, CurrentUserInfo);
                        }
                    }
                }
                //处理余额抵扣
                if (rp.VipEndAmountFlag == 1)
                {
                    var vipAmountBll       = new VipAmountBLL(CurrentUserInfo);
                    var vipAmountDetailBll = new VipAmountDetailBLL(CurrentUserInfo);

                    var vipAmountEntity = vipAmountBll.QueryByEntity(new VipAmountEntity()
                    {
                        VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
                    }, null).FirstOrDefault();
                    if (vipAmountEntity != null)
                    {
                        var detailInfo = new VipAmountDetailEntity()
                        {
                            Amount         = -rp.VipEndAmount,
                            AmountSourceId = "1",
                            ObjectId       = orderId.ToString()
                        };
                        var vipAmountDetailId = vipAmountBll.AddVipAmount(vipInfo, unitInfo, ref vipAmountEntity, detailInfo, CurrentUserInfo);
                        if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                        {//发送微信账户余额变动模板消息
                            var CommonBLL = new CommonBLL();
                            CommonBLL.BalanceChangedMessage(orderNo, vipAmountEntity, detailInfo, vipInfo.WeiXinUserId, vipInfo.VIPID, CurrentUserInfo);
                        }
                    }
                }
            }
            //收款订单
            ReceiveAmountOrderEntity receiveAmountOrderEntity = new ReceiveAmountOrderEntity()
            {
                OrderId             = orderId,
                OrderNo             = orderNo,
                VipId               = vipInfo.VIPID,
                ServiceUnitId       = unitInfo.unit_id,
                ServiceUserId       = rp.EmployeeID,
                TotalAmount         = rp.TotalAmount,
                VipDiscount         = discount * 100,
                TransAmount         = transAmount,
                PayPoints           = integralAmount,
                AmountFromPayPoints = rp.IntegralAmount,
                CouponUsePay        = couponAmount,
                AmountAcctPay       = endAmount,
                PayStatus           = payStatus,
                TimeStamp           = rp.TimeStamp,
                PayDatetTime        = PayDatetTime,
                CustomerId          = CurrentUserInfo.ClientID
            };
            receiveAmountOrderBll.Create(receiveAmountOrderEntity);
            //订单奖励
            if (transAmount == endAmount || transAmount == 0)
            {
                var vipIntegralBll = new VipIntegralBLL(CurrentUserInfo);
                vipIntegralBll.OrderReward(receiveAmountOrderEntity, null);
            }
            rd.orderId = orderId.ToString();
            return(rd);
        }
    }
}
Exemplo n.º 5
0
        protected override GetVipAmountDetailRD ProcessRequest(DTO.Base.APIRequest <GetVipAmountDetailRP> pRequest)
        {
            var                rd                 = new GetVipAmountDetailRD();
            var                para               = pRequest.Parameters;
            VipAmountBLL       vipAmountBLL       = new VipAmountBLL(CurrentUserInfo);
            var                vipAmountDetailBLL = new VipAmountDetailBLL(CurrentUserInfo);
            LoggingSessionInfo loggingSessionInfo = Default.GetBSLoggingSession(pRequest.CustomerID, pRequest.UserID);
            //查询参数
            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
            };

            //商户条件
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "a.VipID", Value = CurrentUserInfo.UserID
            });
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "a.VipCardCode", Value = para.VipCardCode
            });
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "a.CustomerId", Value = loggingSessionInfo.ClientID
            });

            if (para.Type == 1) //余额
            {
                complexCondition.Add(new DirectCondition(" a.AmountSourceId NOT IN (36,35,20) "));
                complexCondition.Add(new DirectCondition(" a.AmountSourceId > 0 "));
            }
            else if (para.Type == 2) //返现
            {
                complexCondition.Add(new DirectCondition(" a.AmountSourceId in (2,3,13,16,22,24)"));
            }

            #region 正常余额
            //排序参数
            List <OrderBy> lstOrder = new List <OrderBy> {
            };
            lstOrder.Add(new OrderBy()
            {
                FieldName = "a.CreateTime", Direction = OrderByDirections.Desc
            });

            var tempList = vipAmountDetailBLL.GetVipAmountDetailList(complexCondition.ToArray(), lstOrder.ToArray(), para.PageSize, para.PageIndex + 1);
            rd.TotalCount          = tempList.RowCount;
            rd.TotalPageCount      = tempList.PageCount;
            rd.VipAmountDetailList = tempList.Entities.Select(t => new VipAmountDetailInfo()
            {
                AmountSourceName = t.AmountSourceName,
                Amount           = t.Amount.Value,
                CreateTime       = t.CreateTime.Value.ToString("yyyy-MM-dd")
            }).ToArray();
            #endregion

            #region 统计信息
            //查询当前余额/返现
            rd.CurrentAmount = 0; //当前余额/返现(默认值)
            var vipAmountInfo = vipAmountBLL.QueryByEntity(new VipAmountEntity()
            {
                VipId = pRequest.UserID, VipCardCode = para.VipCardCode
            }, null).FirstOrDefault();

            if (vipAmountInfo != null)
            {
                if (para.Type == 1) //当前余额
                {
                    rd.CurrentAmount = vipAmountInfo.EndAmount.Value;
                }
                else if (para.Type == 2) //返现
                {
                    rd.CurrentAmount = vipAmountInfo.ValidReturnAmount.Value;
                }

                decimal[] array = vipAmountBLL.GetVipSumAmountByCondition(pRequest.UserID, CurrentUserInfo.ClientID, false);
                rd.OutAmount = -Convert.ToDecimal(array[2]); //支出余额
            }
            #endregion
            return(rd);
        }
Exemplo n.º 6
0
        protected override EmptyResponseData ProcessRequest(DTO.Base.APIRequest <SetSalesReturnRP> pRequest)
        {
            var rd   = new EmptyResponseData();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;
            var salesReturnBLL     = new T_SalesReturnBLL(loggingSessionInfo);
            var historyBLL         = new T_SalesReturnHistoryBLL(loggingSessionInfo);
            var refundOrderBLL     = new T_RefundOrderBLL(loggingSessionInfo);

            var inoutBLL     = new T_InoutBLL(loggingSessionInfo);
            var inoutService = new InoutService(loggingSessionInfo);

            var vipAmountBLL   = new VipAmountBLL(loggingSessionInfo);   //余额返现BLL实例化
            var vipIntegralBLL = new VipIntegralBLL(loggingSessionInfo); //积分BLL实例化

            var pTran = salesReturnBLL.GetTran();                        //事务
            T_SalesReturnEntity        salesReturnEntity = null;
            T_SalesReturnHistoryEntity historyEntity     = null;

            T_RefundOrderEntity refundEntity = null;

            var          vipBll     = new VipBLL(loggingSessionInfo);    //会员BLL实例化
            var          userBll    = new T_UserBLL(loggingSessionInfo); //店员BLL实例化
            T_UserEntity userEntity = null;                              //店员信息
            var          unitBLL    = new t_unitBLL(loggingSessionInfo);

            salesReturnEntity = salesReturnBLL.GetByID(para.SalesReturnID);
            //获取订单信息
            var inoutInfo = inoutBLL.GetInoutInfo(salesReturnEntity.OrderID, loggingSessionInfo);
            //获取会员信息
            var vipInfo = vipBll.GetByID(inoutInfo.vip_no);
            //获取门店信息
            t_unitEntity unitInfo = null;

            if (!string.IsNullOrEmpty(inoutInfo.sales_unit_id))
            {
                unitInfo = unitBLL.GetByID(inoutInfo.sales_unit_id);
            }
            userEntity = userBll.GetByID(loggingSessionInfo.UserID);
            using (pTran.Connection)
            {
                try
                {
                    switch (para.OperationType)
                    {
                    case 1:
                        #region 审核通过
                        salesReturnEntity.Status = 4;    //审核通过

                        #region 计算应退金额
                        decimal payable = 0;       //计算后应退金额

                        //根据订单ID获取订单明细[复用]
                        DataRow drItem     = inoutService.GetOrderDetailByOrderId(salesReturnEntity.OrderID).Tables[0].Select(" item_id= '" + salesReturnEntity.ItemID + "'").FirstOrDefault();
                        decimal salesPrice = Convert.ToDecimal(drItem["enter_price"]);
                        if (inoutInfo != null)
                        {
                            //订单总金额-运费
                            decimal tempAmount = inoutInfo.total_amount.Value - inoutInfo.DeliveryAmount;
                            //计算会员折扣
                            decimal discount = 1;
                            if (inoutInfo.discount_rate.Value > 0)
                            {
                                discount = inoutInfo.discount_rate.Value / 100;
                            }
                            //计算后应退金额
                            //payable = (((tempAmount - inoutInfo.CouponAmount) * discount) / tempAmount) * (salesPrice * salesReturnEntity.ActualQty.Value);
                            //公式:比例 =(应付金额 * 会员折扣 - 优惠券)/ 应付金额
                            //      应退金额 = 退货数量 * 销售价 * 比例
                            payable = ((tempAmount * discount - inoutInfo.CouponAmount) / tempAmount) * (salesPrice * salesReturnEntity.ActualQty.Value);
                        }
                        salesReturnEntity.RefundAmount  = payable;      //应退金额
                        salesReturnEntity.ConfirmAmount = payable;      //实退金额,默认为应退金额,可支持修改
                        #endregion

                        salesReturnBLL.Update(salesReturnEntity, pTran);

                        historyEntity = new T_SalesReturnHistoryEntity()
                        {
                            SalesReturnID = salesReturnEntity.SalesReturnID,
                            OperationType = 4,
                            OperationDesc = "审核",
                            OperatorID    = loggingSessionInfo.UserID,
                            HisRemark     = "您的服务单已审核通过,请将商品寄回",
                            OperatorName  = userEntity.user_name,
                            OperatorType  = 1
                        };
                        historyBLL.Create(historyEntity, pTran);

                        #endregion
                        break;

                    case 2:
                        #region 审核不通过
                        salesReturnEntity.Status = 3;    //审核不通过
                        salesReturnBLL.Update(salesReturnEntity, pTran);

                        historyEntity = new T_SalesReturnHistoryEntity()
                        {
                            SalesReturnID = salesReturnEntity.SalesReturnID,
                            OperationType = 3,
                            OperationDesc = "审核",
                            OperatorID    = loggingSessionInfo.UserID,
                            HisRemark     = para.Desc,
                            OperatorName  = userEntity.user_name,
                            OperatorType  = 1
                        };
                        historyBLL.Create(historyEntity, pTran);
                        break;

                        #endregion
                    case 3:
                        #region 确认收货
                        salesReturnEntity.Status = 6;    //确认收货
                        salesReturnBLL.Update(salesReturnEntity, pTran);

                        historyEntity = new T_SalesReturnHistoryEntity()
                        {
                            SalesReturnID = salesReturnEntity.SalesReturnID,
                            OperationType = 6,
                            OperationDesc = "收货",
                            OperatorID    = loggingSessionInfo.UserID,
                            HisRemark     = "您的服务单" + salesReturnEntity.SalesReturnNo + "的商品已经收到",
                            OperatorName  = userEntity.user_name,
                            OperatorType  = 1
                        };
                        historyBLL.Create(historyEntity, pTran);
                        //退货时生成退款单
                        if (salesReturnEntity.ServicesType == 1)
                        {
                            refundEntity = new T_RefundOrderEntity();
                            refundEntity.SalesReturnID = salesReturnEntity.SalesReturnID;
                            refundEntity.RefundNo      = DateTime.Now.ToString("yyyyMMddhhmmfff");
                            refundEntity.VipID         = salesReturnEntity.VipID;
                            refundEntity.DeliveryType  = salesReturnEntity.DeliveryType;
                            refundEntity.OrderID       = salesReturnEntity.OrderID;
                            refundEntity.ItemID        = salesReturnEntity.ItemID;
                            refundEntity.SkuID         = salesReturnEntity.SkuID;
                            refundEntity.Qty           = salesReturnEntity.Qty;
                            refundEntity.ActualQty     = salesReturnEntity.ActualQty;
                            refundEntity.UnitID        = salesReturnEntity.UnitID;
                            refundEntity.UnitName      = salesReturnEntity.UnitName;
                            refundEntity.UnitTel       = salesReturnEntity.UnitTel;
                            refundEntity.Address       = salesReturnEntity.Address;
                            refundEntity.Contacts      = salesReturnEntity.Contacts;
                            refundEntity.Phone         = salesReturnEntity.Phone;
                            refundEntity.RefundAmount  = salesReturnEntity.RefundAmount;        //退款金额
                            refundEntity.ConfirmAmount = salesReturnEntity.ConfirmAmount;       //确认退款金额

                            #region 计算应退现金金额、余额、积分、返现
                            var inoutDetail = inoutBLL.GetInoutInfo(salesReturnEntity.OrderID, loggingSessionInfo);
                            if (inoutDetail != null)
                            {
                                //订单实付金额-运费 >= 应退金额
                                if (inoutDetail.actual_amount - inoutDetail.DeliveryAmount >= salesReturnEntity.ConfirmAmount)
                                {
                                    refundEntity.ActualRefundAmount = salesReturnEntity.ConfirmAmount;
                                }
                                //订单实付金额-运费+余额抵扣 >= 应退金额
                                else if (inoutDetail.actual_amount - inoutDetail.DeliveryAmount + inoutDetail.VipEndAmount >= salesReturnEntity.ConfirmAmount)
                                {
                                    refundEntity.ActualRefundAmount = inoutDetail.actual_amount - inoutDetail.DeliveryAmount;     //实付金额
                                    //refundEntity.Amount = salesReturnEntity.ConfirmAmount - inoutDetail.actual_amount;  //退回余额
                                    refundEntity.Amount = salesReturnEntity.ConfirmAmount - refundEntity.ActualRefundAmount;      //退回余额
                                }
                                //订单实付金额-运费+余额抵扣+积分抵扣 >= 应退金额
                                else if (inoutDetail.actual_amount - inoutDetail.DeliveryAmount + inoutDetail.VipEndAmount + inoutDetail.IntegralAmount >= salesReturnEntity.ConfirmAmount)
                                {
                                    refundEntity.ActualRefundAmount = inoutDetail.actual_amount - inoutDetail.DeliveryAmount; //实付金额
                                    refundEntity.Amount             = inoutDetail.VipEndAmount;                               //退回余额
                                    //退回积分抵扣金额
                                    refundEntity.PointsAmount = salesReturnEntity.ConfirmAmount.Value - (inoutDetail.actual_amount.Value - inoutDetail.DeliveryAmount) - inoutDetail.VipEndAmount;
                                    //退回积分
                                    refundEntity.Points = (int)Math.Round(refundEntity.PointsAmount.Value * (inoutDetail.pay_points.Value / inoutDetail.IntegralAmount), 1);
                                }
                                else                                                                                    //订单实付金额-运费+余额抵扣+积分抵扣 < 应退金额
                                {
                                    refundEntity.Points             = (int)Math.Round(inoutDetail.pay_points.Value, 1); //退回积分
                                    refundEntity.PointsAmount       = inoutDetail.IntegralAmount;                       //退回积分抵扣金额
                                    refundEntity.Amount             = inoutDetail.VipEndAmount;                         //退回余额
                                    refundEntity.ActualRefundAmount = salesReturnEntity.ConfirmAmount;                  //实付金额
                                }
                                //订单实付金额-运费+余额抵扣+积分抵扣 >= 应退金额
                                //取消返现
                                //else if (inoutDetail.actual_amount - inoutDetail.DeliveryAmount + inoutDetail.VipEndAmount + inoutDetail.IntegralAmount + inoutDetail.ReturnAmount >= salesReturnEntity.ConfirmAmount)
                                //{
                                //    refundEntity.ActualRefundAmount = inoutDetail.actual_amount - inoutDetail.DeliveryAmount;//实付金额
                                //    refundEntity.Amount = inoutDetail.VipEndAmount;             //退回余额
                                //    refundEntity.Points = (int)Math.Round(inoutDetail.pay_points.Value, 1);//退回积分
                                //    refundEntity.PointsAmount = inoutDetail.IntegralAmount;       //退回积分抵扣金额
                                //    //退回的返现
                                //    refundEntity.ReturnAmount = salesReturnEntity.ConfirmAmount.Value - (inoutDetail.actual_amount.Value - inoutDetail.DeliveryAmount) - inoutDetail.VipEndAmount - inoutDetail.IntegralAmount;
                                //}
                            }
                            #endregion

                            refundEntity.Status     = 1;      //待退款
                            refundEntity.CustomerID = loggingSessionInfo.ClientID;
                            refundOrderBLL.Create(refundEntity, pTran);

                            var vipAmountEntity = vipAmountBLL.QueryByEntity(new VipAmountEntity()
                            {
                                VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
                            }, null).FirstOrDefault();

                            //退货返回余额
                            if (refundEntity.Amount > 0)
                            {
                                //变更余额和余额记录
                                var detailInfo = new VipAmountDetailEntity()
                                {
                                    Amount         = refundEntity.Amount.Value,
                                    AmountSourceId = "21",
                                    ObjectId       = refundEntity.RefundID.ToString()
                                };
                                var vipAmountDetailId = vipAmountBLL.AddVipAmount(vipInfo, unitInfo, ref vipAmountEntity, detailInfo, pTran, loggingSessionInfo);
                                if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                                {    //发送微信账户余额变动模板消息
                                    var CommonBLL = new CommonBLL();
                                    CommonBLL.BalanceChangedMessage(inoutInfo.order_no, vipAmountEntity, detailInfo, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                                }
                            }
                            //退货返回返现
                            if (refundEntity.ReturnAmount > 0)
                            {
                                var detailInfo = new VipAmountDetailEntity()
                                {
                                    Amount         = refundEntity.ReturnAmount.Value,
                                    ObjectId       = refundEntity.RefundID.ToString(),
                                    AmountSourceId = "22"
                                };
                                var vipAmountDetailId = vipAmountBLL.AddReturnAmount(vipInfo, unitInfo, vipAmountEntity, ref detailInfo, pTran, loggingSessionInfo);
                                if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                                {    //发送返现到账通知微信模板消息
                                    var CommonBLL = new CommonBLL();
                                    CommonBLL.CashBackMessage(salesReturnEntity.OrderNo, detailInfo.Amount, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                                }
                            }
                            //退货返回积分
                            if (refundEntity.Points > 0)
                            {
                                var IntegralDetail = new VipIntegralDetailEntity()
                                {
                                    Integral         = refundEntity.Points.Value,
                                    IntegralSourceID = "26",
                                    ObjectId         = refundEntity.RefundID.ToString()
                                };

                                if (IntegralDetail.Integral != 0)
                                {
                                    //变动前积分
                                    string OldIntegral = (vipInfo.Integration ?? 0).ToString();
                                    //变动积分
                                    string ChangeIntegral      = (IntegralDetail.Integral ?? 0).ToString();
                                    var    vipIntegralDetailId = vipIntegralBLL.AddIntegral(ref vipInfo, unitInfo, IntegralDetail, pTran, loggingSessionInfo);
                                    //发送微信积分变动通知模板消息
                                    if (!string.IsNullOrWhiteSpace(vipIntegralDetailId))
                                    {
                                        var CommonBLL = new CommonBLL();
                                        CommonBLL.PointsChangeMessage(OldIntegral, vipInfo, ChangeIntegral, vipInfo.WeiXinUserId, loggingSessionInfo);
                                    }
                                }
                            }
                            //确认收货时退回订单奖励积分、返现和佣金
                            vipIntegralBLL.CancelReward(inoutInfo, vipInfo, pTran);
                        }
                        #endregion
                        break;

                    case 4:
                        #region 拒绝收货
                        salesReturnEntity.Status = 5;    //拒绝收货
                        salesReturnBLL.Update(salesReturnEntity, pTran);

                        historyEntity = new T_SalesReturnHistoryEntity()
                        {
                            SalesReturnID = salesReturnEntity.SalesReturnID,
                            OperationType = 5,
                            OperationDesc = "收货",
                            OperatorID    = loggingSessionInfo.UserID,
                            HisRemark     = para.Desc,
                            OperatorName  = userEntity.user_name,
                            OperatorType  = 1
                        };
                        historyBLL.Create(historyEntity, pTran);
                        #endregion
                        break;

                    case 5:
                        #region 修改信息
                        if (para.ServicesType > 0)     //修改服务方式
                        {
                            salesReturnEntity.ServicesType = para.ServicesType;
                            string servicesTypeDesc = para.ServicesType == 1 ? "退货" : "换货";
                            historyEntity = new T_SalesReturnHistoryEntity()
                            {
                                SalesReturnID = salesReturnEntity.SalesReturnID,
                                OperationType = 11,
                                OperationDesc = "修改信息",
                                OperatorID    = loggingSessionInfo.UserID,
                                HisRemark     = "修改服务方式为" + servicesTypeDesc,
                                OperatorName  = userEntity.user_name,
                                OperatorType  = 1,
                                IsDelete      = 1
                            };
                            historyBLL.Create(historyEntity, pTran);
                        }
                        if (para.ActualQty > 0)    //修改申请数量
                        {
                            salesReturnEntity.ActualQty = para.ActualQty;
                            historyEntity = new T_SalesReturnHistoryEntity()
                            {
                                SalesReturnID = salesReturnEntity.SalesReturnID,
                                OperationType = 11,
                                OperationDesc = "修改信息",
                                OperatorID    = loggingSessionInfo.UserID,
                                HisRemark     = "修改确认退货数量为" + para.ActualQty,
                                OperatorName  = userEntity.user_name,
                                OperatorType  = 1,
                                IsDelete      = 1
                            };
                            historyBLL.Create(historyEntity, pTran);
                        }
                        if (para.ConfirmAmount >= 0)    //处理实退金额
                        {
                            salesReturnEntity.ConfirmAmount = para.ConfirmAmount;

                            historyEntity = new T_SalesReturnHistoryEntity()
                            {
                                SalesReturnID = salesReturnEntity.SalesReturnID,
                                OperationType = 13,
                                OperationDesc = "修改信息",
                                OperatorID    = loggingSessionInfo.UserID,
                                HisRemark     = "修改实退金额为" + para.ConfirmAmount,
                                OperatorName  = userEntity.user_name,
                                OperatorType  = 1,
                                IsDelete      = 1
                            };
                            historyBLL.Create(historyEntity, pTran);
                        }
                        salesReturnBLL.Update(salesReturnEntity, pTran);
                        #endregion
                        break;

                    case 6:
                        #region 取消
                        salesReturnEntity.Status = 2;    //取消申请
                        salesReturnBLL.Update(salesReturnEntity, pTran);
                        historyEntity = new T_SalesReturnHistoryEntity()
                        {
                            SalesReturnID = salesReturnEntity.SalesReturnID,
                            OperationType = 2,
                            OperationDesc = "取消申请",
                            OperatorID    = CurrentUserInfo.UserID,
                            HisRemark     = para.Desc,
                            OperatorName  = userEntity.user_name,
                            OperatorType  = 0
                        };
                        historyBLL.Create(historyEntity, pTran);
                        #endregion
                        break;

                    default:
                        break;
                    }
                    pTran.Commit();  //提交事物
                }
                catch (Exception ex)
                {
                    pTran.Rollback();//回滚事务
                    throw new APIException(ex.Message);
                }
            }
            return(rd);
        }
Exemplo n.º 7
0
        protected override GetRechargeActivityListRD ProcessRequest(DTO.Base.APIRequest <GetRechargeActivityListRP> pRequest)
        {
            var rd   = new GetRechargeActivityListRD();
            var para = pRequest.Parameters;
            LoggingSessionInfo loggingSessionInfo = Default.GetBSLoggingSession(pRequest.CustomerID, pRequest.UserID);
            var vipBLL               = new VipBLL(loggingSessionInfo);
            var vipIntegralBLL       = new VipIntegralBLL(loggingSessionInfo);
            var sysVipCardTypeBLL    = new SysVipCardTypeBLL(loggingSessionInfo);
            var vipCardVipMappingBLL = new VipCardVipMappingBLL(loggingSessionInfo);
            var vipCardBLL           = new VipCardBLL(loggingSessionInfo);
            var vipCardRuleBLL       = new VipCardRuleBLL(loggingSessionInfo);
            var vipAmountBLL         = new VipAmountBLL(loggingSessionInfo);
            //获取当前会员卡等级
            VipEntity VipInfo         = null;
            int?      CurVipCardLevel = 0;

            VipInfo = vipBLL.GetByID(para.VipID);
            if (VipInfo != null)
            {
                rd.HeadImgUrl = VipInfo.HeadImgUrl == null ? "" : VipInfo.HeadImgUrl;
                rd.VipName    = VipInfo.VipName != null ? VipInfo.VipName : VipInfo.VipRealName != null ? VipInfo.VipRealName : "";
                //获取当前会员积分信息
                //var vipIntegralInfo = vipIntegralBLL.QueryByEntity(new VipIntegralEntity() { VipID = para.VipID, VipCardCode = VipInfo.VipCode }, null).FirstOrDefault();
                //if (vipIntegralInfo != null)
                //{
                //    rd.Integration = vipIntegralInfo.ValidIntegral != null ? vipIntegralInfo.ValidIntegral.Value : 0;
                //}
                //获取当前会员余额信息
                var vipAmountInfo = vipAmountBLL.QueryByEntity(new VipAmountEntity()
                {
                    VipId = para.VipID, VipCardCode = VipInfo.VipCode
                }, null).FirstOrDefault();
                if (vipAmountInfo != null)
                {
                    rd.VipAmount = vipAmountInfo.EndAmount != null ? vipAmountInfo.EndAmount : 0;
                }
                else
                {
                    rd.VipAmount = 0;
                }
                //获取当前关联信息
                var vipCardMappingInfo = vipCardVipMappingBLL.QueryByEntity(new VipCardVipMappingEntity()
                {
                    VIPID = para.VipID, CustomerID = loggingSessionInfo.ClientID
                },
                                                                            new OrderBy[] { new OrderBy()
                                                                                            {
                                                                                                FieldName = "CreateTime", Direction = OrderByDirections.Desc
                                                                                            } }).FirstOrDefault();
                if (vipCardMappingInfo != null)
                {
                    //获取卡等级主标识信息
                    var vipCardInfo = vipCardBLL.QueryByEntity(new VipCardEntity()
                    {
                        VipCardID = vipCardMappingInfo.VipCardID, VipCardStatusId = 1
                    }, null).FirstOrDefault();
                    if (vipCardInfo != null)
                    {
                        //获取卡等级信息
                        var vipCardTypeInfo = sysVipCardTypeBLL.QueryByEntity(new SysVipCardTypeEntity()
                        {
                            VipCardTypeID = vipCardInfo.VipCardTypeID
                        }, null).FirstOrDefault();
                        if (vipCardTypeInfo != null)
                        {
                            rd.VipCardTypeName = vipCardTypeInfo.VipCardTypeName != null ? vipCardTypeInfo.VipCardTypeName : "";
                            CurVipCardLevel    = vipCardTypeInfo.VipCardLevel;
                        }
                        //获取充值活动列表
                        var rechargeStrategyBLL  = new RechargeStrategyBLL(loggingSessionInfo);
                        var RechargeActivityInfo = rechargeStrategyBLL.GetRechargeActivityList(loggingSessionInfo.ClientID, vipCardInfo.VipCardTypeID.ToString(), 3);
                        if (RechargeActivityInfo != null && RechargeActivityInfo.Tables[0].Rows.Count > 0)
                        {
                            rd.RechargeStrategyList = DataTableToObject.ConvertToList <RechargeStrategyInfo>(RechargeActivityInfo.Tables[0]);
                        }
                    }
                }
            }
            return(rd);
        }
Exemplo n.º 8
0
        protected override GetVIPCardRD ProcessRequest(DTO.Base.APIRequest <GetVIPCardRP> pRequest)
        {
            GetVIPCardRD Data = new GetVIPCardRD();
            var          rd   = new GetVIPCardListRD();
            var          para = pRequest.Parameters;
            var          loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;

            #region 业务对象
            //会员卡
            var VipCardBLL = new VipCardBLL(loggingSessionInfo);
            //会员
            var VipBLL = new VipBLL(loggingSessionInfo);
            //卡状态变更记录
            var VipCardStatusChangeLogBLL = new VipCardStatusChangeLogBLL(loggingSessionInfo);
            //卡与Vip关系
            var VipCardVipMappingBLL = new VipCardVipMappingBLL(loggingSessionInfo);
            //门店
            var unitBll = new t_unitBLL(loggingSessionInfo);
            //员工
            var UserBLL = new T_UserBLL(loggingSessionInfo);
            //卡类型
            var SysVipCardTypeBLL = new SysVipCardTypeBLL(loggingSessionInfo);
            //商户配置
            var CustomerBasicSettingBLL = new CustomerBasicSettingBLL(loggingSessionInfo);
            //积分
            var VipIntegralBLL = new VipIntegralBLL(loggingSessionInfo);
            #endregion



            #region 会员卡
            VipCardEntity resultData = null;
            if (!string.IsNullOrWhiteSpace(para.VipID))
            {
                //会员编号获取详情
                VipCardVipMappingEntity m_VipMappingData = VipCardVipMappingBLL.QueryByEntity(new VipCardVipMappingEntity()
                {
                    VIPID = para.VipID
                }, null).FirstOrDefault();
                if (m_VipMappingData != null && !string.IsNullOrWhiteSpace(m_VipMappingData.VipCardID))
                {
                    resultData = VipCardBLL.GetByID(para.VipCardID);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(para.VipCardID))
                {
                    //卡ID获取详情
                    resultData = VipCardBLL.GetByID(para.VipCardID);
                }
                else
                {
                    //刷卡获取详情
                    List <IWhereCondition> complexCondition = new List <IWhereCondition> {
                    };
                    if (!string.IsNullOrEmpty(para.VipCardISN))
                    {
                        complexCondition.Add(new DirectCondition("VipCardCode='" + para.VipCardISN + "' or VipCardISN='" + para.VipCardISN.ToString() + "' "));
                    }
                    resultData = VipCardBLL.Query(complexCondition.ToArray(), null).FirstOrDefault();
                }
            }

            //try
            //{
            //    if (resultData == null)
            //        throw new APIException("该卡不存在!") { ErrorCode = ERROR_CODES.INVALID_BUSINESS };
            //}
            //catch (APIException apiEx)
            //{
            //    throw new APIException(apiEx.ErrorCode, apiEx.Message);
            //}
            #endregion

            #region 卡关系
            VipCardVipMappingEntity VipCardVipMappingData = null;
            if (resultData != null)
            {
                VipCardVipMappingData = VipCardVipMappingBLL.QueryByEntity(new VipCardVipMappingEntity()
                {
                    VipCardID = resultData.VipCardID
                }, null).FirstOrDefault();
            }
            //else
            //{
            //    return Data;
            //}
            #endregion

            #region 门店
            t_unitEntity unidData = null;
            if (resultData != null && !string.IsNullOrWhiteSpace(resultData.MembershipUnit))
            {
                unidData = unitBll.GetByID(resultData.MembershipUnit);
            }
            #endregion

            #region 会员,积分

            VipEntity         VipData      = null;
            VipIntegralEntity IntegralData = null;
            //string VIPID = VipCardVipMappingData == null ? "" : VipCardVipMappingData.VIPID;
            string VIPID = para.VipID;
            if (!string.IsNullOrWhiteSpace(VIPID))
            {
                VipData = VipBLL.NewGetByID(VIPID);
                //IntegralData = VipIntegralBLL.GetByID(VIPID);
                IntegralData = VipIntegralBLL.QueryByEntity(new VipIntegralEntity()
                {
                    VipID = VipData.VIPID, VipCardCode = VipData.VipCode
                }, null).FirstOrDefault();
            }
            #endregion

            #region 员工
            T_UserEntity UserData = null;
            if (resultData != null && !string.IsNullOrWhiteSpace(resultData.CreateBy))
            {
                UserData = UserBLL.GetByID(resultData.CreateBy);
            }
            #endregion

            #region 响应对象赋值
            if (resultData != null)
            {
                //卡
                Data.VipCardID      = resultData.VipCardID;
                Data.VipCardCode    = resultData.VipCardCode;
                Data.VipCardISN     = resultData.VipCardISN;
                Data.CraeteUserName = UserData == null ? "" : UserData.user_name;

                Data.VipCardStatusId    = resultData.VipCardStatusId.Value;
                Data.MembershipTime     = resultData.MembershipTime == null ? "" : resultData.MembershipTime.Value.ToString("yyyy-MM-dd");
                Data.MembershipUnitName = unidData == null ? "" : unidData.unit_name;
                //Data.TotalAmount = resultData.RechargeTotalAmount == null ? 0 : resultData.RechargeTotalAmount.Value;
                //Data.BalanceAmount = resultData.BalanceAmount == null ? 0 : resultData.BalanceAmount.Value;
                Data.BeginDate     = resultData.BeginDate;
                Data.EndDate       = "永久有效";
                Data.SalesUserName = resultData.SalesUserName == null ? "" : resultData.SalesUserName;
                #region 卡类型名称
                SysVipCardTypeEntity SysVipCardTypeData = SysVipCardTypeBLL.GetByID(resultData.VipCardTypeID);
                Data.VipCardName = SysVipCardTypeData == null ? "" : SysVipCardTypeData.VipCardTypeName;
                #endregion

                #region 状态变更记录列表

                var VipCardStatusChangeLogArray = VipCardStatusChangeLogBLL.Query
                                                      (new IWhereCondition[] { new EqualsCondition()
                                                                               {
                                                                                   FieldName = "VipCardID", Value = resultData.VipCardID
                                                                               } },
                                                      new OrderBy[] { new OrderBy()
                                                                      {
                                                                          FieldName = "CreateTime", Direction = OrderByDirections.Desc
                                                                      } }).ToList();
                //转换业务对象
                Data.StatusLogList = (from t in VipCardStatusChangeLogArray
                                      select new VipCardStatusChangeLog()
                {
                    CreateTime = t.CreateTime.Value.ToString("yyyy-MM-dd"),
                    UnitName = t.UnitName == null ? "" : t.UnitName,
                    Action = t.Action == null ? "" : t.Action,
                    ChangeReason = t.Reason == null ? "" : t.Reason,
                    Remark = t.Remark == null ? "" : t.Remark,
                    CreateBy = t.CreateByName,
                    ImageUrl = t.PicUrl == null ? "" : t.PicUrl
                }).ToList();
                #endregion
            }
            #region 会员
            if (VipData != null)
            {
                Data.VipID   = VipData.VIPID;
                Data.VipCode = VipData.VipCode;
                if (Data.VipCardCode == null)
                {
                    Data.VipCardCode = VipData.VipCode;
                }
                if (!string.IsNullOrWhiteSpace(VipData.VipRealName))
                {
                    Data.VipName = VipData.VipRealName;
                }
                else
                {
                    Data.VipName = VipData.VipName ?? "";
                }
                Data.Phone    = VipData.Phone;
                Data.Birthday = VipData.Birthday == null ? "" : VipData.Birthday;
                Data.Gender   = VipData.Gender ?? 0;
                //Data.Integration = VipData.Integration == null ? 0 : VipData.Integration.Value;
                //会员创建人姓名
                T_UserEntity VipUserData = null;
                if (resultData != null && !string.IsNullOrWhiteSpace(resultData.CreateBy))
                {
                    VipUserData = UserBLL.GetByID(resultData.CreateBy);
                }
                Data.VipCreateByName = VipUserData == null ? "" : VipUserData.user_name;
                Data.IDNumber        = VipData.IDNumber == null ? "" : VipData.IDNumber;

                #region 会员生日是否可修改字段赋值
                //Col22 字段赋值
                ////CustomerBasicSettingEntity SettingData = CustomerBasicSettingBLL.QueryByEntity(new CustomerBasicSettingEntity() { SettingCode = "FSR_NotTwoUpdateVipBirthday" }, null).FirstOrDefault();
                ////if (SettingData != null)
                Data.Col22 = VipData.Col22 == null ? "Y" : VipData.Col22;
                #endregion
            }
            #endregion

            #region 积分
            if (IntegralData != null)
            {
                Data.Integration        = IntegralData.ValidIntegral != null ? IntegralData.ValidIntegral.Value : 0;
                Data.CumulativeIntegral = IntegralData.CumulativeIntegral != null ? IntegralData.CumulativeIntegral.Value : 0;
            }
            #endregion

            #region 余额和返现
            var vipAmountBLL  = new VipAmountBLL(loggingSessionInfo);
            var vipAmountInfo = vipAmountBLL.QueryByEntity(new VipAmountEntity()
            {
                VipId = VipData.VIPID, VipCardCode = VipData.VipCode
            }, null).FirstOrDefault();
            if (vipAmountInfo != null)
            {
                Data.TotalAmount       = vipAmountInfo.TotalAmount == null ? 0 : vipAmountInfo.TotalAmount.Value;
                Data.BalanceAmount     = vipAmountInfo.EndAmount == null ? 0 : vipAmountInfo.EndAmount.Value;
                Data.ValidReturnAmount = vipAmountInfo.ValidReturnAmount == null ? 0 : vipAmountInfo.ValidReturnAmount.Value;
                Data.TotalReturnAmount = vipAmountInfo.TotalReturnAmount == null ? 0 : vipAmountInfo.TotalReturnAmount.Value;
            }
            #endregion


            #endregion
            return(Data);
        }
Exemplo n.º 9
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            var OrderID     = context.Request["OrderID"];
            var OrderStatus = context.Request["OrderStatus"];
            var CustomerID  = context.Request["CustomerID"];
            var UserID      = context.Request["UserID"];
            var ChannelID   = context.Request["ChannelID"];
            var SerialPay   = context.Request["SerialPay"];

            try
            {
                if (string.IsNullOrEmpty(OrderID) || string.IsNullOrEmpty(OrderStatus) || string.IsNullOrEmpty(CustomerID) || string.IsNullOrEmpty(UserID) || string.IsNullOrEmpty(ChannelID))
                {
                    throw new Exception("参数不全:OrderID,OrderStatus,CustomerID,UserID");
                }
                else
                {
                    if (OrderStatus == "2")
                    {
                        //支付成功,更新卡的支付状态
                        //OrderID就是VIPCardID
                        //
                        //var rp = pRequest.DeserializeJSONTo<APIRequest<SetVipCardRP>>();

                        //if (string.IsNullOrEmpty(rp.Parameters.PayID))
                        //{
                        //    throw new APIException("缺少参数【PayID】或参数值为空") { ErrorCode = 135 };
                        //}
                        var loggingSessionInfo = Default.GetBSLoggingSession(CustomerID, UserID);
                        //会员
                        var vipBll               = new VipBLL(loggingSessionInfo);
                        var vipAmountBll         = new VipAmountBLL(loggingSessionInfo);
                        var vipCardVipMappingBll = new VipCardVipMappingBLL(loggingSessionInfo);
                        //支付
                        var tPaymentTypeCustomerMappingBll = new TPaymentTypeCustomerMappingBLL(loggingSessionInfo);
                        var tPaymentTypeBll  = new T_Payment_TypeBLL(loggingSessionInfo);
                        var paymentDetailBll = new T_Payment_detailBLL(loggingSessionInfo);
                        //门店
                        var unitBLL = new t_unitBLL(loggingSessionInfo);
                        //商品订单支付
                        //更新积分和状态
                        //var loggingSessionInfo = Default.GetBSLoggingSession(CustomerID, "1");
                        var inoutBll = new T_InoutBLL(loggingSessionInfo);//订单业务对象实例化

                        var trrBll = new T_RewardRecordBLL(loggingSessionInfo);
                        //辨别打赏订单
                        var rewardOrderPrefix = "REWARD|";
                        if (OrderID.Contains(rewardOrderPrefix))
                        {
                            OrderID = OrderID.Substring(rewardOrderPrefix.Length, OrderID.Length - rewardOrderPrefix.Length);
                            var trrEntity = trrBll.GetByID(OrderID);
                            trrEntity.PayStatus      = 2;
                            trrEntity.LastUpdateTime = DateTime.Now;
                            trrEntity.LastUpdateBy   = loggingSessionInfo.UserID;
                            trrBll.Update(trrEntity);

                            #region 员工余额变更--需要独立出来处理
                            var userAmountBll = new VipAmountBLL(loggingSessionInfo);                                 //作为员工余额使用
                            var employeeId    = trrEntity.RewardedOP;
                            var rewardAmount  = trrEntity.RewardAmount == null ? 0 : (decimal)trrEntity.RewardAmount; //转为非null的decimal类型
                            //门店
                            var unitService = new UnitService(loggingSessionInfo);
                            var unitInfo    = unitService.GetUnitByUser(CustomerID, employeeId).FirstOrDefault();//获取员工所属门店

                            var tran = userAmountBll.GetTran();
                            using (tran.Connection)//事务
                            {
                                try
                                {
                                    var userAmountEntity = userAmountBll.GetByID(trrEntity.RewardedOP);
                                    if (userAmountEntity == null)
                                    {
                                        //创建
                                        userAmountEntity = new VipAmountEntity
                                        {
                                            VipId                  = employeeId,//员工ID
                                            VipCardCode            = string.Empty,
                                            BeginAmount            = 0,
                                            InAmount               = rewardAmount,
                                            OutAmount              = 0,
                                            EndAmount              = rewardAmount,
                                            TotalAmount            = rewardAmount,
                                            BeginReturnAmount      = 0,
                                            InReturnAmount         = 0,
                                            OutReturnAmount        = 0,
                                            ReturnAmount           = 0,
                                            ImminentInvalidRAmount = 0,
                                            InvalidReturnAmount    = 0,
                                            ValidReturnAmount      = 0,
                                            TotalReturnAmount      = 0,
                                            IsLocking              = 0,
                                            CustomerID             = CustomerID
                                        };
                                        userAmountBll.Create(userAmountEntity, tran);//创建员工余额表
                                    }
                                    else
                                    {
                                        //修改
                                        if (rewardAmount > 0)
                                        {
                                            userAmountEntity.InAmount    = (userAmountEntity.InAmount == null ? 0 : userAmountEntity.InAmount.Value) + rewardAmount;
                                            userAmountEntity.TotalAmount = (userAmountEntity.TotalAmount == null ? 0 : userAmountEntity.TotalAmount.Value) + rewardAmount;
                                        }
                                        else
                                        {
                                            userAmountEntity.OutAmount = (userAmountEntity.OutAmount == null ? 0 : userAmountEntity.OutAmount.Value) + Math.Abs(rewardAmount);
                                        }
                                        userAmountEntity.EndAmount = (userAmountEntity.EndAmount == null ? 0 : userAmountEntity.EndAmount.Value) + rewardAmount;

                                        userAmountBll.Update(userAmountEntity, tran);//更新余额
                                    }

                                    var vipamountDetailBll    = new VipAmountDetailBLL(loggingSessionInfo);
                                    var vipAmountDetailEntity = new VipAmountDetailEntity
                                    {
                                        VipAmountDetailId = Guid.NewGuid(),
                                        VipCardCode       = string.Empty,
                                        VipId             = employeeId,//员工ID
                                        UnitID            = unitInfo != null ? unitInfo.unit_id : string.Empty,
                                        UnitName          = unitInfo != null ? unitInfo.Name : string.Empty,
                                        Amount            = rewardAmount,
                                        UsedReturnAmount  = 0,
                                        EffectiveDate     = DateTime.Now,
                                        DeadlineDate      = Convert.ToDateTime("9999-12-31 23:59:59"),
                                        AmountSourceId    = "26",
                                        Reason            = "Reward",
                                        CustomerID        = CustomerID
                                    };
                                    vipamountDetailBll.Create(vipAmountDetailEntity, tran); //创建余额详情

                                    tran.Commit();                                          //提交事务
                                }
                                catch (Exception ex)
                                {
                                    tran.Rollback();
                                    Loggers.Debug(new DebugLogInfo()
                                    {
                                        Message = "异常-->支付成功回调时更新会员打赏金额出错(PayNotify.ashx):" + ex
                                    });
                                }
                            }
                            #endregion

                            if (trrEntity != null)
                            {
                                context.Response.Write("SUCCESS");
                            }
                            else
                            {
                                context.Response.Write("FAIL");
                            }
                            return;
                        }
                        //获取会员信息
                        var vipInfo = vipBll.GetByID(loggingSessionInfo.UserID);
                        //支付信息 Bear
                        //var tPaymentTypeCustomerMappingEntity = tPaymentTypeCustomerMappingBll.QueryByEntity(new TPaymentTypeCustomerMappingEntity(){ChannelId = ChannelID,CustomerId = loggingSessionInfo.ClientID },null).FirstOrDefault();
                        var paymentTypeList = tPaymentTypeBll.GetAll();
                        var tPaymentType    =
                            paymentTypeList.ToList()
                            .Find(t => t.Payment_Type_Code == "WXJS");

                        //var tPaymentType = tPaymentTypeBll.GetByID(tPaymentTypeCustomerMappingEntity.PaymentTypeID);
                        //获取订单信息
                        var inoutInfo = inoutBll.GetByID(OrderID);
                        if (inoutInfo != null)
                        {
                            var    bll = new TInOutStatusNodeBLL(loggingSessionInfo);
                            string msg;
                            if (!bll.SetOrderPayment(OrderID, out msg, ChannelID, SerialPay))
                            //if (!bll.SetOrderPayment(OrderID, out msg, ChannelID))
                            {
                                throw new Exception(msg);
                            }
                            else if (string.IsNullOrEmpty(inoutInfo.Field17) && string.IsNullOrEmpty(inoutInfo.Field18))
                            {
                                #region 发送订单支付成功微信模板消息
                                var SuccessCommonBLL = new CommonBLL();
                                //SuccessCommonBLL.SentPaymentMessage(inoutInfo, vipInfo.WeiXinUserId,vipInfo.VIPID, loggingSessionInfo);
                                new SendOrderPaySuccessMsgBLL().SentPaymentMessage(inoutInfo, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                                #endregion
                                Loggers.Debug(new DebugLogInfo()
                                {
                                    Message = "调用SetOrderPayment方法更新订单成功"
                                });
                            }
                            //获取订单信息,根据Field3==1判断,如果是ALD订单,则调用ALD接口更新ALD订单的状态
                            #region 更新ALD状态
                            //var orderbll = new InoutService(loggingSessionInfo);
                            //var orderInfo = orderbll.GetInoutInfoById(OrderID);
                            //if (orderInfo.Field3 == "1")
                            //{
                            //    Loggers.Debug(new DebugLogInfo() { Message = string.Format("更新O2OMarketing订单状态成功[OrderID={0}].", OrderID) });
                            //    //更新阿拉丁的订单状态
                            //    JIT.CPOS.Web.OnlineShopping.data.DataOnlineShoppingHandler.ALDChangeOrderStatus aldChangeOrder = new data.DataOnlineShoppingHandler.ALDChangeOrderStatus();
                            //    if (string.IsNullOrEmpty(orderInfo.vip_no))
                            //        throw new Exception("会员ID不能为空,OrderID:" + OrderID);
                            //    aldChangeOrder.MemberID = new Guid(orderInfo.vip_no);
                            //    aldChangeOrder.SourceOrdersID = OrderID;
                            //    aldChangeOrder.Status = int.Parse(orderInfo.status);
                            //    aldChangeOrder.IsPaid = true;
                            //    JIT.CPOS.Web.OnlineShopping.data.DataOnlineShoppingHandler.ALDChangeOrderStatusRequest aldRequest = new data.DataOnlineShoppingHandler.ALDChangeOrderStatusRequest();
                            //    aldRequest.BusinessZoneID = 1;//写死
                            //    aldRequest.Locale = 1;

                            //    aldRequest.UserID = new Guid(orderInfo.vip_no);
                            //    aldRequest.Parameters = aldChangeOrder;
                            //    var url = ConfigurationManager.AppSettings["ALDGatewayURL"];
                            //    var postContent = string.Format("Action=ChangeOrderStatus&ReqContent={0}", aldRequest.ToJSON());
                            //    Loggers.Debug(new DebugLogInfo() { Message = "通知ALD更改状态:" + postContent });
                            //    var strAldRsp = HttpWebClient.DoHttpRequest(url, postContent);
                            //    var aldRsp = strAldRsp.DeserializeJSONTo<JIT.CPOS.Web.OnlineShopping.data.DataOnlineShoppingHandler.ALDResponse>();
                            //    if (!aldRsp.IsSuccess())
                            //    {
                            //        Loggers.Debug(new DebugLogInfo() { Message = string.Format("更新阿拉丁订单状态失败[Request ={0}][Response={1}]", aldRequest.ToJSON(), strAldRsp) });
                            //    }
                            //}
                            #endregion

                            #region 格力推送通知
                            //try
                            //{
                            //    GLServiceOrderBLL glsobll = new GLServiceOrderBLL(loggingSessionInfo);
                            //    if (glsobll.ValidateGree(CustomerID, "cpos_bs_lj"))//先写死
                            //        glsobll.GreePushPaymentOorder(CustomerID, OrderID, loggingSessionInfo);
                            //}
                            //catch (Exception ex)
                            //{
                            //    Loggers.Debug(new DebugLogInfo() { Message = string.Format("付款推送评价师傅链接失败[OrderID={0}].", OrderID) });
                            //}
                            #endregion

                            #region ALD生活服务处理
                            //var rechargeBll = new RechargeStrategyBLL(loggingSessionInfo);
                            //var vipAmountBll = new VipAmountBLL(loggingSessionInfo);
                            //var couponBll = new CouponBLL(loggingSessionInfo);
                            //var vipCouponMappingBll = new VipCouponMappingBLL(loggingSessionInfo);
                            //var unitBll = new UnitBLL(loggingSessionInfo);
                            //DataSet dsOrderInfo = rechargeBll.GetInoutOrderItems(OrderID);
                            //int itemSort = 0;            //商品业务分类
                            //string skuId = string.Empty; //商品SkuId
                            //string vipId = string.Empty; //会员ID
                            //string itemId = string.Empty;//商品ID
                            //string couponId = string.Empty;//优惠券ID
                            //if (dsOrderInfo.Tables[0].Rows.Count > 0)
                            //{
                            //    //if (dsOrderInfo.Tables[0].Rows[0]["ItemSort"] != DBNull.Value && Convert.ToString(dsOrderInfo.Tables[0].Rows[0]["ItemSort"]) != "0")
                            //    itemSort = int.Parse(dsOrderInfo.Tables[0].Rows[0]["ItemSort"].ToString());
                            //    switch (itemSort)
                            //    {
                            //        case 2://充
                            //            #region 充值金额处理

                            //            VipAmountDetailBLL vipAmountDetailBll = new VipAmountDetailBLL(loggingSessionInfo);

                            //            List<IWhereCondition> complexCondition = new List<IWhereCondition> { };
                            //            complexCondition.Add(new EqualsCondition() { FieldName = "ObjectId", Value = OrderID });

                            //            var vipAmountDetal = vipAmountDetailBll.Query(complexCondition.ToArray(), null);
                            //            if (vipAmountDetal.Count() == 0)//确认没有多次执行回调
                            //            {
                            //                ////查询
                            //                //RechargeStrategyEntity[] rechargeList = rechargeBll.Query(complexCondition.ToArray(), lstOrder.ToArray());

                            //                skuId = dsOrderInfo.Tables[0].Rows[0]["SkuId"].ToString();
                            //                //RechargeStrategyEntity rechargeEntity = rechargeBll.GetByID(skuId);
                            //                DataSet dsSkuPirce = unitBll.GetSkuPirce(skuId);
                            //                decimal salePrice = 0;//购买金额
                            //                decimal returnCash = 0;//奖励金额
                            //                if (dsSkuPirce.Tables[0].Rows.Count > 0)
                            //                {
                            //                    salePrice = Convert.ToDecimal(dsSkuPirce.Tables[0].Rows[0]["SalesPrice"].ToString());
                            //                    returnCash = Convert.ToDecimal(dsSkuPirce.Tables[0].Rows[0]["ReturnCash"].ToString());
                            //                    InoutService server = new InoutService(loggingSessionInfo);
                            //                    #region 充值金额
                            //                    var tran = server.GetTran();
                            //                    using (tran.Connection)//事物
                            //                    {
                            //                        try
                            //                        {
                            //                            //充值金额
                            //                            vipAmountBll.AddVipEndAmount(UserID, salePrice, tran, "4", OrderID, loggingSessionInfo);//4=充值
                            //                            tran.Commit();
                            //                        }
                            //                        catch (Exception)
                            //                        {
                            //                            tran.Rollback();
                            //                            throw;
                            //                        }
                            //                    }
                            //                    #endregion

                            //                    #region 奖励金额
                            //                    var tran2 = server.GetTran();
                            //                    using (tran2.Connection)//事物
                            //                    {
                            //                        try
                            //                        {
                            //                            //奖励金额
                            //                            vipAmountBll.AddVipEndAmount(UserID, returnCash, tran2, "6", OrderID, loggingSessionInfo);//6=奖励金额
                            //                            tran2.Commit();
                            //                        }
                            //                        catch (Exception)
                            //                        {
                            //                            tran2.Rollback();
                            //                            throw;
                            //                        }
                            //                    }
                            //                    #endregion
                            //                }
                            //            }
                            //            #endregion
                            //            break;
                            //        case 3://券
                            //            #region 券类商品绑定到会员
                            //            itemId = dsOrderInfo.Tables[0].Rows[0]["ItemId"].ToString();
                            //            vipId = dsOrderInfo.Tables[0].Rows[0]["VipId"].ToString();
                            //            couponId = couponBll.GetCouponByItemId(itemId);
                            //            if (!string.IsNullOrEmpty(couponId))
                            //            {
                            //                VipCouponMappingEntity coupon = new VipCouponMappingEntity
                            //                {
                            //                    VIPID = vipId,
                            //                    CouponID = couponId,
                            //                };
                            //                vipCouponMappingBll.Create(coupon);
                            //            }
                            //            #endregion
                            //            break;
                            //        default:
                            //            break;
                            //    }
                            //}

                            #endregion

                            #region 订单与分润关系处理 add by Henry 2014-10-10
                            //var orderSubBll = new OrderOrderSubRunObjectMappingBLL(loggingSessionInfo);
                            //dynamic o = orderSubBll.SetOrderSub(CustomerID, OrderID);
                            //Type t = o.GetType();
                            //var Desc = t.GetProperty("Desc").GetValue(o, null).ToString();
                            //var IsSuccess = t.GetProperty("IsSuccess").GetValue(o, null).ToString();
                            //if (int.Parse(IsSuccess.ToString()) == 0) //失败
                            //    Loggers.Debug(new DebugLogInfo() { Message = string.Format("订单与分润关系处理失败:{0}", Desc) });
                            #endregion

                            CustomerBasicSettingBLL customerBasicSettingBll = new CustomerBasicSettingBLL(loggingSessionInfo);
                            string AfterPaySetStock = customerBasicSettingBll.GetSettingValueByCode("AfterPaySetStock");
                            if (AfterPaySetStock == "1")
                            {
                                var inoutServiceBLL = new InoutService(loggingSessionInfo);
                                var inoutDetailList = inoutServiceBLL.GetInoutDetailInfoByOrderId(OrderID);
                                inoutBll.SetStock(OrderID, inoutDetailList, 1, loggingSessionInfo);
                            }
                            ///超级分销商订单入队列
                            if (inoutInfo.data_from_id == "35" || inoutInfo.data_from_id == "36")
                            {
                                BS.BLL.RedisOperationBLL.Order.SuperRetailTraderOrderBLL bllSuperRetailTraderOrder = new BS.BLL.RedisOperationBLL.Order.SuperRetailTraderOrderBLL();
                                bllSuperRetailTraderOrder.SetRedisToSuperRetailTraderOrder(loggingSessionInfo, inoutInfo);
                            }

                            //购卡
                            if (!string.IsNullOrEmpty(inoutInfo.Field17) && !string.IsNullOrEmpty(inoutInfo.Field18))
                            {
                                //更新订单状态
                                inoutInfo             = inoutBll.GetByID(OrderID);
                                inoutInfo.Field7      = "700";
                                inoutInfo.status      = "700";
                                inoutInfo.status_desc = "已完成";
                                inoutInfo.Field10     = "已完成";
                                inoutBll.Update(inoutInfo);
                                //会员卡升级
                                vipCardVipMappingBll.BindVirtualItem(vipInfo.VIPID, vipInfo.VipCode, inoutInfo.sales_unit_id, Convert.ToInt32(inoutInfo.Field18), orderId: inoutInfo.order_id);

                                //分润计算
                                RedisSalesVipCardOrderBLL redisSalesVipCardOrderBll = new RedisSalesVipCardOrderBLL();
                                redisSalesVipCardOrderBll.SetRedisSalesVipCardOrder(loggingSessionInfo, inoutInfo);

                                //售卡处理积分、返现、佣金[完成订单]
                                new SendOrderRewardMsgBLL().OrderReward(inoutInfo, loggingSessionInfo, null);//存入到缓存
                            }
                            else
                            {
                                //订单入队列
                                RedisCalculateVipConsumeForUpgrade redisCalculateVipConsumeForUpgrade = new RedisCalculateVipConsumeForUpgrade();
                                redisCalculateVipConsumeForUpgrade.SetVipConsumeForUpgradeList(loggingSessionInfo, inoutInfo);
                            }

                            // add by liangx 2016-09-27 获取订单中的虚拟商品 start
                            CouponTypeBLL            couponTypeBLL            = new CouponTypeBLL(loggingSessionInfo);
                            RedisVipMappingCouponBLL redisVipMappingCouponBLL = new RedisVipMappingCouponBLL();

                            var couponTypes = couponTypeBLL.GetVirtualItemCouponTypes(inoutInfo.order_id);

                            if (couponTypes.Any())
                            {
                                redisVipMappingCouponBLL.SetVipMappingCoupon(couponTypes, "", couponTypes.FirstOrDefault().VipId, "PayVirtualItem");
                            }

                            // add by liangx 2016-09-27 获取订单中的虚拟商品 end

                            //获取门店信息
                            t_unitEntity unitInfo = null;
                            if (!string.IsNullOrEmpty(inoutInfo.sales_unit_id))
                            {
                                unitInfo = unitBLL.GetByID(inoutInfo.sales_unit_id);
                            }
                            //入支付明细表
                            var paymentDetail = new T_Payment_detailEntity()
                            {
                                Payment_Id        = Guid.NewGuid().ToString(),
                                Inout_Id          = inoutInfo.order_id,
                                UnitCode          = unitInfo == null ? "" : unitInfo.unit_code,
                                Payment_Type_Id   = tPaymentType.Payment_Type_Id,
                                Payment_Type_Code = tPaymentType.Payment_Type_Code,
                                Payment_Type_Name = tPaymentType.Payment_Type_Name,
                                Price             = inoutInfo.actual_amount,
                                Total_Amount      = inoutInfo.total_amount,
                                Pay_Points        = inoutInfo.pay_points,
                                CustomerId        = loggingSessionInfo.ClientID
                            };
                            paymentDetailBll.Create(paymentDetail);

                            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
                            };
                            complexCondition.Add(new EqualsCondition()
                            {
                                FieldName = "Inout_Id", Value = inoutInfo.order_id
                            });
                            var paymentDetailList = paymentDetailBll.Query(complexCondition.ToArray(), null);

                            try
                            {
                                var msgRabbitMQ = new EventContract
                                {
                                    Operation  = OptEnum.Create,
                                    EntityType = EntityTypeEnum.Order,
                                    Id         = inoutInfo.order_id
                                };
                                var service = new EventService();
                                service.PublishMsg(msgRabbitMQ);

                                foreach (var detail in paymentDetailList)
                                {
                                    var paymentMQ = new EventContract
                                    {
                                        Operation  = OptEnum.Create,
                                        EntityType = EntityTypeEnum.OrderPayment,
                                        Id         = detail.Payment_Id
                                    };
                                    service.PublishMsg(paymentMQ);
                                }
                            }
                            catch (Exception)
                            {
                                throw new Exception("RabbitMQ Error");
                            }
                        }
                        else//充值订单
                        {
                            var rechargeOrderBll   = new RechargeOrderBLL(loggingSessionInfo);
                            var vipamountDetailBll = new VipAmountDetailBLL(loggingSessionInfo);
                            var rechargeOrderInfo  = rechargeOrderBll.GetByID(OrderID);
                            if (rechargeOrderInfo != null)
                            {
                                //获取门店信息
                                t_unitEntity unitInfo = null;
                                if (!string.IsNullOrEmpty(rechargeOrderInfo.UnitId))
                                {
                                    unitInfo = unitBLL.GetByID(rechargeOrderInfo.UnitId);
                                }
                                //充值
                                rechargeOrderBll.Recharge(rechargeOrderInfo, vipInfo, unitInfo, tPaymentType.Payment_Type_Id);
                                //入支付明细表
                                var paymentDetail = new T_Payment_detailEntity()
                                {
                                    Payment_Id        = Guid.NewGuid().ToString(),
                                    Inout_Id          = rechargeOrderInfo.OrderID.ToString(),
                                    UnitCode          = unitInfo == null ? "" : unitInfo.unit_code,
                                    Payment_Type_Id   = tPaymentType.Payment_Type_Id,
                                    Payment_Type_Code = tPaymentType.Payment_Type_Code,
                                    Payment_Type_Name = tPaymentType.Payment_Type_Name,
                                    Price             = rechargeOrderInfo.ActuallyPaid,
                                    Total_Amount      = rechargeOrderInfo.TotalAmount,
                                    Pay_Points        = rechargeOrderInfo.PayPoints,
                                    CustomerId        = loggingSessionInfo.ClientID
                                };
                                paymentDetailBll.Create(paymentDetail);
                            }
                            else
                            {
                                var receiveAmountOrderBll    = new ReceiveAmountOrderBLL(loggingSessionInfo);
                                var receiveAmountOrderEntity = receiveAmountOrderBll.GetByID(OrderID);



                                //更新订单状态
                                if (receiveAmountOrderEntity != null)
                                {
                                    VipIntegralBLL vipIntegralBll = new VipIntegralBLL(loggingSessionInfo);
                                    //更新订单
                                    receiveAmountOrderEntity.PayStatus = "10";
                                    // Bear
                                    //receiveAmountOrderEntity.PayTypeId = tPaymentTypeCustomerMappingEntity.PaymentTypeID;
                                    receiveAmountOrderEntity.PayTypeId    = tPaymentType.Payment_Type_Id;
                                    receiveAmountOrderEntity.PayDatetTime = DateTime.Now;
                                    receiveAmountOrderBll.Update(receiveAmountOrderEntity);

                                    //获取门店信息
                                    t_unitEntity unitInfo = null;
                                    if (!string.IsNullOrEmpty(receiveAmountOrderEntity.ServiceUnitId))
                                    {
                                        unitInfo = unitBLL.GetByID(receiveAmountOrderEntity.ServiceUnitId);
                                    }


                                    //使用过积分,处理积分
                                    if (receiveAmountOrderEntity.PayPoints != 0 && receiveAmountOrderEntity.PayPoints != null)
                                    {
                                        string sourceId       = "20"; //积分抵扣
                                        var    IntegralDetail = new VipIntegralDetailEntity()
                                        {
                                            Integral         = -Convert.ToInt32(receiveAmountOrderEntity.PayPoints),
                                            IntegralSourceID = sourceId,
                                            ObjectId         = receiveAmountOrderEntity.OrderId.ToString()
                                        };
                                        if (IntegralDetail.Integral != 0)
                                        {
                                            //变动前积分
                                            string OldIntegral = (vipInfo.Integration ?? 0).ToString();
                                            //变动积分
                                            string ChangeIntegral      = (IntegralDetail.Integral ?? 0).ToString();
                                            var    vipIntegralDetailId = vipIntegralBll.AddIntegral(ref vipInfo, unitInfo, IntegralDetail, loggingSessionInfo);
                                            //发送微信积分变动通知模板消息
                                            if (!string.IsNullOrWhiteSpace(vipIntegralDetailId))
                                            {
                                                var CommonBLL = new CommonBLL();
                                                CommonBLL.PointsChangeMessage(OldIntegral, vipInfo, ChangeIntegral, vipInfo.WeiXinUserId, loggingSessionInfo);
                                            }
                                        }
                                    }
                                    //if (receiveAmountOrderEntity.CouponUsePay != 0 || receiveAmountOrderEntity.CouponUsePay != null)
                                    //{
                                    //    //更新使用记录
                                    //    var couponUseBll = new CouponUseBLL(loggingSessionInfo);
                                    //    var couponUseEntity = new CouponUseEntity()
                                    //    {
                                    //        CouponUseID = Guid.NewGuid(),
                                    //        CouponID = rp.CouponId,
                                    //        VipID = vipInfo.VIPID,
                                    //        UnitID = rp.UnitId,
                                    //        OrderID = orderId.ToString(),
                                    //        Comment = "商城使用电子券",
                                    //        CustomerID = CurrentUserInfo.ClientID,
                                    //        CreateBy = CurrentUserInfo.UserID,
                                    //        CreateTime = DateTime.Now,
                                    //        LastUpdateBy = CurrentUserInfo.UserID,
                                    //        LastUpdateTime = DateTime.Now,
                                    //        IsDelete = 0
                                    //    };
                                    //    couponUseBll.Create(couponUseEntity);

                                    //    var couponBll = new CouponBLL(CurrentUserInfo);
                                    //    var couponEntity = couponBll.GetByID(rp.CouponId);

                                    //    //更新CouponType数量
                                    //    var conponTypeBll = new CouponTypeBLL(CurrentUserInfo);
                                    //    var conponTypeEntity = conponTypeBll.QueryByEntity(new CouponTypeEntity() { CouponTypeID = new Guid(couponEntity.CouponTypeID), CustomerId = CurrentUserInfo.ClientID }, null).FirstOrDefault();
                                    //    conponTypeEntity.IsVoucher += 1;
                                    //    conponTypeBll.Update(conponTypeEntity);

                                    //    //停用该优惠券
                                    //    couponEntity.Status = 1;
                                    //    couponBll.Update(couponEntity);
                                    //}

                                    //处理余额
                                    if (receiveAmountOrderEntity.AmountAcctPay != null && receiveAmountOrderEntity.AmountAcctPay != 0)
                                    {
                                        var vipAmountDetailBll = new VipAmountDetailBLL(loggingSessionInfo);

                                        var vipAmountEntity = vipAmountBll.QueryByEntity(new VipAmountEntity()
                                        {
                                            VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
                                        }, null).FirstOrDefault();
                                        if (vipAmountEntity != null)
                                        {
                                            var detailInfo = new VipAmountDetailEntity()
                                            {
                                                Amount         = -receiveAmountOrderEntity.AmountAcctPay,
                                                AmountSourceId = "1",
                                                ObjectId       = receiveAmountOrderEntity.OrderId.ToString()
                                            };
                                            var vipAmountDetailId = vipAmountBll.AddVipAmount(vipInfo, unitInfo, ref vipAmountEntity, detailInfo, loggingSessionInfo);
                                            if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                                            {//发送微信账户余额变动模板消息
                                                var CommonBLL = new CommonBLL();
                                                CommonBLL.BalanceChangedMessage(receiveAmountOrderEntity.OrderNo, vipAmountEntity, detailInfo, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                                            }
                                        }
                                    }


                                    //收款订单积分奖励

                                    vipIntegralBll.OrderReward(receiveAmountOrderEntity, null);


                                    var paymentDetail = new T_Payment_detailEntity()
                                    {
                                        Payment_Id        = Guid.NewGuid().ToString(),
                                        Inout_Id          = receiveAmountOrderEntity.OrderId.ToString(),
                                        UnitCode          = unitInfo == null ? "" : unitInfo.unit_code,
                                        Payment_Type_Id   = tPaymentType.Payment_Type_Id,
                                        Payment_Type_Code = tPaymentType.Payment_Type_Code,
                                        Payment_Type_Name = tPaymentType.Payment_Type_Name,
                                        Price             = receiveAmountOrderEntity.TransAmount,
                                        Total_Amount      = receiveAmountOrderEntity.TotalAmount,
                                        Pay_Points        = receiveAmountOrderEntity.PayPoints,
                                        CustomerId        = loggingSessionInfo.ClientID
                                    };
                                    paymentDetailBll.Create(paymentDetail);
                                }
                            }
                        }
                        context.Response.Write("SUCCESS");
                    }
                }
            }
            catch (Exception ex)
            {
                Loggers.Exception(new ExceptionLogInfo(ex));
                context.Response.Write("ERROR:" + ex.Message);
            }
        }
Exemplo n.º 10
0
        protected override EmptyResponseData ProcessRequest(DTO.Base.APIRequest <GetRefundOrderDetailRP> pRequest)
        {
            var rd   = new EmptyResponseData();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;
            var salesReturnBLL     = new T_SalesReturnBLL(loggingSessionInfo);
            var historyBLL         = new T_SalesReturnHistoryBLL(loggingSessionInfo);
            var refundOrderBLL     = new T_RefundOrderBLL(loggingSessionInfo);
            var vipAmountBLL       = new VipAmountBLL(loggingSessionInfo);       //余额返现BLL实例化
            var vipAmountDetailBLL = new VipAmountDetailBLL(loggingSessionInfo); //余额返现BLL实例化


            var pTran = salesReturnBLL.GetTran();//事务
            T_SalesReturnEntity        salesReturnEntity = null;
            T_SalesReturnHistoryEntity historyEntity     = null;

            T_RefundOrderEntity refundEntity = null;

            var          vipBll     = new VipBLL(loggingSessionInfo);    //会员BLL实例化
            var          userBll    = new T_UserBLL(loggingSessionInfo); //店员BLL实例化
            T_UserEntity userEntity = null;                              //店员信息
            var          unitBLL    = new t_unitBLL(loggingSessionInfo);

            refundEntity = refundOrderBLL.GetByID(para.RefundID);
            userEntity   = userBll.GetByID(loggingSessionInfo.UserID);

            using (pTran.Connection)
            {
                try
                {
                    if (refundEntity != null)
                    {
                        //获取会员信息
                        var vipInfo = vipBll.GetByID(refundEntity.VipID);
                        //获取会员的会员上线
                        VipEntity userInfo = vipBll.GetByID(vipInfo.HigherVipID);
                        if (userInfo == null)
                        {
                            //获取会员的员工上线
                            var tempUser = userBll.GetByID(vipInfo.SetoffUserId);
                            if (tempUser != null)
                            {
                                userInfo       = new VipEntity();
                                userInfo.VIPID = tempUser.user_id;
                            }
                        }

                        //获取门店信息
                        t_unitEntity unitInfo = null;
                        if (!string.IsNullOrEmpty(refundEntity.UnitID))
                        {
                            unitInfo = unitBLL.GetByID(refundEntity.UnitID);
                        }
                        userEntity = userBll.GetByID(loggingSessionInfo.UserID);

                        refundEntity.Status = 2;//已退款
                        refundOrderBLL.Update(refundEntity, pTran);
                        salesReturnEntity = salesReturnBLL.GetByID(refundEntity.SalesReturnID);
                        if (salesReturnEntity != null)
                        {
                            salesReturnEntity.Status = 7;//已完成
                            salesReturnBLL.Update(salesReturnEntity, pTran);
                            historyEntity = new T_SalesReturnHistoryEntity()
                            {
                                SalesReturnID = salesReturnEntity.SalesReturnID,
                                OperationType = 7,
                                OperationDesc = "退款",
                                OperatorID    = loggingSessionInfo.UserID,
                                HisRemark     = "您的服务单财务已退款,请注意查收",
                                OperatorName  = userEntity.user_name,
                                OperatorType  = 1
                            };
                            historyBLL.Create(historyEntity, pTran);
                        }

                        #region 退回集客订单分润
                        //上线员工和线上会员不为空
                        if (userInfo != null)
                        {
                            var vipAmountEntity = vipAmountBLL.QueryByEntity(new VipAmountEntity()
                            {
                                VipId = userInfo.VIPID, VipCardCode = userInfo.VipCode
                            }, null).FirstOrDefault();
                            var vipAmountDetail = vipAmountDetailBLL.QueryByEntity(new VipAmountDetailEntity()
                            {
                                ObjectId = refundEntity.OrderID, AmountSourceId = "20"
                            }, null).FirstOrDefault();
                            if (vipAmountDetail != null)
                            {
                                var detailInfo = new VipAmountDetailEntity()
                                {
                                    Amount         = -vipAmountDetail.Amount.Value,
                                    ObjectId       = refundEntity.RefundID.ToString(),
                                    AmountSourceId = "25"
                                };
                                var vipAmountDetailId = vipAmountBLL.AddVipAmount(userInfo, unitInfo, ref vipAmountEntity, detailInfo, pTran, loggingSessionInfo);
                            }
                        }
                        #endregion
                    }

                    pTran.Commit();  //提交事物
                }
                catch (Exception ex)
                {
                    pTran.Rollback();//回滚事务
                    throw new APIException(ex.Message);
                }
            }
            return(rd);
        }
        /// <summary>
        /// 计算超级分销商佣金,分润用到的批处理
        /// </summary>
        public void CalculateSuperRetailTraderOrderJob()
        {
            var numCount = 50;

            var customerIDs = CustomerBLL.Instance.GetCustomerList();

            foreach (var customer in customerIDs)
            {
                string connString = customer.Value;
                var    count      = RedisOpenAPI.Instance.CCSuperRetailTraderOrder().GetSuperRetailTraderOrderLength(new CC_Order
                {
                    CustomerID = customer.Key
                });
                if (count.Code != ResponseCode.Success)
                {
                    BaseService.WriteLog("从redis获取待绑定优惠券数量失败");
                    continue;
                }
                if (count.Result <= 0)
                {
                    continue;
                }
                if (count.Result < numCount)
                {
                    numCount = Convert.ToInt32(count.Result);
                }

                DataTable dtProfitDetail = CreateTableProfitDetail();
                DataTable dtAmountDetail = CreateTableAmountDetail();
                DataTable dtAmount       = CreateTableAmount();

                for (var i = 0; i < numCount; i++)
                {
                    var response = RedisOpenAPI.Instance.CCSuperRetailTraderOrder().GetSuperRetailTraderOrder(new CC_Order
                    {
                        CustomerID = customer.Key
                    });
                    if (response.Code == ResponseCode.Success)
                    {
                        var orderInfo = response.Result.OrderInfo.JsonDeserialize <T_InoutEntity>();
                        //var loggingSessionInfo = response.Result.LogSession.JsonDeserialize<LoggingSessionInfo>();
                        var        loggingSessionInfo = CustomerBLL.Instance.GetBSLoggingSession(customer.Key, "1");
                        T_InoutBLL inoutBLL           = new T_InoutBLL(loggingSessionInfo);
                        //inoutBLL.CalculateSuperRetailTraderOrder(loggingSessionInfo, orderInfo);
                        if (orderInfo != null)
                        {
                            if (orderInfo.data_from_id == "35" || orderInfo.data_from_id == "36")
                            {
                                T_SuperRetailTraderBLL bllSuperRetailTrader = new T_SuperRetailTraderBLL(loggingSessionInfo);
                                DataSet dsAllFather = bllSuperRetailTrader.GetAllFather(orderInfo.sales_user);
                                if (dsAllFather != null && dsAllFather.Tables.Count > 0 && dsAllFather.Tables[0].Rows.Count > 0)
                                {
                                    T_SuperRetailTraderProfitConfigBLL bllSuperRetailTraderProfitConfig = new T_SuperRetailTraderProfitConfigBLL(loggingSessionInfo);
                                    T_SuperRetailTraderConfigBLL       bllSuperRetailTraderConfig       = new T_SuperRetailTraderConfigBLL(loggingSessionInfo);
                                    T_SuperRetailTraderProfitDetailBLL bllSuperRetailTraderProfitDetail = new T_SuperRetailTraderProfitDetailBLL(loggingSessionInfo);

                                    VipAmountBLL       bllVipAmount       = new VipAmountBLL(loggingSessionInfo);
                                    VipAmountDetailBLL bllVipAmountDetail = new VipAmountDetailBLL(loggingSessionInfo);

                                    var entitySuperRetailTraderProfitConfig = bllSuperRetailTraderProfitConfig.QueryByEntity(new T_SuperRetailTraderProfitConfigEntity()
                                    {
                                        CustomerId = loggingSessionInfo.ClientID, IsDelete = 0, Status = "10"
                                    }, null);
                                    var entityConfig = bllSuperRetailTraderConfig.QueryByEntity(new T_SuperRetailTraderConfigEntity()
                                    {
                                        CustomerId = loggingSessionInfo.ClientID, IsDelete = 0
                                    }, null).SingleOrDefault();
                                    if (entityConfig != null && entitySuperRetailTraderProfitConfig != null)
                                    {
                                        //佣金比列
                                        decimal SkuCommission = Convert.ToDecimal(entityConfig.SkuCommission) * Convert.ToDecimal(0.01);
                                        //商品分润比列
                                        decimal DistributionProfit = Convert.ToDecimal(entityConfig.DistributionProfit) * Convert.ToDecimal(0.01);


                                        foreach (DataRow dr in dsAllFather.Tables[0].Rows)
                                        {
                                            decimal amount            = 0;
                                            string  strAmountSourceId = string.Empty;
                                            T_SuperRetailTraderProfitConfigEntity singlProfitConfig = new T_SuperRetailTraderProfitConfigEntity();
                                            if (dr["level"].ToString() == "1")      //佣金
                                            {
                                                strAmountSourceId = "34";
                                                singlProfitConfig = entitySuperRetailTraderProfitConfig.Where(a => a.Level == Convert.ToInt16(dr["level"].ToString())).SingleOrDefault();
                                                if (singlProfitConfig != null)
                                                {
                                                    if (singlProfitConfig.ProfitType == "Percent")
                                                    {
                                                        amount = Convert.ToDecimal(orderInfo.actual_amount) * SkuCommission;
                                                    }
                                                }
                                            }
                                            else      //分润
                                            {
                                                strAmountSourceId = "33";
                                                singlProfitConfig = entitySuperRetailTraderProfitConfig.Where(a => a.Level == Convert.ToInt16(dr["level"].ToString())).SingleOrDefault();
                                                if (singlProfitConfig != null)
                                                {
                                                    if (singlProfitConfig.ProfitType == "Percent")
                                                    {
                                                        //amount = Convert.ToDecimal(orderInfo.actual_amount) * DistributionProfit * Convert.ToDecimal(singlProfitConfig.Profit) * Convert.ToDecimal(0.01);
                                                        amount = Convert.ToDecimal(orderInfo.actual_amount) * Convert.ToDecimal(singlProfitConfig.Profit) * Convert.ToDecimal(0.01);
                                                    }
                                                }
                                            }
                                            var vipAmountDetail = bllVipAmountDetail.QueryByEntity(new VipAmountDetailEntity()
                                            {
                                                ObjectId = orderInfo.order_id, AmountSourceId = strAmountSourceId
                                            }, null);
                                            if (vipAmountDetail != null && vipAmountDetail.Length > 0)
                                            {
                                                continue;
                                            }
                                            if (amount > 0)
                                            {
                                                IDbTransaction tran = new JIT.CPOS.BS.DataAccess.Base.TransactionHelper(loggingSessionInfo).CreateTransaction();
                                                try
                                                {
                                                    T_SuperRetailTraderProfitDetailEntity entitySuperRetailTraderProfitDetail = new T_SuperRetailTraderProfitDetailEntity()
                                                    {
                                                        SuperRetailTraderProfitConfigId = singlProfitConfig.SuperRetailTraderProfitConfigId,
                                                        SuperRetailTraderID             = new Guid(dr["SuperRetailTraderID"].ToString()),
                                                        Level             = Convert.ToInt16(dr["level"].ToString()),
                                                        ProfitType        = "Cash",
                                                        Profit            = amount,
                                                        OrderType         = "Order",
                                                        OrderId           = orderInfo.order_id,
                                                        OrderDate         = Convert.ToDateTime(orderInfo.order_date),
                                                        VipId             = orderInfo.vip_no,
                                                        OrderActualAmount = orderInfo.actual_amount,
                                                        SalesId           = new Guid(orderInfo.sales_user),
                                                        OrderNo           = orderInfo.order_no,
                                                        CustomerId        = loggingSessionInfo.ClientID
                                                    };
                                                    bllSuperRetailTraderProfitDetail.Create(entitySuperRetailTraderProfitDetail, (SqlTransaction)tran);

                                                    VipAmountEntity       entityVipAmount       = new VipAmountEntity();
                                                    VipAmountDetailEntity entityVipAmountDetail = new VipAmountDetailEntity();
                                                    entityVipAmountDetail = new VipAmountDetailEntity {
                                                        VipAmountDetailId = Guid.NewGuid(),
                                                        VipId             = dr["SuperRetailTraderID"].ToString(),
                                                        Amount            = amount,
                                                        UsedReturnAmount  = 0,
                                                        EffectiveDate     = DateTime.Now,
                                                        DeadlineDate      = Convert.ToDateTime("9999-12-31 23:59:59"),
                                                        AmountSourceId    = strAmountSourceId,
                                                        ObjectId          = orderInfo.order_id,
                                                        CustomerID        = loggingSessionInfo.ClientID,
                                                        Reason            = "超级分销商",
                                                        IsWithdrawCash    = 0
                                                    };
                                                    bllVipAmountDetail.Create(entityVipAmountDetail, (SqlTransaction)tran);
                                                    //DataRow dr_ProfitDetail = dtProfitDetail.NewRow();
                                                    //dr_ProfitDetail["Id"] = Guid.NewGuid();
                                                    //dr_ProfitDetail["SuperRetailTraderProfitConfigId"] = new Guid(singlProfitConfig.SuperRetailTraderProfitConfigId.ToString());
                                                    //dr_ProfitDetail["SuperRetailTraderID"] = new Guid(dr["SuperRetailTraderID"].ToString());
                                                    //dr_ProfitDetail["Level"] = Convert.ToInt16(dr["level"].ToString());
                                                    //dr_ProfitDetail["ProfitType"] = "Cash";
                                                    //dr_ProfitDetail["Profit"] = amount;
                                                    //dr_ProfitDetail["OrderType"] = "Order";
                                                    //dr_ProfitDetail["OrderId"] = orderInfo.order_id;
                                                    //dr_ProfitDetail["OrderNo"] = orderInfo.order_no;
                                                    //dr_ProfitDetail["OrderDate"] = Convert.ToDateTime(orderInfo.order_date);
                                                    //dr_ProfitDetail["OrderActualAmount"] = orderInfo.actual_amount;
                                                    //dr_ProfitDetail["SalesId"] = new Guid(orderInfo.sales_user);
                                                    //dr_ProfitDetail["VipId"] = orderInfo.vip_no;
                                                    //dr_ProfitDetail["CreateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_ProfitDetail["CreateTime"] = DateTime.Now;
                                                    //dr_ProfitDetail["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_ProfitDetail["LastUpdateTime"] = DateTime.Now;
                                                    //dr_ProfitDetail["CustomerId"] = loggingSessionInfo.ClientID;
                                                    //dr_ProfitDetail["IsDelete"] = 0;

                                                    //dtProfitDetail.Rows.Add(dr_ProfitDetail);

                                                    //DataRow dr_AmountDetail = dtAmountDetail.NewRow();
                                                    //dr_AmountDetail["VipAmountDetailId"] = Guid.NewGuid();
                                                    //dr_AmountDetail["VipId"] = dr["SuperRetailTraderID"].ToString();
                                                    //dr_AmountDetail["VipCardCode"] = "";
                                                    //dr_AmountDetail["UnitID"] = "";
                                                    //dr_AmountDetail["UnitName"] = "";
                                                    //dr_AmountDetail["SalesAmount"] = 0;
                                                    //dr_AmountDetail["Amount"] = amount;
                                                    //dr_AmountDetail["UsedReturnAmount"] = 0;
                                                    //dr_AmountDetail["Reason"] = "超级分销商";
                                                    //dr_AmountDetail["EffectiveDate"] = DateTime.Now;
                                                    //dr_AmountDetail["DeadlineDate"] = Convert.ToDateTime("9999-12-31 23:59:59");
                                                    //dr_AmountDetail["AmountSourceId"] = strAmountSourceId;
                                                    //dr_AmountDetail["ObjectId"] = orderInfo.order_id;
                                                    //dr_AmountDetail["Remark"] = "超级分销商";
                                                    //dr_AmountDetail["IsValid"] = 0;
                                                    //dr_AmountDetail["IsWithdrawCash"] = 0;
                                                    //dr_AmountDetail["CustomerID"] = loggingSessionInfo.ClientID;
                                                    //dr_AmountDetail["CreateTime"] = DateTime.Now;
                                                    //dr_AmountDetail["CreateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_AmountDetail["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_AmountDetail["LastUpdateTime"] = DateTime.Now;
                                                    //dr_AmountDetail["IsDelete"] = 0;
                                                    ////dr_AmountDetail["IsCalculated"] = 1;

                                                    //dtAmountDetail.Rows.Add(dr_AmountDetail);

                                                    entityVipAmount = bllVipAmount.QueryByEntity(new VipAmountEntity()
                                                    {
                                                        VipId = dr["SuperRetailTraderID"].ToString(), IsDelete = 0
                                                    }, null).SingleOrDefault();
                                                    if (entityVipAmount == null)
                                                    {
                                                        entityVipAmount = new VipAmountEntity {
                                                            VipId                  = dr["SuperRetailTraderID"].ToString(),
                                                            BeginAmount            = 0,
                                                            InAmount               = amount,
                                                            OutAmount              = 0,
                                                            EndAmount              = amount,
                                                            TotalAmount            = amount,
                                                            BeginReturnAmount      = 0,
                                                            InReturnAmount         = 0,
                                                            OutReturnAmount        = 0,
                                                            ReturnAmount           = 0,
                                                            ImminentInvalidRAmount = 0,
                                                            InvalidReturnAmount    = 0,
                                                            ValidReturnAmount      = 0,
                                                            TotalReturnAmount      = 0,
                                                            IsLocking              = 0,
                                                            CustomerID             = loggingSessionInfo.ClientID,
                                                            VipCardCode            = ""
                                                        };
                                                        bllVipAmount.Create(entityVipAmount, tran);
                                                        //DataRow dr_Amount = dtAmount.NewRow();
                                                        //dr_Amount["VipId"] = dr["SuperRetailTraderID"].ToString();
                                                        //dr_Amount["VipCardCode"] = "";
                                                        //dr_Amount["BeginAmount"] = 0;
                                                        //dr_Amount["InAmount"] = amount;
                                                        //dr_Amount["OutAmount"] = 0;
                                                        //dr_Amount["EndAmount"] = amount;
                                                        //dr_Amount["TotalAmount"] = amount;
                                                        //dr_Amount["BeginReturnAmount"] = 0;
                                                        //dr_Amount["InReturnAmount"] = 0;
                                                        //dr_Amount["OutReturnAmount"] = 0;
                                                        //dr_Amount["ReturnAmount"] = 0;
                                                        //dr_Amount["ImminentInvalidRAmount"] = 0;
                                                        //dr_Amount["InvalidReturnAmount"] = 0;
                                                        //dr_Amount["ValidReturnAmount"] = 0;
                                                        //dr_Amount["TotalReturnAmount"] = 0;
                                                        //dr_Amount["PayPassword"] = "";
                                                        //dr_Amount["IsLocking"] = 0;
                                                        //dr_Amount["CustomerID"] = loggingSessionInfo.ClientID;
                                                        //dr_Amount["CreateTime"] = DateTime.Now;
                                                        //dr_Amount["CreateBy"] = loggingSessionInfo.ClientID;
                                                        //dr_Amount["LastUpdateBy"] =loggingSessionInfo.ClientID;
                                                        //dr_Amount["LastUpdateTime"] = DateTime.Now;
                                                        //dr_Amount["IsDelete"] = 0;
                                                        //dtAmount.Rows.Add(dr_Amount);
                                                    }
                                                    else
                                                    {
                                                        entityVipAmount.InReturnAmount    = (entityVipAmount.InReturnAmount == null ? 0 : entityVipAmount.InReturnAmount.Value) + amount;
                                                        entityVipAmount.TotalReturnAmount = (entityVipAmount.TotalReturnAmount == null ? 0 : entityVipAmount.TotalReturnAmount.Value) + amount;

                                                        entityVipAmount.ValidReturnAmount = (entityVipAmount.ValidReturnAmount == null ? 0 : entityVipAmount.ValidReturnAmount.Value) + amount;
                                                        entityVipAmount.ReturnAmount      = (entityVipAmount.ReturnAmount == null ? 0 : entityVipAmount.ReturnAmount.Value) + amount;

                                                        bllVipAmount.Update(entityVipAmount);
                                                    }
                                                    tran.Commit();
                                                }
                                                catch (Exception)
                                                {
                                                    tran.Rollback();
                                                    throw;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //if (dtAmount.Rows.Count > 0)
                //{
                //    Utils.SqlBulkCopy(connString, dtAmount, "VipAmount");
                //}
                //if (dtAmountDetail.Rows.Count>0 && dtProfitDetail.Rows.Count>0)
                //{
                //    Utils.SqlBulkCopy(connString, dtProfitDetail, "T_SuperRetailTraderProfitDetail");
                //    Utils.SqlBulkCopy(connString, dtAmountDetail, "VipAmountDetail");

                //}
            }
        }
Exemplo n.º 12
0
        protected override GetVipAmountDetailRD ProcessRequest(DTO.Base.APIRequest <GetVipAmountDetailRP> pRequest)
        {
            var rd   = new GetVipAmountDetailRD();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo; //登录状态信息
            var vipAmountBLL       = new VipAmountBLL(loggingSessionInfo);
            var vipAmountDetailBLL = new VipAmountDetailBLL(loggingSessionInfo);

            //查询参数
            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
            };

            //商户条件
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "a.VipID", Value = para.VipId
            });
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "a.VipCardCode", Value = para.VipCardCode
            });

            if (para.Type == 1) //余额
            {
                complexCondition.Add(new DirectCondition(" a.AmountSourceId in (1,4,6,10,17,20,21,23) "));
            }
            else if (para.Type == 2) //返现
            {
                complexCondition.Add(new DirectCondition(" a.AmountSourceId in (2,3,13,16,22,24)"));
            }



            //排序参数
            List <OrderBy> lstOrder = new List <OrderBy> {
            };

            lstOrder.Add(new OrderBy()
            {
                FieldName = "a.CreateTime", Direction = OrderByDirections.Desc
            });

            var tempList = vipAmountDetailBLL.GetVipAmountDetailList(complexCondition.ToArray(), lstOrder.ToArray(), para.PageSize, para.PageIndex);

            rd.TotalCount          = tempList.RowCount;
            rd.TotalPageCount      = tempList.PageCount;
            rd.VipAmountDetailList = tempList.Entities.Select(t => new VipAmountDetailInfo()
            {
                UnitName         = t.UnitName,
                AmountSourceName = t.AmountSourceName,
                Amount           = t.Amount.Value,
                CreateTime       = t.CreateTime.Value.ToString("yyyy-MM-dd HH:mm"),
                Reason           = t.Reason == null ? "" : t.Reason,
                Remark           = t.Remark == null ? "" : t.Remark,
                ImageUrl         = t.ImageUrl,
                CreateByName     = t.CreateByName,
            }).ToArray();

            //查询当前余额/返现
            rd.CurrentAmount = 0; //当前余额/返现(默认值)
            var vipAmountInfo = vipAmountBLL.QueryByEntity(new VipAmountEntity()
            {
                VipId = para.VipId, VipCardCode = para.VipCardCode
            }, null).FirstOrDefault();

            if (vipAmountInfo != null)
            {
                if (para.Type == 1) //余额
                {
                    rd.CurrentAmount = vipAmountInfo.EndAmount.Value;
                }
                else
                {
                    rd.CurrentAmount = vipAmountInfo.ValidReturnAmount.Value;
                }
            }
            return(rd);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 充值订单循环队列计算
        /// </summary>
        public void CalculateRechargeOrderJob()
        {
            var numCount    = 50;
            var customerIDs = CustomerBLL.Instance.GetCustomerList();

            foreach (var customer in customerIDs)
            {
                string connString = customer.Value;
                var    count      = RedisOpenAPI.Instance.CCRechargeOrder().GetRechargeOrderLength(new CC_Order
                {
                    CustomerID = customer.Key
                });
                if (count.Code != ResponseCode.Success)
                {
                    BaseService.WriteLog("从redis获取充值订单数据失败");
                    continue;
                }
                if (count.Result <= 0)
                {
                    continue;
                }
                if (count.Result < numCount)
                {
                    numCount = Convert.ToInt32(count.Result);
                }
                var loggingSessionInfo = CustomerBLL.Instance.GetBSLoggingSession(customer.Key, "RedisSystem");
                VipCardProfitRuleBLL      bllVipCardProfitRule    = new VipCardProfitRuleBLL(loggingSessionInfo);
                VipCardProfitRuleEntity[] entityVipCardProfitRule = null;
                var                    bllVipCardGradeChangeLog   = new VipCardGradeChangeLogBLL(loggingSessionInfo);
                VipAmountBLL           bllVipAmount         = new VipAmountBLL(loggingSessionInfo);
                VipAmountDetailBLL     bllVipAmountDetail   = new VipAmountDetailBLL(loggingSessionInfo);
                T_SplitProfitRecordBLL bllSplitProfitRecord = new T_SplitProfitRecordBLL(loggingSessionInfo);

                for (var i = 0; i < numCount; i++)
                {
                    var response = RedisOpenAPI.Instance.CCRechargeOrder().GetRechargeOrder(new CC_Order
                    {
                        CustomerID = customer.Key
                    });
                    if (response.Code == ResponseCode.Success)
                    {
                        var rechargeOrderInfo = response.Result.OrderInfo.JsonDeserialize <RechargeOrderEntity>();

                        entityVipCardProfitRule = bllVipCardProfitRule.QueryByEntity(new VipCardProfitRuleEntity()
                        {
                            VipCardTypeID = rechargeOrderInfo.VipCardTypeId, IsDelete = 0
                        }, null);
                        if (entityVipCardProfitRule != null)
                        {
                            //DataTable dtAmountDetail = CreateTableAmountDetail();
                            //DataTable dtAmount = CreateTableAmount();
                            //DataTable dtSplitProfitRecord = CreateTableSplitProfitRecord();



                            VipAmountEntity           entityVipAmount         = new VipAmountEntity();
                            VipAmountDetailEntity     entityVipAmountDetail   = new VipAmountDetailEntity();
                            T_SplitProfitRecordEntity entitySplitProfitRecord = new T_SplitProfitRecordEntity();

                            foreach (var ProfitRule in entityVipCardProfitRule)
                            {
                                decimal amount            = 0;
                                string  strAmountSourceId = string.Empty;
                                string  strVipId          = string.Empty;
                                string  strUserType       = string.Empty;
                                if (ProfitRule.IsApplyAllUnits == 0)
                                {
                                    VipCardProfitRuleUnitMappingBLL bllVipCardProfitRuleUnitMapping = new VipCardProfitRuleUnitMappingBLL(loggingSessionInfo);
                                    var vipCardProfitRuleUnitMapping = bllVipCardProfitRuleUnitMapping.QueryByEntity(new VipCardProfitRuleUnitMappingEntity()
                                    {
                                        CardBuyToProfitRuleId = ProfitRule.CardBuyToProfitRuleId, UnitID = rechargeOrderInfo.UnitId, IsDelete = 0, CustomerID = loggingSessionInfo.ClientID
                                    }, null).SingleOrDefault();
                                    if (vipCardProfitRuleUnitMapping == null)
                                    {
                                        continue;
                                    }
                                }
                                if (ProfitRule.ProfitOwner == "Employee")
                                {
                                    strAmountSourceId = "38";
                                    strVipId          = rechargeOrderInfo.UserId;
                                    strUserType       = "User";
                                }
                                if (ProfitRule.ProfitOwner == "Unit")
                                {
                                    strAmountSourceId = "42";
                                    strVipId          = rechargeOrderInfo.UnitId;
                                    strUserType       = "Unit";
                                }
                                var vipAmountDetail = bllVipAmountDetail.QueryByEntity(new VipAmountDetailEntity()
                                {
                                    ObjectId = rechargeOrderInfo.OrderID.ToString(), AmountSourceId = strAmountSourceId
                                }, null);
                                if (vipAmountDetail != null && vipAmountDetail.Length > 0)
                                {
                                    continue;
                                }
                                if (rechargeOrderInfo.OrderDesc == "Upgrade")                                //首充
                                {
                                    amount = (decimal)ProfitRule.FirstRechargeProfitPct * (decimal)rechargeOrderInfo.ActuallyPaid * (decimal)0.01;
                                }
                                if (rechargeOrderInfo.OrderDesc == "ReRecharge")//续充
                                {
                                    VipCardReRechargeProfitRuleBLL bllVipCardReRechargeProfitRule = new VipCardReRechargeProfitRuleBLL(loggingSessionInfo);
                                    var entityVipCardReRechargeProfitRule = bllVipCardReRechargeProfitRule.QueryByEntity(new VipCardReRechargeProfitRuleEntity()
                                    {
                                        VipCardTypeID = rechargeOrderInfo.VipCardTypeId, CardBuyToProfitRuleId = ProfitRule.CardBuyToProfitRuleId, IsDelete = 0
                                    }, null);
                                    if (entityVipCardReRechargeProfitRule != null)
                                    {
                                        decimal discount = 0;
                                        foreach (var ReRechargeProfitRule in entityVipCardReRechargeProfitRule.OrderByDescending(a => a.LimitAmount))
                                        {
                                            if (ReRechargeProfitRule.ProfitType == "Superposition")
                                            {
                                                discount = (decimal)(ReRechargeProfitRule.LimitAmount * ReRechargeProfitRule.ProfitPct) * (decimal)0.01;
                                                amount   = (decimal)(rechargeOrderInfo.ActuallyPaid / ReRechargeProfitRule.LimitAmount) * discount;
                                            }
                                            if (ReRechargeProfitRule.ProfitType == "Step")
                                            {
                                                if (rechargeOrderInfo.ActuallyPaid >= ReRechargeProfitRule.LimitAmount)
                                                {
                                                    if (discount == 0)
                                                    {
                                                        discount = (decimal)ReRechargeProfitRule.ProfitPct * (decimal)0.01;
                                                        amount   = (decimal)rechargeOrderInfo.ActuallyPaid * discount;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                //入库
                                if (amount > 0)
                                {
                                    IDbTransaction tran = new JIT.CPOS.BS.DataAccess.Base.TransactionHelper(loggingSessionInfo).CreateTransaction();
                                    try {
                                        //                           DataRow dr_AmountDetail = dtAmountDetail.NewRow();
                                        //                           dr_AmountDetail["VipAmountDetailId"] = Guid.NewGuid();
                                        //                           dr_AmountDetail["VipId"] = strVipId;
                                        //                           dr_AmountDetail["VipCardCode"] = "";
                                        //                           dr_AmountDetail["UnitID"] = "";
                                        //                           dr_AmountDetail["UnitName"] = "";
                                        //                           dr_AmountDetail["SalesAmount"] = 0;
                                        //                           dr_AmountDetail["Amount"] = amount;
                                        //                           dr_AmountDetail["UsedReturnAmount"] = 0;
                                        //                           dr_AmountDetail["Reason"] = "充值";
                                        //                           dr_AmountDetail["EffectiveDate"] = DateTime.Now;
                                        //                           dr_AmountDetail["DeadlineDate"] = Convert.ToDateTime("9999-12-31 23:59:59");
                                        //                           dr_AmountDetail["AmountSourceId"] = strAmountSourceId;
                                        //                           dr_AmountDetail["ObjectId"] = rechargeOrderInfo.OrderID.ToString();
                                        //							 dr_AmountDetail["Remark"] = "充值";
                                        //                           dr_AmountDetail["IsValid"] = 0;
                                        //                           dr_AmountDetail["IsWithdrawCash"] = 0;
                                        //                           dr_AmountDetail["CustomerID"] = loggingSessionInfo.ClientID;
                                        //                           dr_AmountDetail["CreateTime"] = DateTime.Now;
                                        //                           dr_AmountDetail["CreateBy"] = loggingSessionInfo.ClientID;
                                        //                           dr_AmountDetail["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                        //                           dr_AmountDetail["LastUpdateTime"] = DateTime.Now;
                                        //                           dr_AmountDetail["IsDelete"] = 0;
                                        //                           //dr_AmountDetail["IsCalculated"] = 1;
                                        //                           dtAmountDetail.Rows.Add(dr_AmountDetail);

                                        //DataRow dr_SplitProfitRecord = dtSplitProfitRecord.NewRow();
                                        //dr_SplitProfitRecord["Id"] = Guid.NewGuid();
                                        //dr_SplitProfitRecord["SourceType"] = "Amount";
                                        //dr_SplitProfitRecord["SourceId"] = strAmountSourceId;
                                        //dr_SplitProfitRecord["ObjectId"] = rechargeOrderInfo.OrderID.ToString();
                                        //dr_SplitProfitRecord["UserType"] = strUserType;
                                        //dr_SplitProfitRecord["UserId"] = rechargeOrderInfo.UserId;
                                        //dr_SplitProfitRecord["SplitAmount"] = amount;
                                        //dr_SplitProfitRecord["SplitSattus"] = "10";
                                        //dr_SplitProfitRecord["CustomerId"] = loggingSessionInfo.ClientID;
                                        //dr_SplitProfitRecord["CreateTime"] = DateTime.Now;
                                        //dr_SplitProfitRecord["CreateBy"] = loggingSessionInfo.ClientID;
                                        //dr_SplitProfitRecord["LastUpdateTime"] = DateTime.Now;
                                        //dr_SplitProfitRecord["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                        //dr_SplitProfitRecord["IsDelete"] = 0;
                                        //dtSplitProfitRecord.Rows.Add(dr_SplitProfitRecord);

                                        entitySplitProfitRecord = new T_SplitProfitRecordEntity()
                                        {
                                            ID          = Guid.NewGuid().ToString(),
                                            SourceType  = "Amount",
                                            SourceId    = strAmountSourceId,
                                            ObjectId    = rechargeOrderInfo.OrderID.ToString(),
                                            UserType    = strUserType,
                                            UserId      = rechargeOrderInfo.UserId,
                                            SplitAmount = amount,
                                            SplitSattus = "10",
                                            CustomerID  = loggingSessionInfo.ClientID
                                        };
                                        bllSplitProfitRecord.Create(entitySplitProfitRecord, tran);


                                        entityVipAmountDetail = new VipAmountDetailEntity {
                                            VipAmountDetailId = Guid.NewGuid(),
                                            VipId             = strVipId,
                                            Amount            = amount,
                                            UsedReturnAmount  = 0,
                                            EffectiveDate     = DateTime.Now,
                                            DeadlineDate      = Convert.ToDateTime("9999-12-31 23:59:59"),
                                            AmountSourceId    = strAmountSourceId,
                                            ObjectId          = rechargeOrderInfo.OrderID.ToString(),
                                            CustomerID        = loggingSessionInfo.ClientID,
                                            Reason            = "充值",
                                            IsWithdrawCash    = 0
                                        };
                                        bllVipAmountDetail.Create(entityVipAmountDetail, (SqlTransaction)tran);


                                        entityVipAmount = bllVipAmount.QueryByEntity(new VipAmountEntity()
                                        {
                                            VipId = strVipId, IsDelete = 0
                                        }, null).SingleOrDefault();
                                        if (entityVipAmount == null)
                                        {
                                            entityVipAmount = new VipAmountEntity {
                                                VipId                  = strVipId,
                                                BeginAmount            = 0,
                                                InAmount               = amount,
                                                OutAmount              = 0,
                                                EndAmount              = amount,
                                                TotalAmount            = amount,
                                                BeginReturnAmount      = 0,
                                                InReturnAmount         = 0,
                                                OutReturnAmount        = 0,
                                                ReturnAmount           = 0,
                                                ImminentInvalidRAmount = 0,
                                                InvalidReturnAmount    = 0,
                                                ValidReturnAmount      = 0,
                                                TotalReturnAmount      = 0,
                                                IsLocking              = 0,
                                                CustomerID             = loggingSessionInfo.ClientID,
                                                VipCardCode            = ""
                                            };
                                            bllVipAmount.Create(entityVipAmount, tran);

                                            //DataRow dr_Amount = dtAmount.NewRow();
                                            //dr_Amount["VipId"] = strVipId;
                                            //dr_Amount["VipCardCode"] = "";
                                            //dr_Amount["BeginAmount"] = 0;
                                            //dr_Amount["InAmount"] = amount;
                                            //dr_Amount["OutAmount"] = 0;
                                            //dr_Amount["EndAmount"] = amount;
                                            //dr_Amount["TotalAmount"] = amount;
                                            //dr_Amount["BeginReturnAmount"] = 0;
                                            //dr_Amount["InReturnAmount"] = 0;
                                            //dr_Amount["OutReturnAmount"] = 0;
                                            //dr_Amount["ReturnAmount"] = 0;
                                            //dr_Amount["ImminentInvalidRAmount"] = 0;
                                            //dr_Amount["InvalidReturnAmount"] = 0;
                                            //dr_Amount["ValidReturnAmount"] = 0;
                                            //dr_Amount["TotalReturnAmount"] = 0;
                                            //dr_Amount["PayPassword"] = "";
                                            //dr_Amount["IsLocking"] = 0;
                                            //dr_Amount["CustomerID"] = loggingSessionInfo.ClientID;
                                            //dr_Amount["CreateTime"] = DateTime.Now;
                                            //dr_Amount["CreateBy"] = loggingSessionInfo.ClientID;
                                            //dr_Amount["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                            //dr_Amount["LastUpdateTime"] = DateTime.Now;
                                            //dr_Amount["IsDelete"] = 0;
                                            //dtAmount.Rows.Add(dr_Amount);
                                        }
                                        else
                                        {
                                            entityVipAmount.InReturnAmount    = (entityVipAmount.InReturnAmount == null ? 0 : entityVipAmount.InReturnAmount.Value) + amount;
                                            entityVipAmount.TotalReturnAmount = (entityVipAmount.TotalReturnAmount == null ? 0 : entityVipAmount.TotalReturnAmount.Value) + amount;

                                            entityVipAmount.ValidReturnAmount = (entityVipAmount.ValidReturnAmount == null ? 0 : entityVipAmount.ValidReturnAmount.Value) + amount;
                                            entityVipAmount.ReturnAmount      = (entityVipAmount.ReturnAmount == null ? 0 : entityVipAmount.ReturnAmount.Value) + amount;
                                            bllVipAmount.Update(entityVipAmount);
                                        }
                                        tran.Commit();
                                    }
                                    catch (Exception) {
                                        tran.Rollback();
                                        throw;
                                    }
                                }
                            }
                            //if (dtAmount.Rows.Count > 0 && dtAmountDetail.Rows.Count == dtAmount.Rows.Count)
                            //{
                            //    Utils.SqlBulkCopy(connString, dtAmount, "VipAmount");
                            //}
                            //if (dtAmountDetail.Rows.Count > 0 && dtSplitProfitRecord.Rows.Count > 0)
                            //{
                            //    Utils.SqlBulkCopy(connString, dtSplitProfitRecord, "T_SplitProfitRecord");
                            //    Utils.SqlBulkCopy(connString, dtAmountDetail, "VipAmountDetail");

                            //}
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 计算购卡分润
        /// </summary>
        public void CalculateSalesVipCardOrderJob()
        {
            var numCount = 50;

            var customerIDs = CustomerBLL.Instance.GetCustomerList();

            foreach (var customer in customerIDs)
            {
                string connString = customer.Value;
                var    count      = RedisOpenAPI.Instance.CCSalesCardOrder().GetSalesCardOrderLength(new CC_Order
                {
                    CustomerID = customer.Key
                });
                if (count.Code != ResponseCode.Success)
                {
                    BaseService.WriteLog("从redis获取vipcard订单数据失败");
                    continue;
                }
                if (count.Result <= 0)
                {
                    continue;
                }
                if (count.Result < numCount)
                {
                    numCount = Convert.ToInt32(count.Result);
                }
                //DataTable dtAmountDetail = CreateTableAmountDetail();
                //DataTable dtAmount = CreateTableAmount();
                //DataTable dtSplitProfitRecord = CreateTableSplitProfitRecord();

                for (var i = 0; i < numCount; i++)
                {
                    var response = RedisOpenAPI.Instance.CCSalesCardOrder().GetSalesCardOrder(new CC_Order
                    {
                        CustomerID = customer.Key
                    });
                    if (response.Code == ResponseCode.Success)
                    {
                        var        orderInfo          = response.Result.OrderInfo.JsonDeserialize <T_InoutEntity>();
                        var        loggingSessionInfo = CustomerBLL.Instance.GetBSLoggingSession(customer.Key, "RedisSystem");
                        T_InoutBLL inoutBLL           = new T_InoutBLL(loggingSessionInfo);
                        if (orderInfo != null)
                        {
                            VipBLL                      bllVip                    = new VipBLL(loggingSessionInfo);
                            T_Inout_DetailBLL           bllInoutDetail            = new T_Inout_DetailBLL(loggingSessionInfo);
                            T_VirtualItemTypeSettingBLL bllVirtualItemTypeSetting = new T_VirtualItemTypeSettingBLL(loggingSessionInfo);
                            VipCardUpgradeRuleBLL       bllVipCardUpgradeRule     = new VipCardUpgradeRuleBLL(loggingSessionInfo);
                            VipAmountBLL                bllVipAmount              = new VipAmountBLL(loggingSessionInfo);
                            VipAmountDetailBLL          bllVipAmountDetail        = new VipAmountDetailBLL(loggingSessionInfo);
                            T_SplitProfitRecordBLL      bllSplitProfitRecord      = new T_SplitProfitRecordBLL(loggingSessionInfo);

                            VipAmountEntity           entityVipAmount         = new VipAmountEntity();
                            VipAmountDetailEntity     entityVipAmountDetail   = new VipAmountDetailEntity();
                            T_SplitProfitRecordEntity entitySplitProfitRecord = new T_SplitProfitRecordEntity();

                            DataSet dsVipCardLevel    = bllVip.GetVipCardLevel(orderInfo.vip_no, loggingSessionInfo.ClientID);
                            var     entityInoutDetail = bllInoutDetail.QueryByEntity(new T_Inout_DetailEntity()
                            {
                                order_id = orderInfo.order_id
                            }, null).FirstOrDefault();
                            if (entityInoutDetail == null)
                            {
                                continue;
                            }
                            var vipCardType = bllVirtualItemTypeSetting.QueryByEntity(new T_VirtualItemTypeSettingEntity()
                            {
                                SkuId = entityInoutDetail.sku_id, IsDelete = 0
                            }, null).FirstOrDefault();
                            if (vipCardType != null)
                            {
                                int intVipCardTypeID         = Convert.ToInt32(vipCardType.ObjecetTypeId);
                                var entityVipCardUpgradeRule = bllVipCardUpgradeRule.QueryByEntity(new VipCardUpgradeRuleEntity()
                                {
                                    VipCardTypeID = intVipCardTypeID, IsPurchaseUpgrade = 1, IsDelete = 0
                                }, null).SingleOrDefault();
                                if (entityVipCardUpgradeRule != null)
                                {
                                    VipCardProfitRuleBLL bllVipCardProfitRule = new VipCardProfitRuleBLL(loggingSessionInfo);
                                    var entityVipCardProfitRule = bllVipCardProfitRule.QueryByEntity(new VipCardProfitRuleEntity()
                                    {
                                        VipCardTypeID = intVipCardTypeID, IsDelete = 0
                                    }, null);
                                    foreach (var ProfitRule in entityVipCardProfitRule)
                                    {
                                        if (ProfitRule.IsApplyAllUnits == 0)
                                        {
                                            VipCardProfitRuleUnitMappingBLL bllVipCardProfitRuleUnitMapping = new VipCardProfitRuleUnitMappingBLL(loggingSessionInfo);
                                            var vipCardProfitRuleUnitMapping = bllVipCardProfitRuleUnitMapping.QueryByEntity(new VipCardProfitRuleUnitMappingEntity()
                                            {
                                                CardBuyToProfitRuleId = ProfitRule.CardBuyToProfitRuleId, UnitID = orderInfo.sales_unit_id, IsDelete = 0, CustomerID = loggingSessionInfo.ClientID
                                            }, null).SingleOrDefault();
                                            if (vipCardProfitRuleUnitMapping == null)
                                            {
                                                continue;
                                            }
                                        }
                                        decimal amount            = 0;
                                        string  strAmountSourceId = string.Empty;
                                        string  strVipId          = string.Empty;
                                        string  strUserType       = string.Empty;
                                        if (ProfitRule.ProfitOwner == "Employee")
                                        {
                                            strAmountSourceId = "37";
                                            strVipId          = orderInfo.sales_user;
                                            strUserType       = "User";
                                        }
                                        if (ProfitRule.ProfitOwner == "Unit")
                                        {
                                            strAmountSourceId = "40";
                                            strVipId          = orderInfo.sales_unit_id;
                                            strUserType       = "Unit";
                                        }
                                        amount = (decimal)ProfitRule.FirstCardSalesProfitPct * (decimal)orderInfo.actual_amount * (decimal)0.01;
                                        var vipAmountDetail = bllVipAmountDetail.QueryByEntity(new VipAmountDetailEntity()
                                        {
                                            ObjectId = orderInfo.order_id, AmountSourceId = strAmountSourceId
                                        }, null);
                                        if (vipAmountDetail != null && vipAmountDetail.Length > 0)
                                        {
                                            continue;
                                        }
                                        if (amount > 0)
                                        {
                                            IDbTransaction tran = new JIT.CPOS.BS.DataAccess.Base.TransactionHelper(loggingSessionInfo).CreateTransaction();
                                            try {
                                                //                                 DataRow dr_SplitProfitRecord = dtSplitProfitRecord.NewRow();
                                                //                                 dr_SplitProfitRecord["Id"] = Guid.NewGuid();
                                                //                                 dr_SplitProfitRecord["SourceType"] = "Amount";
                                                //                                 dr_SplitProfitRecord["SourceId"] = strAmountSourceId;
                                                //                                 dr_SplitProfitRecord["ObjectId"] = orderInfo.order_id;
                                                //dr_SplitProfitRecord["UserType"] = strUserType;
                                                //                                 dr_SplitProfitRecord["UserId"] = orderInfo.sales_user;
                                                //                                 dr_SplitProfitRecord["SplitAmount"] = amount;
                                                //                                 dr_SplitProfitRecord["SplitSattus"] = "10";
                                                //                                 dr_SplitProfitRecord["CustomerId"] = loggingSessionInfo.ClientID;
                                                //                                 dr_SplitProfitRecord["CreateTime"] = DateTime.Now;
                                                //                                 dr_SplitProfitRecord["CreateBy"] = loggingSessionInfo.ClientID;
                                                //                                 dr_SplitProfitRecord["LastUpdateTime"] = DateTime.Now;
                                                //                                 dr_SplitProfitRecord["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                                //                                 dr_SplitProfitRecord["IsDelete"] = 0;
                                                //                                 dtSplitProfitRecord.Rows.Add(dr_SplitProfitRecord);

                                                //                                 DataRow dr_AmountDetail = dtAmountDetail.NewRow();
                                                //                                 dr_AmountDetail["VipAmountDetailId"] = Guid.NewGuid();
                                                //dr_AmountDetail["VipId"] = strVipId;
                                                //                                 dr_AmountDetail["VipCardCode"] = "";
                                                //                                 dr_AmountDetail["UnitID"] = "";
                                                //                                 dr_AmountDetail["UnitName"] = "";
                                                //                                 dr_AmountDetail["SalesAmount"] = 0;
                                                //                                 dr_AmountDetail["Amount"] = amount;
                                                //                                 dr_AmountDetail["UsedReturnAmount"] = 0;
                                                //                                 dr_AmountDetail["Reason"] = "首次售卡分润";
                                                //                                 dr_AmountDetail["EffectiveDate"] = DateTime.Now;
                                                //                                 dr_AmountDetail["DeadlineDate"] = Convert.ToDateTime("9999-12-31 23:59:59");
                                                //                                 dr_AmountDetail["AmountSourceId"] = strAmountSourceId;
                                                //                                 dr_AmountDetail["ObjectId"] = orderInfo.order_id;
                                                //                                 dr_AmountDetail["Remark"] = "首次售卡分润";
                                                //                                 dr_AmountDetail["IsValid"] = 0;
                                                //                                 dr_AmountDetail["IsWithdrawCash"] = 0;
                                                //                                 dr_AmountDetail["CustomerID"] = loggingSessionInfo.ClientID;
                                                //                                 dr_AmountDetail["CreateTime"] = DateTime.Now;
                                                //                                 dr_AmountDetail["CreateBy"] = loggingSessionInfo.ClientID;
                                                //                                 dr_AmountDetail["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                                //                                 dr_AmountDetail["LastUpdateTime"] = DateTime.Now;
                                                //                                 dr_AmountDetail["IsDelete"] = 0;
                                                //                                 //dr_AmountDetail["IsCalculated"] = 1;
                                                //                                 dtAmountDetail.Rows.Add(dr_AmountDetail);

                                                entitySplitProfitRecord = new T_SplitProfitRecordEntity()
                                                {
                                                    ID          = Guid.NewGuid().ToString(),
                                                    SourceType  = "Amount",
                                                    SourceId    = strAmountSourceId,
                                                    ObjectId    = orderInfo.order_id,
                                                    UserType    = strUserType,
                                                    UserId      = orderInfo.sales_user,
                                                    SplitAmount = amount,
                                                    SplitSattus = "10",
                                                    CustomerID  = loggingSessionInfo.ClientID
                                                };
                                                bllSplitProfitRecord.Create(entitySplitProfitRecord, tran);


                                                entityVipAmountDetail = new VipAmountDetailEntity {
                                                    VipAmountDetailId = Guid.NewGuid(),
                                                    VipId             = strVipId,
                                                    Amount            = amount,
                                                    UsedReturnAmount  = 0,
                                                    EffectiveDate     = DateTime.Now,
                                                    DeadlineDate      = Convert.ToDateTime("9999-12-31 23:59:59"),
                                                    AmountSourceId    = strAmountSourceId,
                                                    ObjectId          = orderInfo.order_id,
                                                    CustomerID        = loggingSessionInfo.ClientID,
                                                    Reason            = "首次售卡分润",
                                                    Remark            = "首次售卡分润",
                                                    IsWithdrawCash    = 0
                                                };
                                                bllVipAmountDetail.Create(entityVipAmountDetail, (SqlTransaction)tran);

                                                entityVipAmount = bllVipAmount.QueryByEntity(new VipAmountEntity()
                                                {
                                                    VipId = orderInfo.sales_user, IsDelete = 0
                                                }, null).SingleOrDefault();
                                                if (entityVipAmount == null)
                                                {
                                                    //DataRow dr_Amount = dtAmount.NewRow();
                                                    //dr_Amount["VipId"] = orderInfo.sales_user;
                                                    //dr_Amount["VipCardCode"] = "";
                                                    //dr_Amount["BeginAmount"] = 0;
                                                    //dr_Amount["InAmount"] = amount;
                                                    //dr_Amount["OutAmount"] = 0;
                                                    //dr_Amount["EndAmount"] = amount;
                                                    //dr_Amount["TotalAmount"] = amount;
                                                    //dr_Amount["BeginReturnAmount"] = 0;
                                                    //dr_Amount["InReturnAmount"] = 0;
                                                    //dr_Amount["OutReturnAmount"] = 0;
                                                    //dr_Amount["ReturnAmount"] = 0;
                                                    //dr_Amount["ImminentInvalidRAmount"] = 0;
                                                    //dr_Amount["InvalidReturnAmount"] = 0;
                                                    //dr_Amount["ValidReturnAmount"] = 0;
                                                    //dr_Amount["TotalReturnAmount"] = 0;
                                                    //dr_Amount["PayPassword"] = "";
                                                    //dr_Amount["IsLocking"] = 0;
                                                    //dr_Amount["CustomerID"] = loggingSessionInfo.ClientID;
                                                    //dr_Amount["CreateTime"] = DateTime.Now;
                                                    //dr_Amount["CreateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_Amount["LastUpdateBy"] = loggingSessionInfo.ClientID;
                                                    //dr_Amount["LastUpdateTime"] = DateTime.Now;
                                                    //dr_Amount["IsDelete"] = 0;
                                                    //dtAmount.Rows.Add(dr_Amount);
                                                    entityVipAmount = new VipAmountEntity {
                                                        VipId                  = strVipId,
                                                        BeginAmount            = 0,
                                                        InAmount               = amount,
                                                        OutAmount              = 0,
                                                        EndAmount              = amount,
                                                        TotalAmount            = amount,
                                                        BeginReturnAmount      = 0,
                                                        InReturnAmount         = 0,
                                                        OutReturnAmount        = 0,
                                                        ReturnAmount           = 0,
                                                        ImminentInvalidRAmount = 0,
                                                        InvalidReturnAmount    = 0,
                                                        ValidReturnAmount      = 0,
                                                        TotalReturnAmount      = 0,
                                                        IsLocking              = 0,
                                                        CustomerID             = loggingSessionInfo.ClientID,
                                                        VipCardCode            = ""
                                                    };
                                                    bllVipAmount.Create(entityVipAmount, tran);
                                                }
                                                else
                                                {
                                                    entityVipAmount.InReturnAmount    = (entityVipAmount.InReturnAmount == null ? 0 : entityVipAmount.InReturnAmount.Value) + amount;
                                                    entityVipAmount.TotalReturnAmount = (entityVipAmount.TotalReturnAmount == null ? 0 : entityVipAmount.TotalReturnAmount.Value) + amount;

                                                    entityVipAmount.ValidReturnAmount = (entityVipAmount.ValidReturnAmount == null ? 0 : entityVipAmount.ValidReturnAmount.Value) + amount;
                                                    entityVipAmount.ReturnAmount      = (entityVipAmount.ReturnAmount == null ? 0 : entityVipAmount.ReturnAmount.Value) + amount;

                                                    bllVipAmount.Update(entityVipAmount);
                                                }
                                                tran.Commit();
                                            }
                                            catch (Exception) {
                                                tran.Rollback();
                                                throw;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //if (dtAmount.Rows.Count > 0)
                //{
                //    Utils.SqlBulkCopy(connString, dtAmount, "VipAmount");
                //}
                //if (dtAmountDetail.Rows.Count > 0 && dtSplitProfitRecord.Rows.Count > 0)
                //{
                //    Utils.SqlBulkCopy(connString, dtSplitProfitRecord, "T_SplitProfitRecord");
                //    Utils.SqlBulkCopy(connString, dtAmountDetail, "VipAmountDetail");

                //}
            }
        }
Exemplo n.º 15
0
        //<summary>
        //Pos订单入库
        //</summary>
        //<param name="pRequest"></param>
        //<returns></returns>
        protected override SetPosOrderRD ProcessRequest(APIRequest <SetPosOrderRP> pRequest)
        {
            //请求参数
            var rp = pRequest.Parameters;
            //返回参数
            var rd = new SetPosOrderRD();

            //订单
            var inoutBll    = new T_InoutBLL(CurrentUserInfo);
            var inoutDetail = new T_Inout_DetailBLL(CurrentUserInfo);
            //商品
            var itemCategoryBll = new T_Item_CategoryBLL(CurrentUserInfo);
            var itemBll         = new T_ItemBLL(CurrentUserInfo);
            var porpBll         = new T_PropBLL(CurrentUserInfo);
            var itemSkuPropBll  = new T_ItemSkuPropBLL(CurrentUserInfo);
            var skuBll          = new T_SkuBLL(CurrentUserInfo);
            var skuPriceBll     = new T_Sku_PriceBLL(CurrentUserInfo);
            var skuProperty     = new T_Sku_PropertyBLL(CurrentUserInfo);
            //获取会员信息
            var vipBll  = new VipBLL(CurrentUserInfo);
            var vipInfo = vipBll.GetByID(pRequest.UserID);
            var vipCardVipMappingBll    = new VipCardVipMappingBLL(CurrentUserInfo);
            var vipCardBll              = new VipCardBLL(CurrentUserInfo);
            var vipCardVipMappingEntity = vipCardVipMappingBll.QueryByEntity(new VipCardVipMappingEntity()
            {
                VIPID = vipInfo.VIPID, CustomerID = CurrentUserInfo.ClientID
            }, null).FirstOrDefault();
            string VipCardTypeID = ""; //卡类型Id

            if (vipCardVipMappingEntity != null)
            {
                var vipCardEntity = vipCardBll.GetByID(vipCardVipMappingEntity.VipCardID);
                VipCardTypeID = vipCardEntity.VipCardTypeID.ToString();
            }
            //员工
            var userBll = new T_UserBLL(CurrentUserInfo);

            //获取门店信息
            var          unitBll  = new t_unitBLL(CurrentUserInfo);
            t_unitEntity unitInfo = null;

            if (!string.IsNullOrEmpty(rp.UnitCode))
            {
                unitInfo = unitBll.QueryByEntity(new t_unitEntity()
                {
                    unit_code = rp.UnitCode, customer_id = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                if (unitInfo == null)
                {
                    throw new APIException("请在正念商户后台录入相应门店")
                          {
                              ErrorCode = 100
                          };
                }
            }
            else
            {
                throw new APIException("缺少请求参数:门店编码")
                      {
                          ErrorCode = 102
                      };
            }

            //获取员工信息
            T_UserEntity userEntity = null;

            if (!string.IsNullOrEmpty(rp.MobliePhone))
            {
                userEntity = userBll.QueryByEntity(new T_UserEntity()
                {
                    user_telephone = rp.MobliePhone, customer_id = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                //没有员工,新增默认员工(店员APP)
                if (userEntity == null)
                {
                    var roleBll    = new T_RoleBLL(CurrentUserInfo);
                    var roleEntity = roleBll.QueryByEntity(new T_RoleEntity()
                    {
                        role_code = "clerkAPP", customer_id = CurrentUserInfo.ClientID
                    }, null).FirstOrDefault();
                    if (roleEntity == null)
                    {
                        throw new APIException("请在正念商户后台录入相应角色")
                              {
                                  ErrorCode = 100
                              };
                    }
                    userEntity = new T_UserEntity();
                    userEntity.user_telephone = rp.MobliePhone;
                    userEntity.user_code      = rp.UserCode;
                    userEntity.user_name      = rp.UserCode;
                    userEntity.user_birthday  = rp.Birthday;
                    userEntity.user_email     = rp.EmailAddress;
                    userEntity.user_address   = rp.Address;
                    userEntity.user_postcode  = rp.Zip;
                    userBll.AddUser(ref userEntity, unitInfo, roleEntity);
                }
            }
            else
            {
                throw new APIException("缺少请求参数:员工手机号")
                      {
                          ErrorCode = 102
                      };
            }
            //获取会员折扣
            var     sysVipCardGradeBLL = new SysVipCardGradeBLL(CurrentUserInfo);
            decimal vipDiscount        = sysVipCardGradeBLL.GetVipDiscount() * 10;


            //订单号
            string        orderId      = BaseService.NewGuidPub();
            T_InoutEntity tInoutEntity = new T_InoutEntity();

            tInoutEntity.order_id = orderId;
            tInoutEntity.order_no = rp.OrderNo;

            //拼接ItemCodes
            //StringBuilder ItemCodes = new StringBuilder();
            //for (int j = 0; j < pRequest.Parameters.OrderDetailList.Count(); j++)
            //{
            //    if (j != 0)
            //    {
            //        ItemCodes.Append(",");
            //    }
            //    ItemCodes.Append(string.Format("{0}", pRequest.Parameters.OrderDetailList[j].ItemCode));
            //}

            ////通过itemCodes取出商品价格
            //SkuPriceService skuPriceService = new SkuPriceService(CurrentUserInfo);
            //List<SkuPrice> skuPriceList = skuPriceService.GetPriceListByItemCodes(ItemCodes.ToString(), CurrentUserInfo.ClientID);
            //if(skuPriceList.Count == 0)
            //{
            //    throw new APIException("未找到商品") { ErrorCode = 100 };
            //}

            //订单总金额
            decimal totalAmount = rp.TotalAmount;
            //订单实付金额
            decimal ActualAmount = rp.DiscountAmount;
            //订单折扣后金额
            decimal DiscountAmount = rp.DiscountAmount;
            //订单明细显示顺序
            int i = 1;

            //商品价格重新计算
            foreach (var item in pRequest.Parameters.OrderDetailList)
            {
                T_ItemEntity itemEntity = null; //商品
                T_SkuEntity  skuEntity  = null; //sku
                if (!string.IsNullOrEmpty(item.ItemCode))
                {
                    itemEntity = itemBll.QueryByEntity(new T_ItemEntity()
                    {
                        item_code = item.ItemCode, CustomerId = CurrentUserInfo.ClientID
                    }, null).FirstOrDefault();
                    if (itemEntity == null)
                    {
                        if (string.IsNullOrEmpty(item.ItemCategoryCode))
                        {
                            throw new APIException("缺少参数:商品类别名称")
                                  {
                                      ErrorCode = 200
                                  };
                        }
                        itemEntity           = new T_ItemEntity();
                        itemEntity.item_code = item.ItemCode;
                        itemEntity.item_name = item.ItemName;

                        itemBll.AddItem(itemEntity, out skuEntity, item.ItemCategoryName, item.ItemCategoryCode, item.SkuOriginPrice, item.SkuSalesPrice);
                    }
                    else
                    {
                        skuEntity = skuBll.QueryByEntity(new T_SkuEntity()
                        {
                            item_id = itemEntity.item_id
                        }, null).FirstOrDefault();
                    }
                }
                else
                {
                    throw new APIException("缺少参数:商品编码")
                          {
                              ErrorCode = 300
                          };
                }

                //订单明细相关处理
                T_Inout_DetailBLL    inoutDetailBll    = new T_Inout_DetailBLL(CurrentUserInfo);
                T_Inout_DetailEntity inoutDetailEntity = new T_Inout_DetailEntity()
                {
                    order_detail_id     = BaseService.NewGuidPub(),
                    order_id            = orderId,               //订单Id
                    sku_id              = skuEntity.sku_id,      //skuId
                    unit_id             = unitInfo.unit_id,      //门店Id
                    order_qty           = item.Qty,              //订单qty
                    enter_qty           = item.Qty,              //实际qty
                    enter_price         = item.price,            //折扣价
                    enter_amount        = item.price * item.Qty, //折扣价
                    std_price           = item.price,            //原价
                    discount_rate       = vipDiscount,           //折扣
                    retail_price        = item.price * item.Qty, //零售价
                    retail_amount       = item.price * item.Qty, //零售价
                    order_detail_status = "1",
                    display_index       = i,
                    if_flag             = 0
                };
                inoutDetailBll.Create(inoutDetailEntity);
                i++;
            }

            //优惠券使用
            if (!string.IsNullOrEmpty(rp.CouponId))
            {
                #region 判断优惠券是否是该会员的

                var vipcouponMappingBll = new VipCouponMappingBLL(CurrentUserInfo);

                var vipcouponmappingList = vipcouponMappingBll.QueryByEntity(new VipCouponMappingEntity()
                {
                    VIPID    = pRequest.UserID,
                    CouponID = rp.CouponId
                }, null);

                if (vipcouponmappingList == null || vipcouponmappingList.Length == 0)
                {
                    throw new APIException("此张优惠券不是该会员的")
                          {
                              ErrorCode = 103
                          };
                }

                #endregion

                #region 判断优惠券是否有效

                var couponBll = new CouponBLL(CurrentUserInfo);

                var couponEntity = couponBll.GetByID(rp.CouponId);

                if (couponEntity == null)
                {
                    throw new APIException("无效的优惠券")
                          {
                              ErrorCode = 103
                          };
                }

                if (couponEntity.Status == 1)
                {
                    throw new APIException("优惠券已使用")
                          {
                              ErrorCode = 103
                          };
                }

                if (couponEntity.EndDate < DateTime.Now)
                {
                    throw new APIException("优惠券已过期")
                          {
                              ErrorCode = 103
                          };
                }
                var couponTypeBll    = new CouponTypeBLL(CurrentUserInfo);
                var couponTypeEntity = couponTypeBll.GetByID(couponEntity.CouponTypeID);

                if (couponTypeEntity == null)
                {
                    throw new APIException("无效的优惠券类型")
                          {
                              ErrorCode = 103
                          };
                }

                #endregion

                #region 优惠券核销
                var couponUseBll    = new CouponUseBLL(CurrentUserInfo);
                var couponUseEntity = new CouponUseEntity()
                {
                    CouponUseID    = Guid.NewGuid(),
                    CouponID       = rp.CouponId,
                    VipID          = pRequest.UserID,
                    UnitID         = unitInfo.unit_id,
                    OrderID        = orderId,
                    Comment        = "商城使用电子券",
                    CustomerID     = pRequest.CustomerID,
                    CreateBy       = pRequest.UserID,
                    CreateTime     = DateTime.Now,
                    LastUpdateBy   = pRequest.UserID,
                    LastUpdateTime = DateTime.Now,
                    IsDelete       = 0
                };
                couponUseBll.Create(couponUseEntity);
                #endregion

                #region 更新CouponType数量
                var conponTypeBll    = new CouponTypeBLL(CurrentUserInfo);
                var conponTypeEntity = conponTypeBll.QueryByEntity(new CouponTypeEntity()
                {
                    CouponTypeID = new Guid(couponEntity.CouponTypeID), CustomerId = pRequest.CustomerID
                }, null).FirstOrDefault();
                conponTypeEntity.IsVoucher += 1;
                conponTypeBll.Update(conponTypeEntity);

                #endregion

                #region 更新优惠券状态

                couponEntity.Status = 1;
                couponBll.Update(couponEntity);

                #endregion

                ActualAmount -= couponTypeEntity.ParValue ?? 0;
            }

            #region 使用积分
            //使用积分
            if (rp.IntegralFlag == 1)
            {
                var vipIntegralBll = new VipIntegralBLL(CurrentUserInfo);

                string sourceId       = "20"; //积分抵扣
                var    IntegralDetail = new VipIntegralDetailEntity()
                {
                    Integral         = -Convert.ToInt32(rp.Integral),
                    IntegralSourceID = sourceId,
                    ObjectId         = orderId
                };
                if (IntegralDetail.Integral != 0)
                {
                    //变动前积分
                    string OldIntegral = (vipInfo.Integration ?? 0).ToString();
                    //变动积分
                    string ChangeIntegral      = (IntegralDetail.Integral ?? 0).ToString();
                    var    vipIntegralDetailId = vipIntegralBll.AddIntegral(ref vipInfo, unitInfo, IntegralDetail, CurrentUserInfo);
                    //发送微信积分变动通知模板消息
                    if (!string.IsNullOrWhiteSpace(vipIntegralDetailId))
                    {
                        var CommonBLL = new CommonBLL();
                        CommonBLL.PointsChangeMessage(OldIntegral, vipInfo, ChangeIntegral, vipInfo.WeiXinUserId, CurrentUserInfo);
                    }
                }
                tInoutEntity.pay_points     = rp.Integral;
                tInoutEntity.receive_points = rp.Integral;
                ActualAmount -= rp.IntegralAmount;
            }
            #endregion

            #region 余额和返现修改

            var vipAmountBll       = new VipAmountBLL(CurrentUserInfo);
            var vipAmountDetailBll = new VipAmountDetailBLL(CurrentUserInfo);

            var vipAmountEntity = vipAmountBll.QueryByEntity(new VipAmountEntity()
            {
                VipId = pRequest.UserID, VipCardCode = vipInfo.VipCode
            }, null).FirstOrDefault();
            if (vipAmountEntity != null)
            {
                //判断该会员账户是否被冻结
                if (vipAmountEntity.IsLocking == 1)
                {
                    throw new APIException("账户已被冻结,请先解冻")
                          {
                              ErrorCode = 103
                          }
                }
                ;

                //判断该会员的账户余额是否大于本次使用的余额
                if (vipAmountEntity.EndAmount < rp.EndAmount)
                {
                    throw new APIException(string.Format("账户余额不足,当前余额为【{0}】", vipAmountEntity.EndAmount))
                          {
                              ErrorCode = 103
                          }
                }
                ;
            }

            //使用余额
            if (rp.EndAmountFlag == 1)
            {
                var detailInfo = new VipAmountDetailEntity()
                {
                    Amount         = -rp.EndAmount,
                    AmountSourceId = "1",
                    ObjectId       = orderId
                };
                var vipAmountDetailId = vipAmountBll.AddVipAmount(vipInfo, unitInfo, ref vipAmountEntity, detailInfo, CurrentUserInfo);
                if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                {//发送微信账户余额变动模板消息
                    var CommonBLL = new CommonBLL();
                    CommonBLL.BalanceChangedMessage(tInoutEntity.order_no, vipAmountEntity, detailInfo, vipInfo.WeiXinUserId, vipInfo.VIPID, CurrentUserInfo);
                }
                tInoutEntity.Field3 = rp.EndAmount.ToString();
            }

            #endregion
            //订单主表更新
            tInoutEntity.VipCardCode      = vipInfo.VipCardCode;//会员卡号
            tInoutEntity.order_reason_id  = "2F6891A2194A4BBAB6F17B4C99A6C6F5";
            tInoutEntity.order_type_id    = "1F0A100C42484454BAEA211D4C14B80F";
            tInoutEntity.warehouse_id     = "67bb4c12785c42d4912aff7d34606592";
            tInoutEntity.data_from_id     = "";
            tInoutEntity.red_flag         = "1";
            tInoutEntity.order_date       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //订单时间
            tInoutEntity.create_unit_id   = unitInfo.unit_id;                             //门店
            tInoutEntity.unit_id          = unitInfo.unit_id;                             //门店
            tInoutEntity.sales_unit_id    = unitInfo.unit_id;                             //门店
            tInoutEntity.purchase_unit_id = unitInfo.unit_id;
            tInoutEntity.sales_user       = userEntity.user_id;
            tInoutEntity.total_amount     = totalAmount;  //订单金额
            tInoutEntity.discount_rate    = vipDiscount;  //会员折扣
            tInoutEntity.actual_amount    = ActualAmount; //实付金额
            tInoutEntity.total_qty        = rp.qty;
            tInoutEntity.total_retail     = totalAmount;  //订单金额
            tInoutEntity.vip_no           = vipInfo.VIPID;
            tInoutEntity.Field6           = vipInfo.Phone;
            tInoutEntity.Field14          = vipInfo.VipName;
            tInoutEntity.Field17          = VipCardTypeID;
            tInoutEntity.Field12          = DiscountAmount.ToString();
            tInoutEntity.Field11          = "知行易";
            tInoutEntity.customer_id      = CurrentUserInfo.ClientID;

            tInoutEntity.Field1      = "1";   //支付完成
            tInoutEntity.Field7      = "700"; //已完成
            tInoutEntity.status      = "700"; //已完成
            tInoutEntity.status_desc = "已完成";
            tInoutEntity.Field10     = "已完成";
            rd.Amount = ActualAmount - rp.EndAmount;

            inoutBll.Create(tInoutEntity);

            //订单奖励
            new SendOrderRewardMsgBLL().OrderReward(tInoutEntity, this.CurrentUserInfo, null);//存入到缓存
            rd.orderId = orderId;
            return(rd);
        }
    }
}
Exemplo n.º 16
0
        protected override GetMemberInfoRD ProcessRequest(DTO.Base.APIRequest <GetMemberInfoRP> pRequest)
        {
            GetMemberInfoRD rd = new GetMemberInfoRD();

            rd.MemberInfo = new MemberInfo();
            var vipLoginBLL = new VipBLL(base.CurrentUserInfo);

            //如果有一个查询标识非空,就用查询标识查,发现没有会员就报错
            if (!string.IsNullOrEmpty(pRequest.Parameters.SearchFlag))
            {
                List <IWhereCondition> complexCondition = new List <IWhereCondition> {
                };
                complexCondition.Add(new EqualsCondition()
                {
                    FieldName = "ClientID", Value = CurrentUserInfo.ClientID
                });
                var cond1 = new LikeCondition()
                {
                    FieldName = "VipName", Value = "%" + pRequest.Parameters.SearchFlag + "%"
                };
                var cond2 = new LikeCondition()
                {
                    FieldName = "VipRealName", Value = "%" + pRequest.Parameters.SearchFlag + "%"
                };
                var com1 = new ComplexCondition()
                {
                    Left = cond1, Right = cond2, Operator = LogicalOperators.Or
                };

                var cond3 = new EqualsCondition()
                {
                    FieldName = "Phone", Value = pRequest.Parameters.SearchFlag
                };
                var com2 = new ComplexCondition()
                {
                    Left = com1, Right = cond3, Operator = LogicalOperators.Or
                };
                complexCondition.Add(com2);
                complexCondition.Add(new DirectCondition("(WeiXinUserId!='' Or WeiXinUserId IS NOT NULL)"));
                var tempVipList = vipLoginBLL.Query(complexCondition.ToArray(), null);
                if (tempVipList != null && tempVipList.Length != 0)
                {
                    pRequest.UserID = pRequest.Parameters.MemberID = tempVipList[0].VIPID;
                }
            }

            string m_MemberID = "";

            if (!string.IsNullOrWhiteSpace(pRequest.Parameters.OwnerVipID))
            {
                m_MemberID = string.IsNullOrWhiteSpace(pRequest.Parameters.OwnerVipID) ? pRequest.UserID : pRequest.Parameters.OwnerVipID;
            }
            else
            {
                m_MemberID = string.IsNullOrWhiteSpace(pRequest.Parameters.MemberID) ? pRequest.UserID : pRequest.Parameters.MemberID;
            }

            string UserID       = m_MemberID;
            var    VipLoginInfo = vipLoginBLL.GetByID(UserID);

            if (VipLoginInfo == null)
            {
                throw new APIException("用户不存在")
                      {
                          ErrorCode = 330
                      }
            }
            ;
            #region 20140909 kun.zou 发现状态为0,改为1
            if (VipLoginInfo.Status.HasValue && VipLoginInfo.Status == 0)
            {
                VipLoginInfo.Status = 1;
                vipLoginBLL.Update(VipLoginInfo, false);
                var log = new VipLogEntity()
                {
                    Action       = "更新",
                    ActionRemark = "vip状态为0的改为1.",
                    CreateBy     = UserID,
                    CreateTime   = DateTime.Now,
                    VipID        = VipLoginInfo.VIPID,
                    LogID        = Guid.NewGuid().ToString("N")
                };
                var logBll = new VipLogBLL(base.CurrentUserInfo);
                logBll.Create(log);
            }
            #endregion
            int couponCount = vipLoginBLL.GetVipCoupon(UserID);

            rd.MemberInfo.Mobile      = VipLoginInfo.Phone;      //手机号码
            rd.MemberInfo.Name        = VipLoginInfo.UserName;   //姓名
            rd.MemberInfo.VipID       = VipLoginInfo.VIPID;      //组标识
            rd.MemberInfo.VipName     = VipLoginInfo.VipName;    //会员名
            rd.MemberInfo.ImageUrl    = VipLoginInfo.HeadImgUrl; //会员头像  add by Henry 2014-12-5
            rd.MemberInfo.VipRealName = VipLoginInfo.VipRealName;
            rd.MemberInfo.VipNo       = VipLoginInfo.VipCode;
            rd.MemberInfo.IsDealer    = VipLoginInfo.Col48 != null?int.Parse(VipLoginInfo.Col48) : 0;

            //超级分销体系配置表 为判断是否存在分销体系使用
            var T_SuperRetailTraderConfigbll = new T_SuperRetailTraderConfigBLL(CurrentUserInfo);
            //获取分销体系信息
            var T_SuperRetailTraderConfigInfo = T_SuperRetailTraderConfigbll.QueryByEntity(new T_SuperRetailTraderConfigEntity()
            {
                IsDelete = 0, CustomerId = CurrentUserInfo.CurrentUser.customer_id
            }, null).FirstOrDefault();
            if (T_SuperRetailTraderConfigInfo != null)
            {
                rd.MemberInfo.CanBeSuperRetailTrader = 1;
            }
            else
            {
                rd.MemberInfo.CanBeSuperRetailTrader = 0;
            }
            rd.MemberInfo.SuperRetailTraderID = VipLoginInfo.Col26;
            //rd.MemberInfo.Integration = VipLoginInfo.Integration ?? 0;//会员积分

            #region 会员有效积分
            var vipIntegralBLL  = new VipIntegralBLL(CurrentUserInfo);
            var vipIntegralInfo = vipIntegralBLL.QueryByEntity(new VipIntegralEntity()
            {
                VipID = UserID, VipCardCode = VipLoginInfo.VipCode
            }, null).FirstOrDefault();
            if (vipIntegralInfo != null)
            {
                rd.MemberInfo.Integration = vipIntegralInfo.ValidIntegral != null ? vipIntegralInfo.ValidIntegral.Value : 0;
            }
            #endregion

            //会员等级
            //rd.MemberInfo.VipLevelName = string.IsNullOrEmpty(vipLoginBLL.GetVipLeave(UserID)) ? null : vipLoginBLL.GetVipLeave(UserID);
            #region 会员卡名称
            var                vipCardVipMappingBLL = new VipCardVipMappingBLL(CurrentUserInfo);
            var                vipCardBLL           = new VipCardBLL(CurrentUserInfo);
            var                vipCardTypeBLL       = new SysVipCardTypeBLL(CurrentUserInfo);
            var                vipCardRuleBLL       = new VipCardRuleBLL(CurrentUserInfo);
            var                vipT_InoutBLL        = new T_InoutBLL(CurrentUserInfo);
            VipAmountBLL       vipAmountBLL         = new VipAmountBLL(CurrentUserInfo);
            ShoppingCartBLL    service     = new ShoppingCartBLL(CurrentUserInfo);
            ShoppingCartEntity queryEntity = new ShoppingCartEntity();
            queryEntity.VipId = UserID;
            int totalQty = service.GetListQty(queryEntity);
            rd.MemberInfo.ShopCartCount = totalQty;
            //定义当前自定义等级
            int?CurVipLevel        = 0;
            var vipCardMappingInfo = vipCardVipMappingBLL.QueryByEntity(new VipCardVipMappingEntity()
            {
                VIPID = UserID, CustomerID = CurrentUserInfo.ClientID
            },
                                                                        new OrderBy[] { new OrderBy()
                                                                                        {
                                                                                            FieldName = "CreateTime", Direction = OrderByDirections.Desc
                                                                                        } }).FirstOrDefault();
            if (vipCardMappingInfo != null)
            {
                var vipCardInfo = vipCardBLL.QueryByEntity(new VipCardEntity()
                {
                    VipCardID = vipCardMappingInfo.VipCardID, VipCardStatusId = 1
                }, null).FirstOrDefault();
                if (vipCardInfo != null)
                {
                    var vipCardTypeInfo = vipCardTypeBLL.QueryByEntity(new SysVipCardTypeEntity()
                    {
                        VipCardTypeID = vipCardInfo.VipCardTypeID
                    }, null).FirstOrDefault();
                    if (vipCardTypeInfo != null)
                    {
                        rd.MemberInfo.VipLevelName     = vipCardTypeInfo.VipCardTypeName != null ? vipCardTypeInfo.VipCardTypeName : "";
                        rd.MemberInfo.CardTypeImageUrl = vipCardTypeInfo.PicUrl != null ? vipCardTypeInfo.PicUrl : "";
                        rd.MemberInfo.CardTypePrice    = vipCardTypeInfo.Prices != null ? vipCardTypeInfo.Prices.Value : 0;
                        rd.MemberInfo.IsExtraMoney     = vipCardTypeInfo.IsExtraMoney != null ? vipCardTypeInfo.IsExtraMoney : 0;
                        CurVipLevel             = vipCardTypeInfo.VipCardLevel;
                        rd.MemberInfo.IsPrepaid = vipCardTypeInfo.Isprepaid;
                        if (CurVipLevel > 1)
                        {
                            var VipCardTypeSysInfo = vipCardTypeBLL.GetBindVipCardTypeInfo(CurrentUserInfo.ClientID, VipLoginInfo.Phone, pRequest.UserID, CurVipLevel);
                            if (VipCardTypeSysInfo == null || VipCardTypeSysInfo.Tables[0].Rows.Count == 0)
                            {
                                rd.MemberInfo.IsNeedCard = 2;
                            }
                        }
                        else
                        {
                            rd.MemberInfo.IsNeedCard = 1;
                        }
                        //因为卡等级不能重复,知道当前等级后查找相应的下一级是否是自动升级(消费升级)
                        var NextVipCardTypeInfo = vipCardTypeBLL.QueryByEntity(new SysVipCardTypeEntity()
                        {
                            VipCardLevel = CurVipLevel + 1, CustomerID = CurrentUserInfo.ClientID
                        }, null).FirstOrDefault();
                        if (NextVipCardTypeInfo != null)
                        {
                            //获取当前会员的消费金额信息
                            decimal CurVipConsumptionAmount = 0;
                            decimal VipConsumptionInfo      = vipT_InoutBLL.GetVipSumAmount(UserID);
                            if (VipConsumptionInfo > 0)
                            {
                                CurVipConsumptionAmount = Convert.ToDecimal(Convert.ToDecimal(VipConsumptionInfo).ToString("0.00"));
                            }
                            //知道下一等级后要判断,升级条件是否是消费升级
                            //定义累积消费金额
                            decimal AccumulatedAmount      = 0;
                            var     vipCardTypeUpGradeInfo = vipCardTypeBLL.GetVipCardTypeUpGradeInfo(CurrentUserInfo.ClientID, CurVipLevel);
                            if (vipCardTypeUpGradeInfo != null && vipCardTypeUpGradeInfo.Tables[0].Rows.Count > 0)
                            {
                                //判断拉取的所有卡等级里的最近的一级满足条件即可返回提示所需的值
                                int flag = 0;
                                foreach (DataRow dr in vipCardTypeUpGradeInfo.Tables[0].Rows)
                                {
                                    AccumulatedAmount = Convert.ToDecimal(Convert.ToDecimal(dr["BuyAmount"].ToString()).ToString("0.00"));
                                    //获取消费升级还需多少钱
                                    if (AccumulatedAmount > CurVipConsumptionAmount && flag == 0)
                                    {
                                        flag = 1;
                                        rd.MemberInfo.UpGradeNeedMoney = AccumulatedAmount - CurVipConsumptionAmount;
                                        if (rd.MemberInfo.UpGradeNeedMoney > 0)
                                        {
                                            rd.MemberInfo.UpgradePrompt = "还需要消费" + rd.MemberInfo.UpGradeNeedMoney + "元可以升级啦,快点通知会员!";
                                        }
                                    }
                                }
                            }
                        }

                        var VipCardRuleInfo = vipCardRuleBLL.QueryByEntity(new VipCardRuleEntity()
                        {
                            CustomerID = CurrentUserInfo.ClientID, VipCardTypeID = vipCardTypeInfo.VipCardTypeID
                        }, null).FirstOrDefault();
                        if (VipCardRuleInfo != null)
                        {
                            rd.MemberInfo.CardDiscount = Convert.ToDecimal(Convert.ToDecimal((VipCardRuleInfo.CardDiscount / 10)).ToString("0.00"));
                        }
                    }
                }
            }
            else
            {
                //表示需要领卡,并展示等级为1的默认卡
                rd.MemberInfo.IsNeedCard = 0;
                var VipCardTypeData = vipCardTypeBLL.QueryByEntity(new SysVipCardTypeEntity()
                {
                    VipCardLevel = 1, CustomerID = CurrentUserInfo.ClientID
                }, null).FirstOrDefault();
                if (VipCardTypeData != null)
                {
                    rd.MemberInfo.CardTypeImageUrl = VipCardTypeData.PicUrl != null ? VipCardTypeData.PicUrl : "";
                }
            }
            //获取红利/// decimal[0]=总收入(红利) decimal[2]=支出余额 decimal[1]=总提现金额
            decimal[] array = vipAmountBLL.GetVipSumAmountByCondition(UserID, CurrentUserInfo.ClientID, true);
            if (array[0] != null)
            {
                rd.MemberInfo.ProfitAmount = array[0];
            }
            //是否有付费的会员卡
            List <IWhereCondition> freeCardCon = new List <IWhereCondition> {
            };
            freeCardCon.Add(new EqualsCondition()
            {
                FieldName = "CustomerID", Value = CurrentUserInfo.ClientID
            });
            freeCardCon.Add(new DirectCondition("Prices>0"));
            var freeCardTypeInfo = vipCardTypeBLL.Query(freeCardCon.ToArray(), null).FirstOrDefault();
            if (freeCardTypeInfo != null)
            {
                rd.MemberInfo.IsCostCardType = 1;
            }
            else
            {
                rd.MemberInfo.IsCostCardType = 0;
            }

            #endregion

            rd.MemberInfo.Status       = VipLoginInfo.Status.HasValue ? VipLoginInfo.Status.Value : 1;
            rd.MemberInfo.CouponsCount = couponCount;
            rd.MemberInfo.IsActivate   = (VipLoginInfo.IsActivate.HasValue && VipLoginInfo.IsActivate.Value == 1 ? true : false);
            var customerBasicSettingBll = new CustomerBasicSettingBLL(CurrentUserInfo);
            rd.MemberInfo.MemberBenefits = customerBasicSettingBll.GetMemberBenefits(pRequest.CustomerID);



            //获取标签信息
            TagsBLL TagsBLL = new TagsBLL(base.CurrentUserInfo);


            var dsIdentity = TagsBLL.GetVipTagsList("", UserID);//“车主标签”  传7
            if (dsIdentity != null && dsIdentity.Tables.Count > 0 && dsIdentity.Tables[0].Rows.Count > 0)
            {
                rd.IdentityTagsList = DataTableToObject.ConvertToList <TagsInfo>(dsIdentity.Tables[0]).ToArray(); //“年龄段”  传8
            }


            #region 获取注册表单的列明和值

            var vipEntity = vipLoginBLL.QueryByEntity(new VipEntity()
            {
                VIPID = UserID
            }, null);

            if (vipEntity == null || vipEntity.Length == 0)
            {
                return(rd);
            }
            else
            {
                var ds = vipLoginBLL.GetVipColumnInfo(CurrentUserInfo.ClientID, "online005");

                var vipDs = vipLoginBLL.GetVipInfo(UserID);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    var temp = ds.Tables[0].AsEnumerable().Select(t => new MemberControlInfo()
                    {
                        ColumnName  = t["ColumnName"].ToString(),
                        ControlType = Convert.ToInt32(t["ControlType"]),
                        ColumnValue = vipDs.Tables[0].Rows[0][t["ColumnName"].ToString()].ToString(),
                        ColumnDesc  = t["columnDesc"].ToString()
                    });

                    rd.MemberControlList = temp.ToArray();
                }
            }

            //var vipamountBll = new VipAmountBLL(this.CurrentUserInfo);

            //var vipAmountEntity = vipamountBll.GetByID(UserID);


            var unitBll = new UnitBLL(this.CurrentUserInfo);
            //Hashtable htPara = new Hashtable();
            //htPara["MemberID"] = UserID;
            //htPara["CustomerID"] = CurrentUserInfo.ClientID;
            //htPara["PageIndex"] = 1;
            //htPara["PageSize"] = 10;
            //DataSet dsMyAccount = unitBll.GetMyAccount(htPara);

            //if (dsMyAccount.Tables[0].Rows.Count > 0)
            //{
            //    //rd.AccountList = DataTableToObject.ConvertToList<AccountInfo>(dsMyAccount.Tables[0]);
            //    //rd.MemberInfo.Balance = Convert.ToDecimal(dsMyAccount.Tables[0].Rows[0]["Total"].ToString());
            //    //rd.TotalPageCount = int.Parse(dsMyAccount.Tables[0].Rows[0]["PageCount"].ToString());

            //}
            //else
            //    rd.MemberInfo.Balance = 0;

            //返现 add by Henry 2015-4-15
            var vipAmountBll = new VipAmountBLL(CurrentUserInfo);
            //var vipAmountInfo = vipAmountBll.GetByID(UserID);
            var vipAmountInfo = vipAmountBll.QueryByEntity(new VipAmountEntity()
            {
                VipId = UserID, VipCardCode = VipLoginInfo.VipCode
            }, null).FirstOrDefault();
            decimal returnAmount = 0;
            decimal amount       = 0;
            if (vipAmountInfo != null)
            {
                returnAmount = vipAmountInfo.ValidReturnAmount == null ? 0 : vipAmountInfo.ValidReturnAmount.Value;
                amount       = vipAmountInfo.EndAmount == null ? 0 : vipAmountInfo.EndAmount.Value;
            }
            rd.MemberInfo.ReturnAmount = returnAmount; //返现
            rd.MemberInfo.Balance      = amount;       //余额
            #endregion


            //获取订单的日期和订单的里的商品名称、商品单价、商品数量
            //先获取订单列表,再获取订单详细信息
            int?         pageSize     = 3; //rp.Parameters.PageSize;,只取三条记录
            int?         pageIndex    = 1; //rp.Parameters.PageIndex;
            string       OrderBy      = "";
            string       OrderType    = "";
            T_InoutBLL   T_InoutBLL   = new T_InoutBLL(CurrentUserInfo);
            InoutService InoutService = new InoutService(CurrentUserInfo);
            //只取状态为700的
            //根据订单列表取订单详情
            DataSet dsOrder = T_InoutBLL.GetOrdersByVipID(rd.MemberInfo.VipID, pageIndex ?? 1, pageSize ?? 15, OrderBy, OrderType);//获取会员信息
            if (dsOrder != null && dsOrder.Tables.Count != 0 && dsOrder.Tables[0].Rows.Count != 0)
            {
                List <JIT.CPOS.DTO.Module.VIP.Login.Response.OrderInfo> orderList = DataTableToObject.ConvertToList <JIT.CPOS.DTO.Module.VIP.Login.Response.OrderInfo>(dsOrder.Tables[1]);
                foreach (JIT.CPOS.DTO.Module.VIP.Login.Response.OrderInfo oi in orderList)
                {
                    IList <InoutDetailInfo> detailList = InoutService.GetInoutDetailInfoByOrderId(oi.order_id);
                    oi.DetailList = detailList;
                }
                rd.OrderList = orderList;
            }

            MessageInfo message = new MessageInfo();


            InnerGroupNewsBLL InnerGroupNewsService = new InnerGroupNewsBLL(CurrentUserInfo);
            SetoffToolsBLL    setofftoolsService    = new SetoffToolsBLL(CurrentUserInfo);

            //1=微信用户 2=APP员工
            int UnReadInnerMessageCount = InnerGroupNewsService.GetVipInnerGroupNewsUnReadCount(CurrentUserInfo.UserID, pRequest.CustomerID, 1, null, Convert.ToDateTime(VipLoginInfo.CreateTime));
            var setofftoolsMessageCount = setofftoolsService.GetUnReadSetoffToolsCount(CurrentUserInfo.UserID, pRequest.CustomerID, 1, 1);
            message.InnerGroupNewsCount = UnReadInnerMessageCount;
            message.SetoffToolsCount    = setofftoolsMessageCount;
            var VipUpNewsInfo = InnerGroupNewsService.GetVipInnerNewsInfo(CurrentUserInfo.ClientID, 2, 1, 3, 0);
            if (VipUpNewsInfo != null && VipUpNewsInfo.Tables[0].Rows.Count > 0)
            {
                message.UpGradeSucess = VipUpNewsInfo.Tables[0].Rows[0]["Text"] != null ? VipUpNewsInfo.Tables[0].Rows[0]["Text"].ToString() : "";
                //获取通知信息 并更新已读状态 数据如果不是一条进行更新所有数据
                var newsUserMappingBLL = new NewsUserMappingBLL(CurrentUserInfo);
                if (VipUpNewsInfo.Tables[0].Rows.Count > 1)//数据如果不是一条进行更新所有数据
                {
                    foreach (DataRow VipNewsdr in VipUpNewsInfo.Tables[0].Rows)
                    {
                        var vipNewsInfo = newsUserMappingBLL.QueryByEntity(new NewsUserMappingEntity()
                        {
                            CustomerId = CurrentUserInfo.ClientID, MappingID = VipNewsdr["MappingID"].ToString()
                        }, null).FirstOrDefault();
                        if (vipNewsInfo != null)
                        {
                            vipNewsInfo.HasRead = 1;
                            newsUserMappingBLL.Update(vipNewsInfo);
                        }
                    }
                }
                else
                {
                    var vipNewsInfo = newsUserMappingBLL.QueryByEntity(new NewsUserMappingEntity()
                    {
                        CustomerId = CurrentUserInfo.ClientID, MappingID = VipUpNewsInfo.Tables[0].Rows[0]["MappingID"].ToString()
                    }, null).FirstOrDefault();
                    if (vipNewsInfo != null)
                    {
                        vipNewsInfo.HasRead = 1;
                        newsUserMappingBLL.Update(vipNewsInfo);
                    }
                }
            }
            else
            {
                message.UpGradeSucess = "";
            }
            rd.MessageInfo = message;
            return(rd);
        }
    }
Exemplo n.º 17
0
        protected override GetVipAmountDetailRD ProcessRequest(DTO.Base.APIRequest <GetVipAmountDetailRP> pRequest)
        {
            var rd        = new GetVipAmountDetailRD();
            var parameter = pRequest.Parameters;
            LoggingSessionInfo loggingSessionInfo = Default.GetBSLoggingSession(pRequest.CustomerID, pRequest.UserID);
            VipAmountBLL       vipAmountBLL       = new VipAmountBLL(loggingSessionInfo);
            var vipAmountDetailBLL = new VipAmountDetailBLL(loggingSessionInfo);
            //查询参数
            List <IWhereCondition> Condition = new List <IWhereCondition> {
            };

            Condition.Add(new EqualsCondition()
            {
                FieldName = "CustomerId", Value = loggingSessionInfo.ClientID
            });
            List <OrderBy> Orders = new List <OrderBy> {
            };

            //商户条件

            if (parameter.DdividendType == 1) //全部=全部收入+提现明细
            {
                Orders.Add(new OrderBy()
                {
                    FieldName = "createTime", Direction = OrderByDirections.Asc
                });
                Condition.Add(new DirectCondition(" (AmountSourceId = -1 OR AmountSourceId=35 OR AmountSourceId=36 OR AmountSourceId=20) "));  //全部收入+提现信息
            }
            else if (parameter.DdividendType == 2)
            {
                Orders.Add(new OrderBy()
                {
                    FieldName = "createTime", Direction = OrderByDirections.Asc
                });
                Condition.Add(new DirectCondition(" AmountSourceId IN (36,35,20)"));           //全部收入
                Condition.Add(new DirectCondition(" TableType != 'VipWithdrawDepositApply'")); //去除提现
            }
            else if (parameter.DdividendType == 3)
            {
                Orders.Add(new OrderBy()
                {
                    FieldName = "createTime", Direction = OrderByDirections.Asc
                });
                Condition.Add(new DirectCondition(" TableType = 'VipWithdrawDepositApply'")); //只获取提现
            }

            //获取红利余额+提现记录
            var tempList = vipAmountDetailBLL.GetVipAmountDetailAndWithdrawList(Condition.ToArray(), loggingSessionInfo.UserID, Orders.ToArray(), parameter.PageSize, parameter.PageIndex);

            rd.TotalCount          = tempList.RowCount;
            rd.TotalPageCount      = tempList.PageCount;
            rd.VipAmountDetailList = tempList.Entities.Select(t => new VipAmountDetailInfo()
            {
                AmountSourceName = t.AmountSourceName,
                Amount           = t.Amount.Value,
                CreateTime       = t.CreateTime.Value.ToString("yyyy-MM-dd"),
                Reason           = t.Reason
            }).ToArray();

            #region 统计信息
            //查询 提现余额+当前余额+总收入
            decimal[] array = vipAmountBLL.GetVipSumAmountByCondition(CurrentUserInfo.UserID, CurrentUserInfo.ClientID, true);
            rd.CurrentAmount  = array[0]; //红利余额{总金额}
            rd.WithdrawAmount = array[1]; //支出余额
            rd.InAmount       = array[2]; //提现金额
            #endregion
            return(rd);
        }
Exemplo n.º 18
0
        protected override EmptyResponseData ProcessRequest(APIRequest <SetVipAmountRP> pRequest)
        {
            var rd   = new EmptyResponseData();
            var para = pRequest.Parameters;
            var loggingSessionInfo = new SessionManager().CurrentUserLoginInfo; //登录状态信息
            var vipAmountBLL       = new VipAmountBLL(loggingSessionInfo);
            var vipAmountDetailBLL = new VipAmountDetailBLL(loggingSessionInfo);
            var objectImagesBLL    = new ObjectImagesBLL(loggingSessionInfo);    //图片表业务对象实例化
            var unitBLL            = new t_unitBLL(loggingSessionInfo);

            var vipBLL = new VipBLL(loggingSessionInfo);

            var vipInfo  = vipBLL.GetByID(para.VipID);
            var unitInfo = unitBLL.GetByID(loggingSessionInfo.CurrentUserRole.UnitId);
            var pTran    = vipAmountBLL.GetTran(); //事务

            var vipAmountEntity = vipAmountBLL.QueryByEntity(new VipAmountEntity()
            {
                VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
            }, null).FirstOrDefault();

            using (pTran.Connection)
            {
                try
                {
                    var amountDetail = new VipAmountDetailEntity()
                    {
                        Amount         = para.Amount,
                        AmountSourceId = para.AmountSourceID,
                        ObjectId       = "",
                        Reason         = para.Reason,
                        Remark         = para.Remark
                    };
                    string vipAmountDetailId = string.Empty;
                    if (para.AmountSourceID == "23")
                    {      //人工调整余额
                        vipAmountDetailId = vipAmountBLL.AddVipAmount(vipInfo, unitInfo, ref vipAmountEntity, amountDetail, pTran, loggingSessionInfo);

                        if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                        {//发送微信账户余额变动模板消息
                            var CommonBLL = new CommonBLL();
                            CommonBLL.BalanceChangedMessage("人工调整", vipAmountEntity, amountDetail, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                        }
                    }
                    else if (para.AmountSourceID == "24")
                    {  //人工调整返现
                        vipAmountDetailId = vipAmountBLL.AddReturnAmount(vipInfo, unitInfo, vipAmountEntity, ref amountDetail, pTran, loggingSessionInfo);
                        if (!string.IsNullOrWhiteSpace(vipAmountDetailId))
                        {//发送返现到账通知微信模板消息
                            var CommonBLL = new CommonBLL();
                            CommonBLL.CashBackMessage("人工调整", amountDetail.Amount, vipInfo.WeiXinUserId, vipInfo.VIPID, loggingSessionInfo);
                        }
                    }
                    //增加图片上传
                    if (!string.IsNullOrEmpty(para.ImageUrl))
                    {
                        var objectImagesEntity = new ObjectImagesEntity()
                        {
                            ImageId  = Guid.NewGuid().ToString(),
                            ObjectId = vipAmountDetailId,
                            ImageURL = para.ImageUrl
                        };
                        objectImagesBLL.Create(objectImagesEntity);
                    }
                    pTran.Commit();  //提交事物
                }
                catch (APIException apiEx)
                {
                    pTran.Rollback();//回滚事物
                    throw new APIException(apiEx.ErrorCode, apiEx.Message);
                }
                catch (Exception ex)
                {
                    pTran.Rollback();//回滚事物
                    throw new Exception(ex.Message);
                }
            }
            return(rd);
        }
Exemplo n.º 19
0
        public HttpResponseMessage MemberBenefits(string vipId, decimal?TotalPayAmount)
        {
            string guid = Guid.NewGuid().ToString();

            Loggers.Debug(new DebugLogInfo()
            {
                Message  = $"调用[api/Vip/MemberBenefits],参数:\"vipId:{vipId}\"",
                UserID   = vipId,
                ClientID = guid
            });
            try
            {
                if (string.IsNullOrEmpty(vipId))
                {
                    throw new Exception("会员数据不能为空!");
                }

                var orderResponse = new MemberBenefitsResponeModel();

                #region MyRegion

                string customerid         = ConfigurationManager.AppSettings["CustomerId"].Trim();
                var    loggingSessionInfo = Default.GetLoggingSession(customerid, vipId);
                loggingSessionInfo.Conn = ConfigurationManager.AppSettings["Conn"].Trim();

                var bll     = new VipBLL(loggingSessionInfo);
                var vipInfo = bll.GetByID(vipId); //会员信息

                if (vipInfo == null)
                {
                    throw new APIException("没有该会员信息")
                          {
                              ErrorCode = 302
                          };
                }

                #endregion

                //获取社会化销售配置和积分返现配置
                var       basicSettingBll = new CustomerBasicSettingBLL(loggingSessionInfo);
                Hashtable htSetting       = basicSettingBll.GetSocialSetting();

                orderResponse.EnableIntegral   = int.Parse(htSetting["enableIntegral"].ToString());
                orderResponse.EnableRewardCash = int.Parse(htSetting["enableRewardCash"].ToString());

                //应付金额
                decimal?totalPayAmount = 0;
                if (TotalPayAmount != null)
                {
                    totalPayAmount = TotalPayAmount;
                }

                #region 启用积分

                if (orderResponse.EnableIntegral == 1)
                {
                    //2.获取会员的积分和账户余额
                    var vipIntegralbll = new VipIntegralBLL(loggingSessionInfo);
                    //var vipIntegralEntity = vipIntegralbll.GetByID(rp.UserID);
                    //根据会员和会员卡号获取积分
                    var vipIntegralEntity =
                        vipIntegralbll.QueryByEntity(
                            new VipIntegralEntity()
                    {
                        VipID = vipInfo.UserId, VipCardCode = vipInfo.VipCode
                    }, null)
                        .FirstOrDefault();
                    if (vipIntegralEntity == null)
                    {
                        orderResponse.Integral       = 0;
                        orderResponse.IntegralAmount = 0;
                    }
                    else
                    {
                        decimal validIntegral = vipIntegralEntity.ValidIntegral ?? 0; //会员积分

                        int totalIntegral = 0;                                        //可使用积分(取整)
                        //if (int.Parse(htSetting["rewardsType"].ToString()) == 1)//按商品奖励
                        //    totalIntegral = (int)Math.Round(bll.GetIntegralBySkuId(skuIdList), 1);

                        //积分使用上限比例
                        decimal pointsRedeemUpLimit = decimal.Parse(htSetting["pointsRedeemUpLimit"].ToString()) / 100;
                        //3.获取积分与金额的兑换比例
                        var integralAmountPre = bll.GetIntegralAmountPre(customerid);
                        if (integralAmountPre == 0)
                        {
                            integralAmountPre = (decimal)0.01;
                        }

                        totalIntegral = (int)Math.Round(totalPayAmount.Value * pointsRedeemUpLimit * integralAmountPre, 1);
                        //可使用的积分
                        orderResponse.Integral = validIntegral > totalIntegral ? totalIntegral : validIntegral;

                        if (totalPayAmount == 0)
                        {
                            orderResponse.Integral = Convert.ToDecimal(vipIntegralEntity.ValidIntegral);
                        }

                        //rd.IntegralAmount = rd.Integral * integralAmountPre;
                        orderResponse.IntegralAmount = bll.GetAmountByIntegralPer(loggingSessionInfo.ClientID,
                                                                                  orderResponse.Integral);
                        orderResponse.IntegralDesc = "使用积分" + orderResponse.Integral.ToString("0") + ",可兑换"
                                                     + orderResponse.IntegralAmount.ToString("0.00") + "元";
                        orderResponse.PointsRedeemLowestLimit =
                            int.Parse(htSetting["pointsRedeemLowestLimit"].ToString());
                    }
                }

                #endregion

                //根据会员和会员卡号获取余额和返现
                var vipAmountBll  = new VipAmountBLL(loggingSessionInfo);
                var vipAmountInfo =
                    vipAmountBll.QueryByEntity(
                        new VipAmountEntity()
                {
                    VipId = vipInfo.VIPID, VipCardCode = vipInfo.VipCode
                }, null)
                    .FirstOrDefault();

                #region 启用返现

                if (orderResponse.EnableRewardCash == 1)
                {
                    if (vipAmountInfo != null)
                    {
                        //累计返现金额
                        decimal returnAmount = vipAmountInfo.ValidReturnAmount == null
                            ? 0
                            : vipAmountInfo.ValidReturnAmount.Value;
                        //订单可使用最大返现金额
                        decimal returnAmountOrder = totalPayAmount.Value *
                                                    (decimal.Parse(htSetting["cashRedeemUpLimit"].ToString()) / 100);
                        orderResponse.ReturnAmount          = returnAmount > returnAmountOrder ? returnAmountOrder : returnAmount;
                        orderResponse.CashRedeemLowestLimit =
                            decimal.Parse(htSetting["cashRedeemLowestLimit"].ToString());
                    }
                }

                #endregion

                //账户余额
                //var vipEndAmount = bll.GetVipEndAmount(rp.UserID);
                //rd.VipEndAmount = totalPayAmount > vipEndAmount ? vipEndAmount : totalPayAmount;
                if (vipAmountInfo != null)
                {
                    orderResponse.VipEndAmount = vipAmountInfo.EndAmount.Value;
                }

                //获取会员折扣
                var     sysVipCardGradeBLL = new SysVipCardGradeBLL(loggingSessionInfo);
                decimal vipDiscount        = 10; //会员折扣
                //如果订单业务类型为null
                var orderReason = GetOrderReason(EnumOrderReason.Pos);
                //超级分销、团购、抢购、砍价商品没有会员折扣
                if (orderReason != "CB43DD7DD1C94853BE98C4396738E00C" &&
                    orderReason != "671E724C85B847BDA1E96E0E5A62055A" &&
                    orderReason != "096419BFDF394F7FABFE0DFCA909537F")
                {
                    //if (rp.Parameters.DiscountType == 0)
                    vipDiscount = sysVipCardGradeBLL.GetVipDiscount();
                }

                orderResponse.VipDiscount = vipDiscount;

                var tempAmount = totalPayAmount.Value;
                if (totalPayAmount.Value > 0 && vipDiscount > 0)
                {
                    tempAmount = totalPayAmount.Value * (vipDiscount / 10);
                }

                var ds = bll.GetVipCouponDataSet(vipInfo.VIPID, tempAmount, 2, string.Empty, 1, customerid);

                if (ds.Tables[0].Rows.Count > 0)
                {
                    var temp = ds.Tables[0].AsEnumerable().Select(t => new CouponModel()
                    {
                        CouponId     = t["CouponID"].ToString(),
                        CouponCode   = t["CouponCode"].ToString(),
                        CouponAmount = Convert.ToDecimal(t["parValue"]),
                        CouponName   = t["CoupnName"].ToString(),
                        CouponDesc   = t["CouponDesc"].ToString(),
                        DisplayIndex = Convert.ToInt32(t["displayIndex"]),
                        EnableFlag   = Convert.ToInt32(t["EnableFlag"]),
                        //ValidDateDesc = t["ValidDateDesc"].ToString(),
                        StartDate = t["BeginDate"].ToString(),
                        EndDate   = t["EndDate"].ToString()
                    });
                    orderResponse.CouponInfoList = temp.ToList();
                }

                orderResponse.IsSucess = true;

                var json = new JavaScriptSerializer().Serialize(orderResponse);
                Loggers.Debug(new DebugLogInfo()
                {
                    Message  = $"调用[api/Vip/MemberBenefits],返回参数:\"{json}\"",
                    UserID   = vipId,
                    ClientID = guid
                });

                return(Request.CreateResponse(HttpStatusCode.OK, orderResponse));
            }
            catch (Exception ex)
            {
                var orderResponse = new MemberBenefitsResponeModel()
                {
                    IsSucess     = false,
                    ErrorMessage = ex.Message
                };
                Loggers.Debug(new DebugLogInfo()
                {
                    Message  = $"[api/Vip/MemberBenefits]错误,参数:\"ErrorMsg:{ex.Message}\"",
                    UserID   = vipId,
                    ClientID = guid
                });
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, orderResponse));
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// 根据用户发送的二维码去二维码表中VipDCode匹配
        /// </summary>
        /// <param name="content"></param>
        /// <param name="vipID"></param>
        public void StoreRebate(string content, string vipID)
        {
            content = content.Trim();
            BaseService.WriteLogWeixin("返利信息:" + content);

            VipDCodeBLL          bll            = new VipDCodeBLL(requestParams.LoggingSessionInfo);
            WXSalesPolicyRateBLL SalesPolicybll = new WXSalesPolicyRateBLL(requestParams.LoggingSessionInfo);

            //var tran = bll.GetTran();
            try
            {
                //判断当前发送二维码的微信号是否是 二维码表中当前二维码Code的会员 VipId=vipID;
                //var temp = bll.QueryByEntity(new VipDCodeEntity { IsDelete = 0, DCodeId = content}, null);
                var     temp         = bll.GetByID(content);
                decimal?ReturnAmount = 0;
                string  PushInfo     = string.Empty;
                //using (tran.Connection)
                //{
                if (temp != null)   //如果可以匹配,则更新二维码表中的会员ID,OpenId
                {
                    #region 1.更新返现金额。更新返现状态
                    VipDCodeEntity entity = new VipDCodeEntity();
                    entity = temp;
                    DataSet ds = SalesPolicybll.getReturnAmount(Convert.ToDecimal(entity.SalesAmount), entity.CustomerId);
                    if (ds != null && ds.Tables[0].Rows.Count == 0 && ds.Tables[1].Rows.Count == 0)
                    {
                        BaseService.WriteLogWeixin("该客户没有配置策略信息");

                        throw new Exception("该客户没有配置策略信息");
                    }
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        //返现金额
                        ReturnAmount = entity.ReturnAmount = Convert.ToDecimal(ds.Tables[0].Rows[0]["ReturnAmount"].ToString());
                        //返现消息内容
                        PushInfo = ds.Tables[0].Rows[0]["PushInfo"].ToString();

                        BaseService.WriteLogWeixin("PushInfo1:" + PushInfo);
                    }
                    else
                    {
                        //返现金额
                        ReturnAmount = entity.ReturnAmount = Convert.ToDecimal(ds.Tables[1].Rows[0]["ReturnAmount"].ToString());
                        //返现消息内容
                        PushInfo = ds.Tables[1].Rows[0]["PushInfo"].ToString();

                        BaseService.WriteLogWeixin("PushInfo2:" + PushInfo);
                    }

                    entity.OpenId       = requestParams.OpenId;
                    entity.VipId        = vipID;
                    entity.ReturnAmount = ReturnAmount;
                    VipAmountBLL Amountbll = new VipAmountBLL(requestParams.LoggingSessionInfo);

                    var vipBll = new VipBLL(requestParams.LoggingSessionInfo);

                    var vipEntity = vipBll.GetByID(vipID);


                    string strErrormessage = "";
                    if (entity.IsReturn != 1)  //当未返现的时候金额变更
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "begin update VipDcode:"
                        });

                        if (Amountbll.SetVipAmountChange(entity.CustomerId, 2, vipID, ReturnAmount ?? 0, entity.ObjectId, "门店返现", "IN", out strErrormessage))
                        {
                            entity.IsReturn = 1;
                            entity.DCodeId  = content;
                            bll.Update(entity); //更新返现金额

                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = "update VipDcode success"
                            });
                        }
                    }

                    #endregion



                    var     vipamountBll    = new VipAmountBLL(requestParams.LoggingSessionInfo);
                    var     vipAmountEntity = vipamountBll.GetByID(vipID);
                    decimal endAmount       = 0;
                    if (vipAmountEntity != null)
                    {
                        endAmount = vipAmountEntity.EndAmount ?? 0;
                    }
                    var message = PushInfo.Replace("#SalesAmount#", entity.SalesAmount.ToString()).Replace("#ReturnAmount#", Convert.ToDecimal(ReturnAmount).ToString("0.00")).Replace("#EndAmount#", endAmount.ToString("0.00")).Replace("#VipName#", vipEntity.VipName);

                    #region 插入门店返现推送消息日志表
                    WXSalesPushLogBLL    PushLogbll = new WXSalesPushLogBLL(requestParams.LoggingSessionInfo);
                    WXSalesPushLogEntity pushLog    = new WXSalesPushLogEntity();
                    pushLog.LogId    = Guid.NewGuid();
                    pushLog.WinXin   = requestParams.WeixinId;
                    pushLog.OpenId   = requestParams.OpenId;
                    pushLog.VipId    = vipID;
                    pushLog.PushInfo = message;
                    pushLog.DCodeId  = content;
                    pushLog.RateId   = Guid.NewGuid();
                    PushLogbll.Create(pushLog);
                    #endregion
                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = message
                    });
                    string code = JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage(message, "1", requestParams.LoggingSessionInfo, vipEntity);

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "消息推送完成,code=" + code + ", message=" + message
                    });

                    #region 增加抽奖信息
                    var rateList = SalesPolicybll.QueryByEntity(new WXSalesPolicyRateEntity {
                        CustomerId = temp.CustomerId
                    }, null);
                    if (rateList == null || rateList.Length == 0)
                    {
                        //rateList = SalesPolicybll.QueryByEntity(new WXSalesPolicyRateEntity{CustomerId =null},null);
                        rateList = SalesPolicybll.GetWxSalesPolicyRateList().ToArray();
                    }

                    if (rateList != null && rateList.Length > 0)
                    {
                        var wxSalespolicyRateMapBll = new WXSalesPolicyRateObjectMappingBLL(requestParams.LoggingSessionInfo);

                        var rateMappingEntity =
                            wxSalespolicyRateMapBll.QueryByEntity(new WXSalesPolicyRateObjectMappingEntity {
                            RateId = rateList[0].RateId
                        }, null);
                        if (rateMappingEntity != null && rateMappingEntity.Length > 0)
                        {
                            if (Convert.ToDecimal(temp.SalesAmount) >= rateMappingEntity[0].CoefficientAmount)
                            {
                                if (rateMappingEntity[0].PushInfo != null)
                                {
                                    var eventMessage = rateMappingEntity[0].PushInfo.Replace("#CustomerId#", temp.CustomerId).Replace("#EventId#", rateMappingEntity[0].ObjectId).Replace("#VipId#", vipID).Replace("#OpenId#", vipEntity.WeiXinUserId);


                                    BaseService.WriteLogWeixin("微信推送的抽奖活动URL:" + eventMessage);

                                    WXSalesPushLogEntity qrLog = new WXSalesPushLogEntity();
                                    qrLog.LogId    = Guid.NewGuid();
                                    qrLog.WinXin   = requestParams.WeixinId;
                                    qrLog.OpenId   = requestParams.OpenId;
                                    qrLog.VipId    = vipID;
                                    qrLog.PushInfo = eventMessage;
                                    qrLog.DCodeId  = content;
                                    qrLog.RateId   = Guid.NewGuid();
                                    PushLogbll.Create(qrLog);

                                    #region 增加抽奖机会

                                    LEventsVipObjectBLL    eventbll    = new LEventsVipObjectBLL(requestParams.LoggingSessionInfo);
                                    LEventsVipObjectEntity evententity = new LEventsVipObjectEntity();
                                    evententity.MappingId   = Guid.NewGuid().ToString();
                                    evententity.EventId     = rateMappingEntity[0].ObjectId;
                                    evententity.VipId       = vipID;
                                    evententity.ObjectId    = "";
                                    evententity.IsCheck     = 0;
                                    evententity.LotteryCode = "0";
                                    evententity.IsLottery   = 0;
                                    eventbll.Create(evententity);
                                    #endregion

                                    JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage(eventMessage, "1", requestParams.LoggingSessionInfo, vipEntity);
                                }
                            }
                        }
                    }
                    #endregion
                }
                // }
            }
            catch (Exception)
            {
                // tran.Rollback();
                throw;
            }
        }
Exemplo n.º 21
0
        public void StoreRebate(string content, string vipID)
        {
            Loggers.Debug(new DebugLogInfo()
            {
                Message = "返利信息:" + content
            });

            var loggingSessionInfo = Default.GetBSLoggingSession("e703dbedadd943abacf864531decdac1", "1");

            VipDCodeBLL          bll            = new VipDCodeBLL(loggingSessionInfo);
            WXSalesPolicyRateBLL SalesPolicybll = new WXSalesPolicyRateBLL(loggingSessionInfo);

            //var tran = bll.GetTran();
            try
            {
                //判断当前发送二维码的微信号是否是 二维码表中当前二维码Code的会员 VipId=vipID;
                //var temp = bll.QueryByEntity(new VipDCodeEntity { IsDelete = 0, DCodeId = content}, null);
                var     temp         = bll.GetByID(content);
                decimal?ReturnAmount = 0;
                string  PushInfo     = string.Empty;
                //using (tran.Connection)
                //{
                if (temp != null)   //如果可以匹配,则更新二维码表中的会员ID,OpenId
                {
                    #region 1.更新返现金额。更新返现状态
                    VipDCodeEntity entity = new VipDCodeEntity();
                    entity = temp;
                    DataSet ds = SalesPolicybll.getReturnAmount(Convert.ToDecimal(entity.SalesAmount), entity.CustomerId);
                    if (ds != null && ds.Tables[0].Rows.Count == 0 && ds.Tables[1].Rows.Count == 0)
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "该客户没有配置策略信息"
                        });

                        throw new Exception("该客户没有配置策略信息");
                    }
                    if (ds != null && ds.Tables[0].Rows.Count > 0)
                    {
                        //返现金额
                        ReturnAmount = entity.ReturnAmount = Convert.ToDecimal(ds.Tables[0].Rows[0]["ReturnAmount"].ToString());
                        //返现消息内容
                        PushInfo = ds.Tables[0].Rows[0]["PushInfo"].ToString();
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "PushInfo1:" + PushInfo
                        });
                    }
                    else
                    {
                        //返现金额
                        ReturnAmount = entity.ReturnAmount = Convert.ToDecimal(ds.Tables[1].Rows[0]["ReturnAmount"].ToString());
                        //返现消息内容
                        PushInfo = ds.Tables[1].Rows[0]["PushInfo"].ToString();

                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "PushInfo2:" + PushInfo
                        });
                    }

                    entity.OpenId       = "oxbbcjg5NBbdpK1T9mDkIzTn434U";
                    entity.VipId        = vipID;
                    entity.ReturnAmount = ReturnAmount;
                    VipAmountBLL Amountbll = new VipAmountBLL(loggingSessionInfo);

                    var vipBll = new VipBLL(loggingSessionInfo);

                    var vipEntity = vipBll.GetByID(vipID);

                    if (temp.IsReturn == 1)
                    {
                        //发送消息

                        JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage("对不起,该返利码已经被领取", "1", loggingSessionInfo, vipEntity);
                        return;
                    }

                    if (DateTime.Now > (temp.CreateTime ?? DateTime.Now).AddDays(1))
                    {
                        //发送消息
                        JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage("对不起,您的返利码已经过期,请在收到返利码后的24小时内使用", "1", loggingSessionInfo, vipEntity);
                        return;
                    }



                    string strErrormessage = "";
                    if (entity.IsReturn != 1)  //当未返现的时候金额变更
                    {
                        Loggers.Debug(new DebugLogInfo()
                        {
                            Message = "begin update VipDcode:"
                        });

                        if (Amountbll.SetVipAmountChange(entity.CustomerId, 2, vipID, ReturnAmount ?? 0, entity.ObjectId, "门店返现", "IN", out strErrormessage))
                        {
                            entity.IsReturn = 1;
                            entity.DCodeId  = content;
                            bll.Update(entity); //更新返现金额

                            Loggers.Debug(new DebugLogInfo()
                            {
                                Message = "update VipDcode success"
                            });
                        }
                    }

                    #endregion



                    var     vipamountBll    = new VipAmountBLL(loggingSessionInfo);
                    var     vipAmountEntity = vipamountBll.GetByID(vipID);
                    decimal endAmount       = 0;
                    if (vipAmountEntity != null)
                    {
                        endAmount = vipAmountEntity.EndAmount ?? 0;
                    }
                    var message = PushInfo.Replace("#SalesAmount#", entity.SalesAmount.ToString()).Replace("#ReturnAmount#", Convert.ToDecimal(ReturnAmount).ToString("0.00")).Replace("#EndAmount#", endAmount.ToString("0.00")).Replace("#VipName#", vipEntity.VipName);

                    #region 插入门店返现推送消息日志表
                    WXSalesPushLogBLL    PushLogbll = new WXSalesPushLogBLL(loggingSessionInfo);
                    WXSalesPushLogEntity pushLog    = new WXSalesPushLogEntity();
                    pushLog.LogId    = Guid.NewGuid();
                    pushLog.WinXin   = "gh_e2b2da1e6edf";
                    pushLog.OpenId   = "oxbbcjg5NBbdpK1T9mDkIzTn434U";
                    pushLog.VipId    = vipID;
                    pushLog.PushInfo = message;
                    pushLog.DCodeId  = content;
                    pushLog.RateId   = Guid.NewGuid();
                    PushLogbll.Create(pushLog);
                    #endregion
                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = message
                    });
                    string code = JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage(message, "1", loggingSessionInfo, vipEntity);

                    Loggers.Debug(new DebugLogInfo()
                    {
                        Message = "消息推送完成,code=" + code + ", message=" + message
                    });

                    #region 增加抽奖信息
                    var rateList = SalesPolicybll.QueryByEntity(new WXSalesPolicyRateEntity {
                        CustomerId = temp.CustomerId
                    }, null);
                    if (rateList == null || rateList.Length == 0)
                    {
                        //rateList = SalesPolicybll.QueryByEntity(new WXSalesPolicyRateEntity{CustomerId =null},null);
                        rateList = SalesPolicybll.GetWxSalesPolicyRateList().ToArray();
                    }

                    if (rateList != null && rateList.Length > 0)
                    {
                        var wxSalespolicyRateMapBll = new WXSalesPolicyRateObjectMappingBLL(loggingSessionInfo);

                        var rateMappingEntity =
                            wxSalespolicyRateMapBll.QueryByEntity(new WXSalesPolicyRateObjectMappingEntity {
                            RateId = rateList[0].RateId
                        }, null);
                        if (rateMappingEntity != null && rateMappingEntity.Length > 0)
                        {
                            if (Convert.ToDecimal(temp.SalesAmount) >= rateMappingEntity[0].CoefficientAmount)
                            {
                                if (rateMappingEntity[0].PushInfo != null)
                                {
                                    var eventMessage = rateMappingEntity[0].PushInfo.Replace("#CustomerId#", temp.CustomerId).Replace("#EventId#", rateMappingEntity[0].ObjectId).Replace("#VipId#", vipID).Replace("#OpenId#", vipEntity.WeiXinUserId);
                                    JIT.CPOS.BS.BLL.WX.CommonBLL.SendWeixinMessage(eventMessage, "1", loggingSessionInfo, vipEntity);
                                }
                            }
                        }
                    }
                    #endregion
                }
                // }
            }
            catch (Exception)
            {
                // tran.Rollback();
                throw;
            }
        }