示例#1
0
        /// <summary>
        /// 下载二维码
        /// </summary>
        /// <param name="coupon"></param>
        /// <param name="strCon"></param>
        /// <returns></returns>
        public DataTable DownloadCoupon(CC_Coupon coupon, string strCustomerid, int downLoadNum, int intIsNotLimitQty)
        {
            var                count              = RedisOpenAPI.Instance.CCCoupon().GetCouponListLength(coupon);
            DataTable          dtCoupon           = new DataTable();
            LoggingSessionInfo loggingSessionInfo = CustomerBLL.Instance.GetBSLoggingSession(strCustomerid, "RedisSystem");


            dtCoupon.Columns.Add("CouponID", typeof(string));
            dtCoupon.Columns.Add("CouponCode", typeof(string));
            dtCoupon.Columns.Add("CouponDesc", typeof(string));
            dtCoupon.Columns.Add("BeginDate", typeof(DateTime));
            dtCoupon.Columns.Add("EndDate", typeof(DateTime));
            dtCoupon.Columns.Add("CouponUrl", typeof(string));
            dtCoupon.Columns.Add("ImageUrl", typeof(string));
            dtCoupon.Columns.Add("Status", typeof(Int32));
            dtCoupon.Columns.Add("CreateTime", typeof(DateTime));
            dtCoupon.Columns.Add("CreateBy", typeof(string));
            dtCoupon.Columns.Add("LastUpdateTime", typeof(DateTime));
            dtCoupon.Columns.Add("LastUpdateBy", typeof(string));
            dtCoupon.Columns.Add("IsDelete", typeof(Int32));
            dtCoupon.Columns.Add("CouponTypeID", typeof(string));
            dtCoupon.Columns.Add("CoupnName", typeof(string));
            dtCoupon.Columns.Add("DoorID", typeof(string));
            dtCoupon.Columns.Add("CouponPwd", typeof(string));
            dtCoupon.Columns.Add("CollarCardMode", typeof(string));
            dtCoupon.Columns.Add("CustomerID", typeof(string));

            DataTable dtCouponExport = new DataTable();

            dtCouponExport.Columns.Add("CouponCode", typeof(string));
            CC_Connection connection = new CC_Connection();
            string        strCon     = string.Empty;

            if (count.Code == ResponseCode.Success)
            {
                if (count.Result > 0)
                {
                    connection = new RedisConnectionBLL().GetConnection(strCustomerid);
                    if (connection.ConnectionStr == null)
                    {
                        strCon = GetCustomerConn(strCustomerid);
                    }
                    else
                    {
                        strCon = connection.ConnectionStr;
                    }

                    long num = 0;
                    if (downLoadNum > count.Result)
                    {
                        if (intIsNotLimitQty == 1)
                        {
                            var bllCouponType = new CouponTypeBLL(loggingSessionInfo);
                            bllCouponType.UpdateCouponTypeIssuedQty(coupon.CouponTypeId, downLoadNum);
                            coupon.CouponLenth = downLoadNum;
                            RedisOpenAPI.Instance.CCCoupon().SetCouponList(coupon);
                            num = downLoadNum;
                        }
                        else
                        {
                            num = count.Result;
                        }
                    }
                    else
                    {
                        num = downLoadNum;
                    }

                    for (int i = 0; i < num; i++)
                    {
                        var response = RedisGetCoupon(coupon);
                        if (response.Code == ResponseCode.Success)
                        {
                            String uperStr       = StringUtil.GetRandomUperStr(4);
                            String strInt        = StringUtil.GetRandomStrInt(8);
                            string strCouponCode = uperStr + "-" + strInt;

                            DataRow dr_Coupon = dtCoupon.NewRow();
                            dr_Coupon["CouponID"]   = Guid.NewGuid().ToString();
                            dr_Coupon["CouponCode"] = strCouponCode;
                            dr_Coupon["CouponDesc"] = response.Result.CouponTypeDesc;
                            if (response.Result.ServiceLife > 0)
                            {
                                dr_Coupon["BeginDate"] = DateTime.Now;
                                dr_Coupon["EndDate"]   = DateTime.Now.Date.AddDays(response.Result.ServiceLife - 1).ToShortDateString() + " 23:59:59.998";
                            }
                            else
                            {
                                dr_Coupon["BeginDate"] = response.Result.BeginTime;
                                dr_Coupon["EndDate"]   = response.Result.EndTime;
                            }
                            dr_Coupon["CouponUrl"]      = "";
                            dr_Coupon["ImageUrl"]       = "";
                            dr_Coupon["Status"]         = 0;
                            dr_Coupon["CreateTime"]     = DateTime.Now;
                            dr_Coupon["CreateBy"]       = "Redis";
                            dr_Coupon["LastUpdateTime"] = DateTime.Now;
                            dr_Coupon["LastUpdateBy"]   = "Redis";
                            dr_Coupon["IsDelete"]       = 0;
                            dr_Coupon["CouponTypeID"]   = response.Result.CouponTypeId;
                            dr_Coupon["CoupnName"]      = response.Result.CouponTypeName;
                            dr_Coupon["DoorID"]         = "";
                            dr_Coupon["CouponPwd"]      = "";
                            dr_Coupon["CollarCardMode"] = "";
                            dr_Coupon["CustomerID"]     = coupon.CustomerId;
                            dtCoupon.Rows.Add(dr_Coupon);

                            DataRow dr_CouponExport = dtCouponExport.NewRow();
                            dr_CouponExport["CouponCode"] = strCouponCode;
                            dtCouponExport.Rows.Add(dr_CouponExport);
                        }
                    }
                    if (dtCoupon != null && dtCoupon.Rows.Count > 0)
                    {
                        SqlBulkCopy(strCon, dtCoupon, "Coupon");
                        var bllCouponType = new CouponTypeBLL(loggingSessionInfo);
                        bllCouponType.UpdateCouponTypeIsVoucher(strCustomerid);
                    }
                }
            }
            return(dtCouponExport);
        }
示例#2
0
        public DataTable DownloadCouponNew(string strCustomerId, string strCouponTypeId, int downLoadNum)
        {
            DataTable dtCoupon = new DataTable();

            dtCoupon.Columns.Add("CouponID", typeof(string));
            dtCoupon.Columns.Add("CouponCode", typeof(string));
            dtCoupon.Columns.Add("CouponDesc", typeof(string));
            dtCoupon.Columns.Add("BeginDate", typeof(DateTime));
            dtCoupon.Columns.Add("EndDate", typeof(DateTime));
            dtCoupon.Columns.Add("CouponUrl", typeof(string));
            dtCoupon.Columns.Add("ImageUrl", typeof(string));
            dtCoupon.Columns.Add("Status", typeof(Int32));
            dtCoupon.Columns.Add("CreateTime", typeof(DateTime));
            dtCoupon.Columns.Add("CreateBy", typeof(string));
            dtCoupon.Columns.Add("LastUpdateTime", typeof(DateTime));
            dtCoupon.Columns.Add("LastUpdateBy", typeof(string));
            dtCoupon.Columns.Add("IsDelete", typeof(Int32));
            dtCoupon.Columns.Add("CouponTypeID", typeof(string));
            dtCoupon.Columns.Add("CoupnName", typeof(string));
            dtCoupon.Columns.Add("DoorID", typeof(string));
            dtCoupon.Columns.Add("CouponPwd", typeof(string));
            dtCoupon.Columns.Add("CollarCardMode", typeof(string));
            dtCoupon.Columns.Add("CustomerID", typeof(string));

            DataTable dtCouponExport = new DataTable();

            dtCouponExport.Columns.Add("CouponCode", typeof(string));

            PooledRedisClientManager pooleManager = new PooledRedisClientManager(10, 5, "182.254.151.114:6379");
            var redisClient = pooleManager.GetClient();

            redisClient.Db       = 2;
            redisClient.Password = "******";
            string strKey    = "Coupon" + strCustomerId + strCouponTypeId;
            long   ListCount = redisClient.GetListCount(strKey);

            if (ListCount > 0)
            {
                string strCon = new RedisConnectionBLL().GetConnection(strCustomerId).ConnectionStr;
                long   num    = 0;
                if (downLoadNum > ListCount)
                {
                    num = ListCount;
                }
                else
                {
                    num = downLoadNum;
                }

                for (int i = 0; i < num; i++)
                {
                    var coupon = GetRedisCouponNew(strKey);
                    if (coupon.CouponTypeId != null && coupon.CouponTypeId.Length > 0)
                    {
                        String uperStr       = StringUtil.GetRandomUperStr(4);
                        String strInt        = StringUtil.GetRandomStrInt(8);
                        string strCouponCode = uperStr + "-" + strInt;

                        DataRow dr_Coupon = dtCoupon.NewRow();
                        dr_Coupon["CouponID"]   = Guid.NewGuid().ToString();
                        dr_Coupon["CouponCode"] = strCouponCode;
                        dr_Coupon["CouponDesc"] = coupon.CouponTypeDesc;
                        if (coupon.ServiceLife > 0)
                        {
                            dr_Coupon["BeginDate"] = DateTime.Now;
                            dr_Coupon["EndDate"]   = DateTime.Now.Date.AddDays(coupon.ServiceLife - 1).ToShortDateString() + " 23:59:59.998";
                        }
                        else
                        {
                            dr_Coupon["BeginDate"] = coupon.BeginTime;
                            dr_Coupon["EndDate"]   = coupon.EndTime;
                        }
                        dr_Coupon["CouponUrl"]      = "";
                        dr_Coupon["ImageUrl"]       = "";
                        dr_Coupon["Status"]         = 0;
                        dr_Coupon["CreateTime"]     = DateTime.Now;
                        dr_Coupon["CreateBy"]       = "Redis";
                        dr_Coupon["LastUpdateTime"] = DateTime.Now;
                        dr_Coupon["LastUpdateBy"]   = "Redis";
                        dr_Coupon["IsDelete"]       = 0;
                        dr_Coupon["CouponTypeID"]   = coupon.CouponTypeId;
                        dr_Coupon["CoupnName"]      = coupon.CouponTypeName;
                        dr_Coupon["DoorID"]         = "";
                        dr_Coupon["CouponPwd"]      = "";
                        dr_Coupon["CollarCardMode"] = "";
                        dr_Coupon["CustomerID"]     = coupon.CustomerId;
                        dtCoupon.Rows.Add(dr_Coupon);

                        DataRow dr_CouponExport = dtCouponExport.NewRow();
                        dr_CouponExport["CouponCode"] = strCouponCode;
                        dtCouponExport.Rows.Add(dr_CouponExport);
                    }
                }
                if (dtCoupon != null && dtCoupon.Rows.Count > 0)
                {
                    SqlBulkCopy(strCon, dtCoupon, "Coupon");

                    LoggingSessionInfo _loggingSessionInfo   = new LoggingSessionInfo();
                    LoggingManager     CurrentLoggingManager = new LoggingManager();

                    _loggingSessionInfo.ClientID              = strCustomerId;
                    CurrentLoggingManager.Connection_String   = strCon;
                    _loggingSessionInfo.CurrentLoggingManager = CurrentLoggingManager;
                    var bllCouponType = new CouponTypeBLL(_loggingSessionInfo);
                    bllCouponType.UpdateCouponTypeIsVoucher(strCustomerId);
                }
            }
            return(dtCouponExport);
        }
示例#3
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);
        }
    }
}
        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);
        }
    }
}
示例#5
0
        public string RetailTraderMain(string pRequest)
        {
            var rp = pRequest.DeserializeJSONTo <APIRequest <GetRetailVipInfosRP> >();

            if (string.IsNullOrEmpty(rp.Parameters.RetailTraderID))
            {
                throw new APIException("缺少参数【RetailTraderID】或参数值为空")
                      {
                          ErrorCode = 135
                      };
            }

            var loggingSessionInfo = Default.GetBSLoggingSession(rp.CustomerID, "1");
            var bll           = new RetailTraderBLL(loggingSessionInfo);
            var rd            = new RetailTraderMainRD();
            var rsp           = new SuccessResponse <IAPIResponseData>(rd);
            var CouponTypeBll = new CouponTypeBLL(loggingSessionInfo);
            //  BringVipCount//我为兰博士带多少会员
            //  RewardAmount//奖励多少钱
            //累计会员数量
            var ds3 = bll.GetRetailVipInfos(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, -1, -1, -1);   //获取

            if (ds3 != null && ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
            {
                var tempDt = ds3.Tables[0];
                rd.BringVipCount = tempDt.Rows.Count;
            }
            //累积奖励
            decimal TotalRewards = bll.RetailRewardByAmountSource(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, -1, -1, -1, "17")
                                   + bll.RetailRewardByAmountSource(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, -1, -1, -1, "14")
                                   + bll.RetailRewardByAmountSource(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, -1, -1, -1, "15");    //获取

            rd.RewardAmount = TotalRewards;

            int?pageIndex = 1;
            int?pageSize  = 10000;
            //未核销优惠券列表
            int NoWriteOffCouponCount = 0;
            var ds4 = bll.GetRetailCoupon(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, 0, pageIndex ?? 1, pageSize ?? 15, rp.Parameters.OrderBy, rp.Parameters.OrderType);   //获取

            if (ds4 != null && ds4.Tables.Count > 0 && ds4.Tables[0].Rows.Count > 0)
            {
                //var tempDt = ds4.Tables[0];
                NoWriteOffCouponCount = Convert.ToInt32(ds4.Tables[0].Rows[0]["TotalCount"].ToString());//tempDt.Rows.Count;
                //  rd.WriteOffCouponList = DataTableToObject.ConvertToList<RetailCouponInfo>(ds4.Tables[1]);
            }

            var ds5 = bll.GetRetailCoupon(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, 1, pageIndex ?? 1, pageSize ?? 15, rp.Parameters.OrderBy, rp.Parameters.OrderType);   //获取

            if (ds5 != null && ds5.Tables.Count > 0 && ds5.Tables[0].Rows.Count > 0)
            {
                //var tempDt = ds5.Tables[0];
                rd.UsedCoupon = Convert.ToInt32(ds5.Tables[0].Rows[0]["TotalCount"].ToString());
                //  rd.WriteOffCouponList = DataTableToObject.ConvertToList<RetailCouponInfo>(ds3.Tables[1]);
            }


            //    rd.AllCouponCouponCount = rd.WriteOffCouponCount + rd.NoWriteOffCouponCount;


            rd.SendCouponCount = rd.UsedCoupon + NoWriteOffCouponCount;//	兰博士为我发券数量

            #region 获取适用所有门店的券
            var CouponTypeList = CouponTypeBll.QueryByEntity(new CouponTypeEntity()
            {
                SuitableForStore = 3, CustomerId = loggingSessionInfo.ClientID
            }, null).ToList();
            if (CouponTypeList.Count > 0)
            {
                foreach (var item in CouponTypeList)
                {
                    int Count = CouponTypeBll.GetCouponCount(item.CouponTypeID.ToString());
                    rd.SendCouponCount += Count;
                }
            }
            #endregion


            return(rsp.ToJSON());
        }
示例#6
0
        private void DownLoadCoupon_TicketNumber(HttpContext pContext)
        {
            try
            {
                #region 获取信息
                string couponTypeID   = FormatParamValue(Request("couponTypeID")); //优惠券类型id
                string filename       = FormatParamValue(Request("filename"));     //导出的文件名
                int    intDownLoadNum = Request("downLoadNum") == null ? 0 : Convert.ToInt32(Request("downLoadNum"));


                var bllCouponType = new CouponTypeBLL(CurrentUserInfo);

                var couponType = bllCouponType.QueryByEntity(new CouponTypeEntity()
                {
                    CustomerId = CurrentUserInfo.ClientID, CouponTypeID = new Guid(couponTypeID), IsDelete = 0
                }, null).SingleOrDefault();
                var couponBLL = new CouponBLL(CurrentUserInfo);

                var count = RedisOpenAPI.Instance.CCCoupon().GetCouponListLength(new CC_Coupon()
                {
                    CustomerId   = CurrentUserInfo.ClientID,
                    CouponTypeId = couponTypeID,
                });
                if (couponType.IsNotLimitQty == 0 && intDownLoadNum > count.Result)
                {
                    throw new APIException("下载数量大于优惠券剩余量")
                          {
                              ErrorCode = 333
                          };
                }
                //System.Data.DataTable list_CouponEntity = couponBLL.GetCouponIDBycouponType(couponTypeID).Tables[0];

                var redisCouponBLL = new JIT.CPOS.BS.BLL.RedisOperationBLL.Coupon.RedisCouponBLL();
                System.Data.DataTable list_CouponEntity = redisCouponBLL.DownloadCoupon(new CC_Coupon()
                {
                    CustomerId   = CurrentUserInfo.ClientID,
                    CouponTypeId = couponTypeID,
                }, CurrentUserInfo.ClientID, intDownLoadNum, couponType.IsNotLimitQty);
                //xu的redis
                //System.Data.DataTable list_CouponEntity = redisCouponBLL.DownloadCouponNew(CurrentUserInfo.ClientID, couponTypeID, intDownLoadNum);
                #endregion
                if (list_CouponEntity.Rows.Count == 0)
                {
                    return;
                }
                if (filename == null || filename == "")
                {
                    filename = "优惠券";
                }

                string filesrc = @"~/Framework/Upload/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                if (!System.IO.Directory.Exists(pContext.Server.MapPath(filesrc)))
                {
                    System.IO.Directory.CreateDirectory(pContext.Server.MapPath(filesrc));
                }


                string MapUrl            = pContext.Server.MapPath(filesrc + filename + ".xls");
                Aspose.Cells.License lic = new Aspose.Cells.License();
                lic.SetLicense("Aspose.Total.lic");
                Workbook  workbook = new Workbook();
                Worksheet sheet    = workbook.Worksheets[0];
                Cells     cells    = sheet.Cells;//单元格
                #region
                //为标题设置样式
                Style styleTitle = workbook.Styles[workbook.Styles.Add()]; //新增样式
                styleTitle.HorizontalAlignment = TextAlignmentType.Center; //文字居中
                styleTitle.Font.Name           = "宋体";                     //文字字体
                styleTitle.Font.Size           = 18;                       //文字大小
                styleTitle.Font.IsBold         = true;                     //粗体

                //样式2
                Style style2 = workbook.Styles[workbook.Styles.Add()]; //新增样式
                style2.HorizontalAlignment = TextAlignmentType.Center; //文字居中
                style2.Font.Name           = "宋体";                     //文字字体
                style2.Font.Size           = 14;                       //文字大小
                style2.Font.IsBold         = true;                     //粗体
                style2.IsTextWrapped       = true;                     //单元格内容自动换行
                style2.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
                style2.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
                style2.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
                style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

                //样式3
                Style style3 = workbook.Styles[workbook.Styles.Add()]; //新增样式
                style3.HorizontalAlignment = TextAlignmentType.Center; //文字居中
                style3.Font.Name           = "宋体";                     //文字字体
                style3.Font.Size           = 12;                       //文字大小
                style3.Borders[BorderType.LeftBorder].LineStyle   = CellBorderType.Thin;
                style3.Borders[BorderType.RightBorder].LineStyle  = CellBorderType.Thin;
                style3.Borders[BorderType.TopBorder].LineStyle    = CellBorderType.Thin;
                style3.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
                #endregion
                //生成行1 标题行

                cells[0, 0].PutValue(string.Format("{0}券号", filename));//填写内容
                cells[0, 0].SetStyle(styleTitle);
                cells.SetRowHeight(0, 30);
                cells.SetColumnWidth(0, 50);


                #region 生成数据行

                for (int i = 0; i < list_CouponEntity.Rows.Count; i++)
                {
                    cells[1 + i, 0].PutValue(list_CouponEntity.Rows[i]["CouponCode"]);
                    cells[1 + i, 0].SetStyle(style3);

                    cells.SetRowHeight(1 + i, 24);
                }
                #endregion
                workbook.Save(MapUrl);

                Utils.OutputExcel(pContext, MapUrl);    //输出Excel文件
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
示例#7
0
        /// <summary>
        /// 活动服务送券业务方法
        /// </summary>
        private void ActivitySendCoupon()
        {
            #region 业务对象
            var activityBLL        = new C_ActivityBLL(c_loggingSessionInfo);
            var targetGroupBLL     = new C_TargetGroupBLL(c_loggingSessionInfo);
            var prizesBLL          = new C_PrizesBLL(c_loggingSessionInfo);
            var prizesDetailBLL    = new C_PrizesDetailBLL(c_loggingSessionInfo);
            var CouponTypeBLL      = new CouponTypeBLL(c_loggingSessionInfo);
            var ActivityMessageBLL = new C_ActivityMessageBLL(c_loggingSessionInfo);
            #endregion


            #region 获取当前商户活动集合
            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
            };
            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "CustomerID", Value = c_loggingSessionInfo.ClientID
            });
            //complexCondition.Add(new DirectCondition(" ((IsLongTime=1 and GETDATE()>=StartTime) OR (GETDATE()>=StartTime AND GETDATE()<=EndTime)) AND STATUS=0 and IsDelete=0 "));
            complexCondition.Add(new DirectCondition(" (IsLongTime=1 or (IsLongTime=0 and GETDATE()<=EndTime)) and STATUS=0 and IsDelete=0 "));
            var ActivityList = activityBLL.Query(complexCondition.ToArray(), null);//营销活动

            #endregion
            #region 轮循活动,送券业务处理
            foreach (var activity in ActivityList)
            {
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = "轮循营销活动"
                });
                #region 获取卡类型ID(目标卡人群)
                var targetGroupInfo = targetGroupBLL.QueryByEntity(new C_TargetGroupEntity()
                {
                    ActivityID = activity.ActivityID, GroupType = 1
                }, null).FirstOrDefault();
                int VipCardTypeID = targetGroupInfo == null ? -1 : int.Parse(targetGroupInfo.ObjectID);//卡类型ID
                #endregion



                #region 活动是否设置奖品控制
                //获取赠送礼券奖品
                var prizesData = prizesBLL.QueryByEntity(new C_PrizesEntity()
                {
                    ActivityID = activity.ActivityID, PrizesType = 1
                }, null).FirstOrDefault();
                //当前活动消息类型集合
                var ActivityMessageLsit = ActivityMessageBLL.QueryByEntity(new C_ActivityMessageEntity()
                {
                    ActivityID = activity.ActivityID
                }, null).ToList();

                List <IWhereCondition> PrizeDetailCondition = new List <IWhereCondition> {
                };
                if (prizesData != null)
                {
                    PrizeDetailCondition.Add(new DirectCondition(" PrizesID='" + prizesData.PrizesID + "' "));
                }
                var PrizeDetailList = prizesDetailBLL.Query(PrizeDetailCondition.ToArray(), null).ToList();
                #endregion

                #region 当前活动券处理

                #region 获取活动会员人数
                int SumVipCount = 0;//会员数
                if (activity.IsAllVipCardType == 0)
                {
                    SumVipCount = activityBLL.GetholderCardCount(VipCardTypeID.ToString(), null);//当前卡类型会员数
                }
                else
                {
                    SumVipCount = activityBLL.GetholderCardCount(null, null);//所有会员数
                }
                #endregion

                #region 获取当前活动送券集合
                List <IWhereCondition> CouponTypeCondition = new List <IWhereCondition> {
                };
                StringBuilder strWhere    = new StringBuilder();
                string        NewStrWhere = "";
                foreach (var itemPrizeDetail in PrizeDetailList)
                {
                    strWhere.Append("couponTypeID='" + itemPrizeDetail.CouponTypeID + "' or ");
                }
                if (PrizeDetailList.Count > 0)
                {
                    NewStrWhere = ((strWhere.ToString().TrimEnd()).TrimEnd('r')).Trim('o');
                }
                if (!string.IsNullOrWhiteSpace(NewStrWhere))
                {
                    CouponTypeCondition.Add(new DirectCondition(NewStrWhere));
                }
                //券集合
                var ActivityCouponTypeList = CouponTypeBLL.Query(CouponTypeCondition.ToArray(), null);
                #endregion

                #region 判断当前券数量是否充足,不充足:计算出缺省券数量,充足获取券数最少的一种券

                //券种数量集合
                List <int> CouponNumList = new List <int>();
                bool       CouponFlag    = true;
                string     Remark        = "";
                foreach (var CouponTypeitem in ActivityCouponTypeList)
                {
                    if (CouponTypeitem.IsVoucher >= CouponTypeitem.IssuedQty)
                    {
                        if (SumVipCount > activity.SendCouponQty)
                        {
                            int Math = SumVipCount - (activity.SendCouponQty ?? 0);//目标数-使用数
                            // Loggers.Debug(new DebugLogInfo() { Message = CouponTypeitem.CouponTypeName + "券数量库存不足!" + DateTime.Now });
                            Remark    += string.Format("{1}都已发完还少{0}张,", Math, CouponTypeitem.CouponTypeName);
                            CouponFlag = false;
                        }
                    }
                    else
                    {
                        CouponNumList.Add((CouponTypeitem.IssuedQty ?? 0) - (CouponTypeitem.IsVoucher ?? 0));
                    }
                }
                if (CouponFlag == false)
                {
                    Remark += "请追加券数量!";
                    //activity.Remark = Remark;
                    activityBLL.Update(activity);//更新当前活动备注
                    continue;
                }
                int MinCouponNum = 0;
                if (CouponNumList.Count > 0)
                {
                    MinCouponNum = CouponNumList.Min();//当前活动奖品券种数量最少的券数
                }
                if (MinCouponNum == 0)
                {
                    continue;
                }
                #endregion


                #endregion

                #region 批量新增券关系,修改券数量
                int    ResultConunt      = 0;
                string CouponTypeNameStr = "";//所有券名称
                foreach (var CouponTypeitem in ActivityCouponTypeList)
                {
                    CouponTypeNameStr += CouponTypeitem.CouponTypeName + ",";
                    ResultConunt       = BatchAddSendCoupon(MinCouponNum, activity.ActivityID.Value.ToString(), activity.ActivityType.Value, CouponTypeitem.CouponTypeID.Value.ToString(), VipCardTypeID);
                    System.Threading.Thread.Sleep(2000);//沉睡2秒
                }
                #endregion

                if (ResultConunt > 0)
                {
                    #region 修改活动领券人数
                    activity.SendCouponQty = activity.SendCouponQty + ResultConunt;
                    activityBLL.Update(activity);

                    #endregion

                    #region 批量新增活动获赠奖品预发送消息
                    //CouponTypeNameStr = CouponTypeNameStr.TrimEnd(',');
                    foreach (var ActMessageitem in ActivityMessageLsit)
                    {
                        string Content = ActMessageitem.Content + "," + CouponTypeNameStr; //消息内容
                        BatchAddMessageSend(ResultConunt, activity.ActivityID.Value.ToString(), VipCardTypeID, ActMessageitem.MessageID.Value.ToString(), ActMessageitem.MessageType, Content, ActMessageitem.SendTime.Value, activity.ActivityType ?? 2);
                        System.Threading.Thread.Sleep(2000);                               //沉睡2秒
                    }
                    #endregion

                    #region 批量新增获赠信息
                    BatchAddPrizeReceive(ResultConunt, activity.ActivityID.Value.ToString(), VipCardTypeID, activity.ActivityType ?? 2);
                    System.Threading.Thread.Sleep(2000);//沉睡2秒
                    #endregion
                }
            }

            #endregion
        }
        /// <summary>
        /// vip绑定coupon入队列
        /// </summary>
        /// <param name="coupon"></param>
        /// <param name="strObjectId"></param>
        /// <param name="strVipId"></param>
        /// <param name="strSource"></param>
        public void SetVipMappingCoupon(CC_Coupon coupon, string strObjectId, string strVipId, string strSource)
        {
            LoggingSessionInfo _loggingSessionInfo   = new LoggingSessionInfo();
            LoggingManager     CurrentLoggingManager = new LoggingManager();
            string             strCon = string.Empty;

            var connection = new RedisConnectionBLL().GetConnection(coupon.CustomerId);

            //如果缓存获取不到数据,从数据库读取数据库连接字符串
            if (connection.CustomerID == null)
            {
                connection.ConnectionStr = GetCustomerConn(coupon.CustomerId);
            }

            CurrentLoggingManager.Connection_String = connection.ConnectionStr;

            _loggingSessionInfo.ClientID = coupon.CustomerId;
            _loggingSessionInfo.CurrentLoggingManager = CurrentLoggingManager;

            RedisCouponBLL redisCouponBLL = new RedisCouponBLL();
            //获取优惠券数量
            var count = RedisOpenAPI.Instance.CCCoupon().GetCouponListLength(coupon);

            if (count.Code == ResponseCode.Success)
            {
                if (count.Result == 0)
                {
                    var bllCouponType = new CouponTypeBLL(_loggingSessionInfo);

                    var couponType = bllCouponType.QueryByEntity(new CouponTypeEntity()
                    {
                        CustomerId = coupon.CustomerId, CouponTypeID = new Guid(coupon.CouponTypeId), IsDelete = 0
                    }, null).SingleOrDefault();
                    if (couponType != null)
                    {
                        //计算剩余的优惠券数量
                        int intCouponLenth = Convert.ToInt32(couponType.IssuedQty) - Convert.ToInt32(couponType.IsVoucher);
                        if (intCouponLenth <= 0)
                        {
                            intCouponLenth = 1000;
                            //重置优惠券数量为1000
                            bllCouponType.UpdateCouponTypeIssuedQty(coupon.CouponTypeId, intCouponLenth);
                        }

                        //这里可能是重置 Redis 缓存中该类型优惠券数据数量
                        RedisOpenAPI.Instance.CCCoupon().SetCouponList(new CC_Coupon()
                        {
                            CustomerId     = couponType.CustomerId,
                            CouponTypeId   = couponType.CouponTypeID.ToString(),
                            CouponTypeDesc = couponType.CouponTypeDesc,
                            CouponTypeName = couponType.CouponTypeName,
                            BeginTime      = couponType.BeginTime.ToString(),
                            EndTime        = couponType.EndTime.ToString(),
                            ServiceLife    = couponType.ServiceLife ?? 0,
                            CouponLenth    = intCouponLenth,
                            CouponCategory = couponType.CouponCategory
                        });
                    }
                }
                //从 Redis 中重新获取优惠券信息
                var response = redisCouponBLL.RedisGetCoupon(coupon);
                if (response.Code == ResponseCode.Success && response.Result.CouponTypeId != null && response.Result.CouponTypeId.Length > 0)
                {
                    string strCouponCode = string.Empty;
                    //从数据库中读取优惠券编码
                    strCouponCode = GetCouponNum(_loggingSessionInfo, response.Result.CustomerId);
                    var _coupon = new CC_Coupon()
                    {
                        CustomerId     = response.Result.CustomerId,
                        CouponTypeId   = response.Result.CouponTypeId,
                        CouponTypeDesc = response.Result.CouponTypeDesc,
                        CouponTypeName = response.Result.CouponTypeName,
                        CouponCode     = strCouponCode,
                        BeginTime      = response.Result.BeginTime,
                        EndTime        = response.Result.EndTime,
                        ServiceLife    = response.Result.ServiceLife,
                        CouponCategory = response.Result.CouponCategory,
                        CouponId       = Guid.NewGuid().ToString()
                    };
                    BaseService.WriteLog("---------------------------入vip绑定优惠券队列---------------------------");
                    //将优惠券推送到 Redis 缓存中
                    RedisOpenAPI.Instance.CCVipMappingCoupon().SetVipMappingCoupon(new CC_VipMappingCoupon()
                    {
                        CustomerId = coupon.CustomerId,
                        ObjectId   = strObjectId,
                        VipId      = strVipId,
                        Source     = strSource,
                        Coupon     = _coupon
                    });
                }
            }
        }
示例#9
0
        protected override EmptyResponseData ProcessRequest(DTO.Base.APIRequest <ExchangeCouponRP> pRequest)
        {
            var rd                 = new EmptyResponseData();
            var para               = pRequest.Parameters;
            var pointMarkBLL       = new X_VipPointMarkBLL(CurrentUserInfo);
            var pointMarkDetailBLL = new X_VipPointMarkDetailBLL(CurrentUserInfo);

            var activityPrizesBLL = new X_ActivityPrizesBLL(CurrentUserInfo);
            var activityJoinBLL   = new X_ActivityJoinBLL(CurrentUserInfo);

            var couponBLL           = new CouponBLL(CurrentUserInfo);
            var vipCouponMappingBLL = new VipCouponMappingBLL(CurrentUserInfo);
            var couponTypeBLL       = new CouponTypeBLL(CurrentUserInfo);


            var activityPrizeInfo = activityPrizesBLL.GetByID(para.PrizesID);

            if (activityPrizeInfo != null)
            {
                //扣减积点
                var pointMarkInfo = pointMarkBLL.QueryByEntity(new X_VipPointMarkEntity()
                {
                    VipID = CurrentUserInfo.UserID
                }, null).FirstOrDefault();
                if (pointMarkInfo != null)
                {
                    pointMarkInfo.Count = pointMarkInfo.Count - activityPrizeInfo.UsePoint;
                    pointMarkBLL.Update(pointMarkInfo);

                    X_VipPointMarkDetailEntity detail = new X_VipPointMarkDetailEntity()
                    {
                        VipID      = CurrentUserInfo.UserID,
                        Count      = -activityPrizeInfo.UsePoint,
                        Source     = 2,//抽奖兑换
                        CustomerID = CurrentUserInfo.ClientID
                    };
                    pointMarkDetailBLL.Create(detail);
                }
                //更改参与信息
                var activityJoinInfo = activityJoinBLL.QueryByEntity(new X_ActivityJoinEntity()
                {
                    VipID = CurrentUserInfo.UserID
                }, new OrderBy[] { new OrderBy {
                                       FieldName = "CreateTime", Direction = OrderByDirections.Desc
                                   } }).FirstOrDefault();
                if (activityJoinInfo != null)
                {
                    activityJoinInfo.IsExchange = 1;
                    activityJoinBLL.Update(activityJoinInfo);
                }
                //兑换优惠券
                string couponID = couponBLL.GetUsableCouponID(activityPrizeInfo.CouponTypeID.ToString());
                VipCouponMappingEntity vipCouponMappingInfo = new VipCouponMappingEntity()
                {
                    VIPID    = CurrentUserInfo.UserID,
                    CouponID = couponID
                };
                vipCouponMappingBLL.Create(vipCouponMappingInfo);
                //修改券产品个数
                var couponTypeInfo = couponTypeBLL.GetByID(activityPrizeInfo.CouponTypeID);
                if (couponTypeInfo != null)
                {
                    couponTypeInfo.IsVoucher = couponTypeInfo.IsVoucher + 1;
                    couponTypeBLL.Update(couponTypeInfo);
                }
            }
            return(rd);
        }
示例#10
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);
            }
        }
示例#11
0
        /// <summary>
        /// 核销优惠劵
        /// </summary>
        /// <param name="pRequest"></param>
        /// <returns></returns>
        private string BestowCoupon(string pRequest)
        {
            RespData respData = new RespData();

            try
            {
                var reqObj = pRequest.DeserializeJSONTo <reqConunbondata>();
                if (string.IsNullOrEmpty(reqObj.userId))
                {
                    respData.ResultCode = "103";
                    respData.Message    = "登陆用户不能为空";
                }
                if (string.IsNullOrEmpty(reqObj.Parameters.doorID))
                {
                    respData.ResultCode = "103";
                    respData.Message    = "此APP版本无法核销,请升级到新版本。";
                    return(respData.ToJSON());
                }
                var loggingSessionInfo = Default.GetBSLoggingSession(reqObj.customerId, reqObj.userId);
                var couponUseBll       = new CouponUseBLL(loggingSessionInfo);             //优惠券使用BLL实例化
                var vcmBll             = new VipCouponMappingBLL(loggingSessionInfo);      //优惠券BLL实例化
                var couponTypeBll      = new CouponTypeBLL(loggingSessionInfo);            //优惠券类型
                var mappingBll         = new CouponTypeUnitMappingBLL(loggingSessionInfo); //优惠券和门店映射
                //var vcmEntity = new VipCouponMappingEntity();
                CouponBLL bll = new CouponBLL(loggingSessionInfo);



                //判断是否有权限核销优惠券
                CouponEntity couponEntity = null;
                if (!string.IsNullOrEmpty(reqObj.Parameters.couponCode))
                {
                    CouponEntity[] couponEntityArray = bll.QueryByEntity(new CouponEntity()
                    {
                        CouponCode = reqObj.Parameters.couponCode, CustomerID = reqObj.customerId
                    }, null);
                    if (couponEntityArray.Length != 0)
                    {
                        couponEntity = couponEntityArray[0];
                    }
                }
                else
                {
                    couponEntity = bll.GetByID(reqObj.Parameters.cuponID);
                }


                if (couponEntity != null)
                {
                    List <IWhereCondition> wheresOrderNo = new List <IWhereCondition>();
                    wheresOrderNo.Add(new EqualsCondition()
                    {
                        FieldName = "CouponID", Value = couponEntity.CouponID
                    });
                    var resultCouponVipID = vcmBll.Query(wheresOrderNo.ToArray(), null);

                    var couponTypeInfo = couponTypeBll.GetByID(couponEntity.CouponTypeID);
                    if (couponTypeInfo != null)
                    {
                        if (couponTypeInfo.SuitableForStore == 2)//下面的doorid传的是门店的id,如果等于1所有门店都能用,如果等于3所有分销商都能用
                        {
                            var couponTypeUnitMapping = mappingBll.QueryByEntity(new CouponTypeUnitMappingEntity()
                            {
                                CouponTypeID = new Guid(couponEntity.CouponTypeID.ToString()), ObjectID = reqObj.Parameters.doorID
                            }, null).FirstOrDefault();

                            if (couponTypeUnitMapping == null)
                            {
                                respData.ResultCode = "104";
                                respData.Message    = "请到指定门店/分销商使用";
                                return(respData.ToJSON());
                            }
                        }
                        if (couponTypeInfo.SuitableForStore == 3)//下面的doorid传的是门店的id,如果等于1所有门店都能用,如果等于3所有分销商都能用
                        {
                            //doorid必须是获取,分销商如果没数据,就报错。
                            RetailTraderBLL    _RetailTraderBLL = new RetailTraderBLL(loggingSessionInfo);
                            RetailTraderEntity en = _RetailTraderBLL.GetByID(reqObj.Parameters.doorID);
                            if (en == null)
                            {
                                respData.ResultCode = "104";
                                respData.Message    = "请到指定分销商使用";
                                return(respData.ToJSON());
                            }
                        }
                        if (couponTypeInfo.SuitableForStore == 1)//下面的doorid传的是门店的id,如果等于1所有门店都能用,如果等于3所有分销商都能用
                        {
                            //doorid必须是获取,门店如果没有数据,就报错。
                            TUnitBLL    _TUnitBLL = new TUnitBLL(loggingSessionInfo);
                            TUnitEntity en        = _TUnitBLL.GetByID(reqObj.Parameters.doorID);
                            if (en == null)
                            {
                                respData.ResultCode = "104";
                                respData.Message    = "请到指定门店使用";
                                return(respData.ToJSON());
                            }
                        }

                        int res = bll.BestowCoupon(couponEntity.CouponID, reqObj.Parameters.doorID);
                        if (res > 0) //如果没有影响一行,所以Coupon表里这条记录的status=1了,不能被使用了。
                        {
                            InoutService server = new InoutService(loggingSessionInfo);
                            var          tran   = server.GetTran();
                            using (tran.Connection)//事务
                            {
                                #region 优惠券使用记录
                                var couponUseEntity = new CouponUseEntity()
                                {
                                    CouponID = couponEntity.CouponID,
                                    VipID    = resultCouponVipID.Length == 0 ? "" : resultCouponVipID[0].VIPID,
                                    UnitID   = reqObj.Parameters.doorID,
                                    //OrderID = orderEntity.OrderID.ToString(),
                                    //CreateBy = reqObj.userId,
                                    Comment    = "核销电子券",
                                    CustomerID = reqObj.customerId
                                };
                                couponUseBll.Create(couponUseEntity);//生成优惠券使用记录
                                #endregion

                                //#region 修改优惠券数量   2016-06-03 使用了redis不用在这里更新数量
                                //couponTypeInfo.IsVoucher = couponTypeInfo.IsVoucher == null ? 1 : couponTypeInfo.IsVoucher + 1;
                                //couponTypeBll.Update(couponTypeInfo, tran);
                                //#endregion

                                respData.ResultCode = "200";
                                respData.Message    = "优惠劵使用成功";

                                tran.Commit();
                            }
                        }
                        else
                        {
                            respData.ResultCode = "103";
                            respData.Message    = "优惠劵已使用";
                        }
                    }
                }
                else
                {
                    respData.ResultCode = "104";
                    respData.Message    = "没有找到对应券。";
                    return(respData.ToJSON());
                }
            }
            catch (Exception)
            {
                respData.ResultCode = "103";
                respData.Message    = "数据库操作失败";
            }
            return(respData.ToJSON());
        }
        const int ERROR_LOAD_WRONG  = 302; //打开出错
        protected override GetSetoffToolDetailRD ProcessRequest(APIRequest <GetSetoffToolDetailRP> pRequest)
        {
            string content    = string.Empty;
            string customerId = string.Empty;
            GetSetoffToolDetailRD setoffToolDetailRD = new GetSetoffToolDetailRD();
            var para = pRequest.Parameters;

            customerId = CurrentUserInfo.CurrentUser.customer_id;
            try
            {
                var    imageUrl              = string.Empty;
                Random ro                    = new Random();
                var    iUp                   = 100000000;
                var    iDown                 = 50000000;
                var    rpVipDCode            = 0;                   //临时二维码
                var    iResult               = ro.Next(iDown, iUp); //随机数
                var    userQrCodeBll         = new WQRCodeManagerBLL(CurrentUserInfo);
                var    imgBll                = new ObjectImagesBLL(CurrentUserInfo);
                var    setOffPosterBLL       = new SetoffPosterBLL(CurrentUserInfo);
                var    SetoffToolUserViewBLL = new SetoffToolUserViewBLL(CurrentUserInfo);
                var    SetoffToolsBll        = new SetoffToolsBLL(CurrentUserInfo);
                var    SetOffPosterInfo      = setOffPosterBLL.QueryByEntity(new SetoffPosterEntity()
                {
                    SetoffPosterID = new Guid(para.ObjectId)
                }, null);                                                                                                                         //获取集客海报信息
                var setoffEventBLL  = new SetoffEventBLL(CurrentUserInfo);
                var setoffEventInfo = setoffEventBLL.QueryByEntity(new SetoffEventEntity()
                {
                    Status = "10", SetoffType = 1, CustomerId = customerId
                }, null);
                //var SetoffToolsInfo = SetoffToolsBll.QueryByEntity(new SetoffToolsEntity() { ObjectId = para.ObjectId, Status = "10", ToolType = para.ToolType, SetoffEventID = setoffEventInfo[0].SetoffEventID }, null);//获取工具信息
                //VipDcode=9生成永久二维码
                if (para.VipDCode == 9)
                {
                    //根据分享人ID和对象ID获取永久二维码信息
                    var userQrCode = userQrCodeBll.QueryByEntity(new WQRCodeManagerEntity()
                    {
                        ObjectId = para.ObjectId
                    }, null);
                    if (userQrCode != null && userQrCode.Length > 0)
                    {
                        if (para.ToolType == "Coupon")//如果类型为优惠券则返回二维码
                        {
                            setoffToolDetailRD.ToolType = para.ToolType;
                        }
                        if (para.ToolType == "SetoffPoster")//如果为集客海报则返回背景图和二维码
                        {
                            if (SetOffPosterInfo != null)
                            {
                                var backImgInfo = imgBll.QueryByEntity(new ObjectImagesEntity()
                                {
                                    ObjectId = SetOffPosterInfo[0].ImageId
                                }, null);
                                setoffToolDetailRD.ToolType   = para.ToolType;
                                setoffToolDetailRD.imageUrl   = userQrCode[0].ImageUrl;
                                setoffToolDetailRD.paraTemp   = userQrCode[0].QRCode;
                                setoffToolDetailRD.backImgUrl = backImgInfo[0].ImageURL;
                            }
                        }
                        setoffToolDetailRD.imageUrl = userQrCode[0].ImageUrl;
                        setoffToolDetailRD.paraTemp = userQrCode[0].QRCode;
                        return(setoffToolDetailRD);
                    }
                    //获取当前二维码 最大值
                    iResult    = new WQRCodeManagerBLL(CurrentUserInfo).GetMaxWQRCod() + 1;
                    rpVipDCode = 1;
                }

                #region 获取微信帐号
                var server = new WApplicationInterfaceBLL(CurrentUserInfo);
                var wxObj  = new WApplicationInterfaceEntity();
                wxObj = server.QueryByEntity(new WApplicationInterfaceEntity {
                    CustomerId = customerId
                }, null).FirstOrDefault();
                if (wxObj == null)
                {
                    throw new APIException("不存在对应的微信帐号.")
                          {
                              ErrorCode = ERROR_NULL_WXOBJ
                          };
                }
                else
                {
                    var commonServer = new CommonBLL();
                    //rpVipDCode 二维码类型  0: 临时二维码  1:永久二维码
                    imageUrl = commonServer.GetQrcodeUrl(wxObj.AppID, wxObj.AppSecret, rpVipDCode.ToString(""), iResult, CurrentUserInfo);//iResult作为场景值ID,临时二维码时为32位整型,永久二维码时只支持1--100000
                    //供本地测试时使用  "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=gQGN7zoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL1dreENCS1htX0xxQk94SEJ6MktIAAIEUk88VwMECAcAAA==";
                }
                #endregion

                if (para.VipDCode == 9 && !string.IsNullOrEmpty(imageUrl))    //永久二维码
                {
                    #region 创建店员永久二维码匹配表
                    var    userQrTypeBll = new WQRCodeTypeBLL(CurrentUserInfo);
                    string pTypeCode     = string.Empty;
                    if (para.ToolType.ToLower() == "coupon")
                    {
                        pTypeCode = "CouponQrCode";
                    }
                    if (para.ToolType.ToLower() == "setoffposter")
                    {
                        pTypeCode = "SetoffPosterQrCode";
                    }
                    if (para.ToolType.ToLower() == "superretail")
                    {
                        pTypeCode = "SuperRetailQrCode";
                    }
                    var userQrType = userQrTypeBll.QueryByEntity(new WQRCodeTypeEntity()
                    {
                        TypeCode = pTypeCode
                    }, null);                                                                                            //"SuperRetailQrCode=超级分销商二维码"
                    if (userQrType != null && userQrType.Length > 0)
                    {
                        var userQrcodeBll = new WQRCodeManagerBLL(CurrentUserInfo);
                        var userQrCode    = new WQRCodeManagerEntity();
                        userQrCode.QRCode        = iResult.ToString();//记录传过去的二维码场景值
                        userQrCode.QRCodeTypeId  = userQrType[0].QRCodeTypeId;
                        userQrCode.IsUse         = 1;
                        userQrCode.CustomerId    = customerId;
                        userQrCode.ImageUrl      = imageUrl;
                        userQrCode.ApplicationId = wxObj.ApplicationId;
                        //objectId 为集客海报ID或者优惠券ID
                        userQrCode.ObjectId = para.ObjectId;
                        userQrcodeBll.Create(userQrCode);
                    }
                    #endregion
                }
                else
                {
                    #region 创建临时匹配表
                    VipDCodeBLL    vipDCodeServer = new VipDCodeBLL(CurrentUserInfo);
                    VipDCodeEntity info           = new VipDCodeEntity();
                    info.DCodeId    = iResult.ToString();//记录传过去的二维码场景值****(保存到数据库时没加空格)
                    info.CustomerId = customerId;
                    VipBLL vipBll = new VipBLL(CurrentUserInfo);
                    info.UnitId      = "";
                    info.Status      = "0";
                    info.IsReturn    = 0;
                    info.DCodeType   = para.VipDCode;
                    info.CreateBy    = CurrentUserInfo.UserID;
                    info.ImageUrl    = imageUrl;
                    info.VipId       = "";
                    info.ObjectId    = para.ObjectId;   //工具对象ID(优惠券或集客海报对象ID)
                    info.OwnerUserId = para.ShareVipId; //分享人ID
                    vipDCodeServer.Create(info);
                    #endregion
                }
                int flag         = 0;//定义是否需要新增打开数据,0=不需要新增,1=需要新增
                var UserViewData = SetoffToolUserViewBLL.QueryByEntity(new SetoffToolUserViewEntity()
                {
                    ObjectId = para.ObjectId, UserID = CurrentUserInfo.UserID
                }, null);
                if (!string.IsNullOrEmpty(para.SetoffToolID))
                {
                    UserViewData = SetoffToolUserViewBLL.QueryByEntity(new SetoffToolUserViewEntity()
                    {
                        ObjectId = para.ObjectId, UserID = CurrentUserInfo.UserID, SetoffToolID = new Guid(para.SetoffToolID)
                    }, null);
                }
                if (UserViewData.Length == 0 && !string.IsNullOrEmpty(para.SetoffToolID) && para.PlatformType != "3")
                {
                    flag = 1;                  //当为1时进行增加打开工具记录
                }
                if (para.ToolType == "Coupon") //如果类型为优惠券则返回二维码
                {
                    #region 用户领优惠券过程
                    var CouponTypeBLL       = new CouponTypeBLL(CurrentUserInfo);
                    var couponBLL           = new CouponBLL(CurrentUserInfo);
                    var CouponSourceBLL     = new CouponSourceBLL(CurrentUserInfo);
                    var VipCouponMappingBLL = new VipCouponMappingBLL(CurrentUserInfo);

                    int?SurplusCount   = 0; //先获得剩余张数
                    int hasCouponCount = 0; //已领张数 如果>0表示已领取过就不让他领,=0就领取
                    var couponTypeInfo = CouponTypeBLL.QueryByEntity(new CouponTypeEntity()
                    {
                        CouponTypeID = new Guid(para.ObjectId)
                    }, null);

                    if (couponTypeInfo != null)
                    {
                        string couponIsVocher = string.Empty;
                        if (couponTypeInfo[0].IsVoucher == null)
                        {
                            SurplusCount = couponTypeInfo[0].IssuedQty - 0;
                        }
                        else
                        {
                            SurplusCount = couponTypeInfo[0].IssuedQty - couponTypeInfo[0].IsVoucher;
                        }
                        if (SurplusCount != 0 && para.ShareVipId != null && para.ShareVipId != "")// 通过列表进详细自己不能领券
                        {
                            //当剩余数量不为0时,进行下一步判断是否存在已领券的信息
                            hasCouponCount = VipCouponMappingBLL.GetReceiveCouponCount(CurrentUserInfo.UserID, para.ObjectId, "Share");
                            if (hasCouponCount == 0)//如果等于零,开始领券流程
                            {
                                //关联优惠券让用户领券
                                var redisVipMappingCouponBLL = new JIT.CPOS.BS.BLL.RedisOperationBLL.Coupon.RedisVipMappingCouponBLL();
                                try
                                {
                                    //执行领取操作
                                    redisVipMappingCouponBLL.InsertDataBase(CurrentUserInfo.CurrentUser.customer_id, CurrentUserInfo.UserID, para.SetoffToolID, "Share", new CC_Coupon()
                                    {
                                        CustomerId   = CurrentUserInfo.CurrentUser.customer_id,
                                        CouponTypeId = para.ObjectId
                                    });
                                    setoffToolDetailRD.Name = couponTypeInfo[0].CouponTypeName + ",已飞入您的账户";
                                }
                                catch (Exception ex)
                                {
                                    setoffToolDetailRD.Name = "很遗憾此次优惠券" + couponTypeInfo[0].CouponTypeName + "的分享已失效,下次请及时领取.";
                                }
                            }
                        }
                        else
                        {
                            //如果剩余数量为0时,给出已领完提示
                            if (para.ShareVipId != null && para.ShareVipId != "")
                            {
                                setoffToolDetailRD.Name = "很遗憾您来迟一步优惠券" + couponTypeInfo[0].CouponTypeName + "已被领完.";
                                //throw new APIException("很遗憾您来迟一步券已被领完.") { ErrorCode = ERROR_LOAD_WRONG };
                            }
                        }
                        if (setoffToolDetailRD.Name == null || setoffToolDetailRD.Name == "")
                        {
                            setoffToolDetailRD.Name = couponTypeInfo[0].CouponTypeName;
                        }
                        setoffToolDetailRD.StartTime = couponTypeInfo[0].BeginTime == null?Convert.ToDateTime(couponTypeInfo[0].CreateTime).ToString("yyyy-MM-dd") : Convert.ToDateTime(couponTypeInfo[0].BeginTime).ToString("yyyy-MM-dd");

                        setoffToolDetailRD.EndTime     = couponTypeInfo[0].EndTime == null ? "" : Convert.ToDateTime(couponTypeInfo[0].EndTime).ToString("yyyy-MM-dd");
                        setoffToolDetailRD.ServiceLife = couponTypeInfo[0].ServiceLife.ToString();
                    }
                    #endregion
                    setoffToolDetailRD.ToolType = para.ToolType;                     //返回工具类别
                    setoffToolDetailRD.imageUrl = imageUrl;                          //返回临时二维码
                    setoffToolDetailRD.paraTemp = iResult.ToString().Insert(4, " "); //加空格,加空格有什么作用?
                }
                if (para.ToolType == "SetoffPoster")                                 //如果为集客海报则返回背景图和二维码
                {
                    if (SetOffPosterInfo != null && SetOffPosterInfo.Length > 0)
                    {
                        var backImgInfo = imgBll.QueryByEntity(new ObjectImagesEntity()
                        {
                            ImageId = SetOffPosterInfo[0].ImageId
                        }, null);
                        setoffToolDetailRD.ToolType   = para.ToolType;
                        setoffToolDetailRD.imageUrl   = imageUrl;
                        setoffToolDetailRD.paraTemp   = iResult.ToString().Insert(4, " "); //加空格,加空格有什么作用?
                        setoffToolDetailRD.backImgUrl = backImgInfo[0].ImageURL;
                        setoffToolDetailRD.Name       = SetOffPosterInfo[0].Name;
                    }
                }
                if (flag == 1)//当为1是需进行打开工具的记录
                {
                    var SetoffToolUserView = new SetoffToolUserViewEntity();
                    SetoffToolUserView.SetoffToolUserViewID = Guid.NewGuid();
                    SetoffToolUserView.SetoffEventID        = setoffEventInfo[0].SetoffEventID;
                    SetoffToolUserView.SetoffToolID         = new Guid(para.SetoffToolID);
                    SetoffToolUserView.ToolType             = para.ToolType;
                    SetoffToolUserView.ObjectId             = para.ObjectId;
                    SetoffToolUserView.NoticePlatformType   = 1;
                    SetoffToolUserView.UserID         = CurrentUserInfo.UserID;
                    SetoffToolUserView.IsOpen         = 1;
                    SetoffToolUserView.OpenTime       = System.DateTime.Now;
                    SetoffToolUserView.CustomerId     = customerId;
                    SetoffToolUserView.CreateTime     = System.DateTime.Now;
                    SetoffToolUserView.CreateBy       = CurrentUserInfo.UserID;
                    SetoffToolUserView.LastUpdateTime = System.DateTime.Now;
                    SetoffToolUserView.LastUpdateBy   = CurrentUserInfo.UserID;
                    SetoffToolUserView.IsDelete       = 0;
                    SetoffToolUserViewBLL.Create(SetoffToolUserView);
                }
            }
            catch (Exception ex)
            {
                throw new APIException(ex.Message)
                      {
                          ErrorCode = ERROR_CODES.DEFAULT_ERROR
                      };
            }
            return(setoffToolDetailRD);
        }
示例#13
0
        public string RetailCoupon(string pRequest)
        {
            var rp = pRequest.DeserializeJSONTo <APIRequest <GetRetailVipInfosRP> >();

            if (string.IsNullOrEmpty(rp.Parameters.RetailTraderID))
            {
                throw new APIException("缺少参数【RetailTraderID】或参数值为空")
                      {
                          ErrorCode = 135
                      };
            }
            var pageSize  = rp.Parameters.PageSize;
            var pageIndex = rp.Parameters.PageIndex;

            var loggingSessionInfo = Default.GetBSLoggingSession(rp.CustomerID, "1");
            var bll           = new RetailTraderBLL(loggingSessionInfo);
            var rd            = new RetailCouponRD();
            var rsp           = new SuccessResponse <IAPIResponseData>(rd);
            var CouponTypeBll = new CouponTypeBLL(loggingSessionInfo);


            //优惠券状态为1代表已经使用,为0
            //已核销优惠券列表
            var ds3 = bll.GetRetailCoupon(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, 1, pageIndex ?? 1, pageSize ?? 15, rp.Parameters.OrderBy, rp.Parameters.OrderType);   //获取

            if (ds3 != null && ds3.Tables.Count > 0 && ds3.Tables[0].Rows.Count > 0)
            {
                rd.WriteOffCouponCount = Convert.ToInt32(ds3.Tables[0].Rows[0]["TotalCount"].ToString());
                rd.WriteOffCouponList  = DataTableToObject.ConvertToList <RetailCouponInfo>(ds3.Tables[1]);
            }



            //未核销优惠券列表
            var ds4 = bll.GetRetailCoupon(rp.Parameters.RetailTraderID, loggingSessionInfo.ClientID, 0, pageIndex ?? 1, pageSize ?? 15, rp.Parameters.OrderBy, rp.Parameters.OrderType);   //获取

            if (ds4 != null && ds4.Tables.Count > 0 && ds4.Tables[0].Rows.Count > 0)
            {
                rd.NoWriteOffCouponCount = Convert.ToInt32(ds4.Tables[0].Rows[0]["TotalCount"].ToString());
                rd.NoWriteOffCouponList  = DataTableToObject.ConvertToList <RetailCouponInfo>(ds4.Tables[1]);
            }

            rd.AllCouponCouponCount = rd.WriteOffCouponCount + rd.NoWriteOffCouponCount;

            #region 获取适用所有门店的券
            var CouponTypeList = CouponTypeBll.QueryByEntity(new CouponTypeEntity()
            {
                SuitableForStore = 3, CustomerId = loggingSessionInfo.ClientID
            }, null).ToList();
            if (CouponTypeList.Count > 0)
            {
                foreach (var item in CouponTypeList)
                {
                    int Count = CouponTypeBll.GetCouponCount(item.CouponTypeID.ToString());
                    rd.AllCouponCouponCount += Count;
                }
            }
            #endregion

            return(rsp.ToJSON());
        }
示例#14
0
        /// <summary>
        /// 种植所有商户优惠券
        /// </summary>
        public void RedisSetAllCoupon()
        {
            //CC_Connection connection = new CC_Connection();

            LoggingSessionInfo _loggingSessionInfo   = new LoggingSessionInfo();
            LoggingManager     CurrentLoggingManager = new LoggingManager();
            int defaultNum  = 1000;
            var customerIDs = CustomerBLL.Instance.GetCustomerList();

            foreach (var customer in customerIDs)
            {
                _loggingSessionInfo.ClientID              = customer.Key;
                CurrentLoggingManager.Connection_String   = customer.Value;
                _loggingSessionInfo.CurrentLoggingManager = CurrentLoggingManager;
                var bllCouponType  = new CouponTypeBLL(_loggingSessionInfo);
                var bllCoupon      = new CouponBLL(_loggingSessionInfo);
                var couponTypeList = bllCouponType.QueryByEntity(new CouponTypeEntity()
                {
                    CustomerId = customer.Key, IsDelete = 0
                }, null).ToList();
                foreach (var couponType in couponTypeList)
                {
                    var count = RedisOpenAPI.Instance.CCCoupon().GetCouponListLength(new CC_Coupon()
                    {
                        CustomerId = customer.Key, CouponTypeId = couponType.CouponTypeID.ToString()
                    });
                    if (count.Code == ResponseCode.Success && count.Result == 0)
                    {
                        ///无限量的优惠券 默认种植1000
                        if (couponType.IsNotLimitQty == 1)
                        {
                            RedisSetSingleCoupon(new CC_Coupon()
                            {
                                CustomerId     = couponType.CustomerId,
                                CouponTypeId   = couponType.CouponTypeID.ToString(),
                                CouponTypeDesc = couponType.CouponTypeDesc,
                                CouponTypeName = couponType.CouponTypeName,
                                BeginTime      = couponType.BeginTime.ToString(),
                                EndTime        = couponType.EndTime.ToString(),
                                ServiceLife    = couponType.ServiceLife ?? 0,
                                CouponLenth    = defaultNum,
                                CouponCategory = couponType.CouponCategory
                            });
                        }
                        else
                        {
                            //RedisOpenAPI.Instance.CCCoupon().DeleteCouponList(new CC_Coupon() { CustomerId = customer.Key, CouponTypeId = couponType.CouponTypeID.ToString() });

                            int intCouponLenth = (int)couponType.IssuedQty;

                            int intUsed = bllCoupon.QueryByEntity(new CouponEntity()
                            {
                                CouponTypeID = couponType.CouponTypeID.ToString(), IsDelete = 0, CreateBy = "Redis"
                            }, null).ToList().Count();

                            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
                            };
                            complexCondition.Add(new EqualsCondition()
                            {
                                FieldName = "CouponTypeID", Value = couponType.CouponTypeID
                            });
                            complexCondition.Add(new EqualsCondition()
                            {
                                FieldName = "CustomerID", Value = customer.Key
                            });
                            complexCondition.Add(new EqualsCondition()
                            {
                                FieldName = "IsDelete", Value = "0"
                            });
                            complexCondition.Add(new DirectCondition("  Status=0 and CreateBy <>'Redis' "));
                            int intOldUsed = bllCoupon.Query(complexCondition.ToArray(), null).ToList().Count();
                            if (intOldUsed > 0)
                            {
                                intCouponLenth = intOldUsed;
                            }
                            intCouponLenth = intCouponLenth - intUsed;

                            if (intCouponLenth > 0)
                            {
                                if (intCouponLenth > defaultNum)
                                {
                                    intCouponLenth = defaultNum;
                                }

                                RedisSetSingleCoupon(new CC_Coupon()
                                {
                                    CustomerId     = couponType.CustomerId,
                                    CouponTypeId   = couponType.CouponTypeID.ToString(),
                                    CouponTypeDesc = couponType.CouponTypeDesc,
                                    CouponTypeName = couponType.CouponTypeName,
                                    BeginTime      = couponType.BeginTime.ToString(),
                                    EndTime        = couponType.EndTime.ToString(),
                                    ServiceLife    = couponType.ServiceLife ?? 0,
                                    CouponLenth    = intCouponLenth,
                                    CouponCategory = couponType.CouponCategory
                                });
                            }
                            else                              //如果生成量和已使用量<=0 就删除相应的key
                            {
                                RedisOpenAPI.Instance.CCCoupon().DeleteCouponList(new CC_Coupon()
                                {
                                    CustomerId = customer.Key, CouponTypeId = couponType.CouponTypeID.ToString()
                                });
                            }
                        }
                    }
                }
            }
        }
        protected override GetActivityDeatilRD ProcessRequest(DTO.Base.APIRequest <GetActivityDeatilRP> pRequest)
        {
            var rd   = new GetActivityDeatilRD();
            var para = pRequest.Parameters;
            var loggingSessionInfo  = new SessionManager().CurrentUserLoginInfo;
            var activityBll         = new C_ActivityBLL(loggingSessionInfo);
            var prizesBll           = new C_PrizesBLL(loggingSessionInfo);
            var prizesDetailBll     = new C_PrizesDetailBLL(loggingSessionInfo);
            var activityMessageBll  = new C_ActivityMessageBLL(loggingSessionInfo);
            var targetGroupBll      = new C_TargetGroupBLL(loggingSessionInfo);
            var rechargeStrategyBll = new RechargeStrategyBLL(loggingSessionInfo);

            if (!string.IsNullOrWhiteSpace(para.ActivityID))
            {
                #region 基础信息
                C_ActivityEntity activityData = activityBll.GetByID(para.ActivityID);
                if (activityData != null)
                {
                    rd.ActivityID      = activityData.ActivityID.ToString();
                    rd.ActivityType    = activityData.ActivityType ?? 2;
                    rd.ActivityName    = activityData.ActivityName;
                    rd.StartTime       = activityData.StartTime == null ? "" : activityData.StartTime.Value.ToString("yyyy-MM-dd");
                    rd.EndTime         = activityData.EndTime == null ? "" : activityData.EndTime.Value.ToString("yyyy-MM-dd");
                    rd.IsLongTime      = activityData.IsLongTime == null ? "0" : activityData.IsLongTime.Value.ToString();
                    rd.IsAllCardType   = activityData.IsAllVipCardType ?? 0;
                    rd.VipCardTypeID   = activityBll.GetTargetGroupId(rd.IsAllCardType, rd.ActivityID);
                    rd.HolderCardCount = activityBll.GetTargetCount(rd.VipCardTypeID, rd.ActivityType, rd.StartTime, rd.EndTime, activityData.IsLongTime.Value);
                    rd.Status          = activityData.Status.Value;
                }
                #endregion
                #region 奖品
                var PrizesList = prizesBll.Query(new IWhereCondition[] { new EqualsCondition()
                                                                         {
                                                                             FieldName = "ActivityID", Value = para.ActivityID
                                                                         }, new EqualsCondition()
                                                                         {
                                                                             FieldName = "CustomerID", Value = loggingSessionInfo.ClientID
                                                                         } }, null).ToList();
                if (PrizesList.Count > 0)
                {
                    //奖品集合赋值
                    rd.PrizesInfoList = (from u in PrizesList
                                         select new PrizesInfo()
                    {
                        PrizesID = Convert.ToString(u.PrizesID),
                        PrizesType = u.PrizesType.Value
                    }).ToList();

                    foreach (var item in rd.PrizesInfoList)
                    {
                        item.PrizesDetailList = new List <PrizesDetailInfo>();
                        //奖品明细
                        var PrizesDetailList = prizesDetailBll.GetPrizesDetailList(item.PrizesID);
                        if (PrizesDetailList.Count > 0)
                        {
                            CouponTypeBLL ctbll = new CouponTypeBLL(CurrentUserInfo);
                            foreach (var itemes in PrizesDetailList)
                            {
                                PrizesDetailInfo m = new PrizesDetailInfo();
                                m.PrizesDetailID = Convert.ToString(itemes.PrizesDetailID);
                                m.CouponTypeID   = Convert.ToString(itemes.CouponTypeID);
                                m.CouponTypeName = itemes.CouponTypeName;
                                m.NumLimit       = itemes.NumLimit.Value;
                                m.CouponTypeDesc = itemes.CouponTypeDesc;
                                //ValidityPeriod = t.BeginTime == null ? ("领取后" + (t.ServiceLife == 0 ? "1天内有效" : t.ServiceLife.ToString() + "天内有效")) : (t.BeginTime.Value.ToString("yyyy-MM-dd") + "至" + t.EndTime.Value.ToString("yyyy-MM-dd")),
                                var t = ctbll.GetByID(m.CouponTypeID);
                                m.ValidityPeriod = t.BeginTime == null ? ("领取后" + (t.ServiceLife == 0 ? "1天内有效" : t.ServiceLife.ToString() + "天内有效")) : (t.BeginTime.Value.ToString("yyyy-MM-dd") + "至" + t.EndTime.Value.ToString("yyyy-MM-dd"));
                                //奖品明细集合额赋值
                                item.PrizesDetailList.Add(m);
                            }
                        }
                    }
                }
                #endregion
                #region 消息
                var ActivityMessageList = activityMessageBll.Query(new IWhereCondition[] { new EqualsCondition()
                                                                                           {
                                                                                               FieldName = "ActivityID", Value = para.ActivityID
                                                                                           }, new EqualsCondition()
                                                                                           {
                                                                                               FieldName = "CustomerID", Value = loggingSessionInfo.ClientID
                                                                                           } }, null).ToList();
                if (ActivityMessageList.Count > 0)
                {
                    //消息赋值
                    rd.ActivityMessageInfoList = (from u in ActivityMessageList
                                                  select new ActivityMessageInfo()
                    {
                        MessageID = u.MessageID.Value.ToString(),
                        MessageType = u.MessageType.Trim(),
                        Content = u.Content,
                        SendTime = u.SendTime == null ? "" : u.SendTime.Value.ToString(),
                        AdvanceDays = u.AdvanceDays,
                        SendAtHour = u.SendAtHour
                    }).ToList();
                }
                #endregion
                #region 充值策略

                var rechargeStrategyInfoList = rechargeStrategyBll.Query(new IWhereCondition[] { new EqualsCondition()
                                                                                                 {
                                                                                                     FieldName = "ActivityID", Value = para.ActivityID
                                                                                                 }, new EqualsCondition()
                                                                                                 {
                                                                                                     FieldName = "CustomerId", Value = loggingSessionInfo.ClientID
                                                                                                 } }, new[] {
                    new OrderBy()
                    {
                        FieldName = "RechargeAmount", Direction = OrderByDirections.Asc
                    }
                }).ToList();
                if (rechargeStrategyInfoList.Count > 0)
                {
                    //消息赋值
                    rd.RechargeStrategyInfoList = (from u in rechargeStrategyInfoList
                                                   select new RechargeStrategyInfo()
                    {
                        RechargeStrategyId = u.RechargeStrategyId.ToString(),
                        RuleType = u.RuleType,
                        RechargeAmount = u.RechargeAmount,
                        GiftAmount = u.GiftAmount.Value
                    }).ToList();
                }
                #endregion
            }
            return(rd);
        }
        /// <summary>
        /// 批量
        /// </summary>
        public void InsertDataBase()
        {
            BaseService.WriteLog("---------------------------vip绑定优惠券开始---------------------------");

            var numCount    = 30;
            var customerIDs = CustomerBLL.Instance.GetCustomerList();

            foreach (var customer in customerIDs)
            {
                try
                {
                    LoggingSessionInfo loggingSessionInfo = CustomerBLL.Instance.GetBSLoggingSession(customer.Key, "RedisSystem");

                    DataTable dtCoupon = CreateTableCoupon();

                    DataTable dtVipCoupon = CreateTableVipCoupon();

                    var count = RedisOpenAPI.Instance.CCVipMappingCoupon().GetVipMappingCouponLength(new CC_VipMappingCoupon
                    {
                        CustomerId = customer.Key
                    });
                    if (count.Code != ResponseCode.Success)
                    {
                        BaseService.WriteLog("从redis获取待绑定优惠券数量失败");
                        continue;
                    }
                    if (count.Result <= 0)
                    {
                        continue;
                    }
                    BaseService.WriteLog("优惠券redis取数据:" + customer.Key);
                    if (count.Result < numCount)
                    {
                        numCount = Convert.ToInt32(count.Result);
                    }

                    for (var i = 0; i < numCount; i++)
                    {
                        BaseService.WriteLog("---------------------------vip绑定优惠券长度:" + count.Result.ToString());
                        var response = RedisOpenAPI.Instance.CCVipMappingCoupon().GetVipMappingCoupon(new CC_VipMappingCoupon
                        {
                            CustomerId = customer.Key
                        });
                        if (response.Code == ResponseCode.Success)
                        {
                            DataRow dr_Coupon = dtCoupon.NewRow();
                            dr_Coupon["CouponID"]   = response.Result.Coupon.CouponId;
                            dr_Coupon["CouponCode"] = response.Result.Coupon.CouponCode;
                            dr_Coupon["CouponDesc"] = response.Result.Coupon.CouponTypeDesc;
                            if (response.Result.Coupon.ServiceLife > 0)
                            {
                                dr_Coupon["BeginDate"] = DateTime.Now;
                                dr_Coupon["EndDate"]   = DateTime.Now.Date.AddDays(response.Result.Coupon.ServiceLife - 1).ToShortDateString() + " 23:59:59.998";
                            }
                            else
                            {
                                dr_Coupon["BeginDate"] = response.Result.Coupon.BeginTime;
                                dr_Coupon["EndDate"]   = response.Result.Coupon.EndTime;
                            }
                            dr_Coupon["CouponUrl"]      = "";
                            dr_Coupon["ImageUrl"]       = "";
                            dr_Coupon["Status"]         = 2;
                            dr_Coupon["CreateTime"]     = DateTime.Now;
                            dr_Coupon["CreateBy"]       = "Redis";
                            dr_Coupon["LastUpdateTime"] = DateTime.Now;
                            dr_Coupon["LastUpdateBy"]   = "Redis";
                            dr_Coupon["IsDelete"]       = 0;
                            dr_Coupon["CouponTypeID"]   = response.Result.Coupon.CouponTypeId;
                            dr_Coupon["CoupnName"]      = response.Result.Coupon.CouponTypeName;
                            dr_Coupon["DoorID"]         = "";
                            dr_Coupon["CouponPwd"]      = "";
                            dr_Coupon["CollarCardMode"] = "";
                            dr_Coupon["CustomerID"]     = customer.Key;
                            dtCoupon.Rows.Add(dr_Coupon);

                            DataRow dr_VipCoupon = dtVipCoupon.NewRow();
                            dr_VipCoupon["VipCouponMapping"] = Guid.NewGuid().ToString().Replace("-", "");
                            dr_VipCoupon["VIPID"]            = response.Result.VipId;
                            dr_VipCoupon["CouponID"]         = response.Result.Coupon.CouponId;
                            dr_VipCoupon["UrlInfo"]          = "";
                            dr_VipCoupon["IsDelete"]         = 0;
                            dr_VipCoupon["LastUpdateBy"]     = "Redis";
                            dr_VipCoupon["LastUpdateTime"]   = DateTime.Now;
                            dr_VipCoupon["CreateBy"]         = "Redis";
                            dr_VipCoupon["CreateTime"]       = DateTime.Now;
                            dr_VipCoupon["FromVipId"]        = "";
                            dr_VipCoupon["ObjectId"]         = response.Result.ObjectId;
                            dr_VipCoupon["CouponSourceId"]   = GetSourceId(response.Result.Source);
                            dtVipCoupon.Rows.Add(dr_VipCoupon);
//活动或者虚拟商品发优惠券,不发通知
                            if (response.Result.Source != "Activity" && response.Result.Source != "PayVirtualItem")
                            {//会员活动延迟发送
                                try
                                {
                                    ///优惠券到账通知
                                    var CommonBLL = new CommonBLL();
                                    var bllVip    = new VipBLL(loggingSessionInfo);
                                    var vip       = bllVip.GetByID(response.Result.VipId);

                                    string strValidityData = Convert.ToDateTime(dr_Coupon["BeginDate"].ToString()).ToShortDateString() + "-" + Convert.ToDateTime(dr_Coupon["EndDate"].ToString()).ToShortDateString();
                                    CommonBLL.CouponsArrivalMessage(response.Result.Coupon.CouponCode, response.Result.Coupon.CouponTypeName, strValidityData, response.Result.Coupon.CouponCategory == null ? "" : response.Result.Coupon.CouponCategory, vip.WeiXinUserId, loggingSessionInfo);
                                }
                                catch (Exception ex)
                                {
                                    BaseService.WriteLog("优惠券到账通知异常:" + ex.Message);
                                    continue;
                                }
                            }
                        }
                    }
                    if (dtCoupon != null && dtCoupon.Rows.Count > 0)
                    {
                        SqlBulkCopy(customer.Value, dtCoupon, "Coupon");
                        var bllCouponType = new CouponTypeBLL(loggingSessionInfo);
                        bllCouponType.UpdateCouponTypeIsVoucher(customer.Key);
                        BaseService.WriteLog("批量插入Coupon:");
                    }
                    if (dtVipCoupon != null && dtVipCoupon.Rows.Count > 0)
                    {
                        SqlBulkCopy(customer.Value, dtVipCoupon, "VipCouponMapping");
                        BaseService.WriteLog("批量插入VipCouponMapping:");
                    }
                    //BaseService.WriteLog("延迟时间开始");
                    //Thread.Sleep(1000);
                    //BaseService.WriteLog("延迟时间结束");
                }
                catch (Exception ex)
                {
                    BaseService.WriteLog("vip绑定优惠券异常" + ex.Message);
                    continue;
                }
            }
            BaseService.WriteLog("---------------------------vip绑定优惠券结束---------------------------");
        }
示例#17
0
        protected override GetCouponTypeListRD ProcessRequest(DTO.Base.APIRequest <GetCouponTypeListRP> pRequest)
        {
            var  rd   = new GetCouponTypeListRD();
            var  para = pRequest.Parameters;
            var  loggingSessionInfo = new SessionManager().CurrentUserLoginInfo;
            var  couponTypeBLL      = new CouponTypeBLL(loggingSessionInfo);
            bool IsEffective        = false;

            if (para.IsEffective != null)
            {
                IsEffective = para.IsEffective.Value;
            }
            //查询参数
            List <IWhereCondition> complexCondition = new List <IWhereCondition> {
            };

            complexCondition.Add(new EqualsCondition()
            {
                FieldName = "CustomerID", Value = loggingSessionInfo.ClientID
            });
            if (!string.IsNullOrEmpty(para.CouponTypeName))
            {
                complexCondition.Add(new LikeCondition()
                {
                    FieldName = "CouponTypeName", Value = "%" + para.CouponTypeName + "%"
                });
            }
            if (!string.IsNullOrEmpty(para.ParValue))
            {
                complexCondition.Add(new LikeCondition()
                {
                    FieldName = "ParValue", Value = para.ParValue.ToString()
                });
            }
            if (para.IsNotLimitQty != null && para.IsNotLimitQty.ToString() != "")
            {
                complexCondition.Add(new LikeCondition()
                {
                    FieldName = "IsNotLimitQty", Value = para.IsNotLimitQty.ToString()
                });
            }
            //过滤用完的 #bug 2838 (不改了 改从前端改)
            //complexCondition.Add(new DirectCondition(" ((IssuedQty-IsVoucher)>0) "));

            if (para.SurplusCount != null && para.SurplusCount == 1)
            {
                complexCondition.Add(new DirectCondition(" IssuedQty-IsVoucher>0 "));                                                                         //剩余张数大于o
                complexCondition.Add(new DirectCondition(" (EndTime>='" + DateTime.Now + "' OR (BeginTime IS NULL AND EndTime IS NULL AND ServiceLife>0))")); //剩余张数大于o  结束时间小于当前时间也要过滤掉
            }
            if (para.IsServiceLife == 1)
            {
                complexCondition.Add(new DirectCondition(" ServiceLife>0 "));                 //设置了有效期的相对时间
            }


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

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



            var tempList = couponTypeBLL.PagedQuery(complexCondition.ToArray(), lstOrder.ToArray(), para.PageSize, para.PageIndex);

            rd.TotalPageCount = tempList.PageCount;
            rd.TotalCount     = tempList.RowCount;
            rd.CouponTypeList = tempList.Entities.Select(t => new CouponTypeInfo()
            {
                CouponTypeID   = t.CouponTypeID,
                CouponTypeName = t.CouponTypeName,
                ParValue       = t.ParValue,
                IssuedQty      = t.IssuedQty,
                SurplusQty     = t.IssuedQty - (t.IsVoucher ?? 0),
                ValidityPeriod = t.BeginTime == null ? ("领取后" + (t.ServiceLife == 0 ? "1天内有效" : t.ServiceLife.ToString() + "天内有效")) : (t.BeginTime.Value.ToString("yyyy-MM-dd") + "至" + t.EndTime.Value.ToString("yyyy-MM-dd")),
                BeginTime      = t.BeginTime,
                EndTime        = t.EndTime,
                BeginTimeDate  = t.BeginTime == null ? "" : t.BeginTime.Value.ToString("yyyy年MM月dd日"),
                EndTimeDate    = t.EndTime == null ? "" : t.EndTime.Value.ToString("yyyy年MM月dd日"),
                ServiceLife    = t.ServiceLife,
                IsNotLimitQty  = t.IsNotLimitQty
            }).ToArray();
            return(rd);
        }
        public void InsertDataBase(string strCustomerId, string strVipId, string strObjectId, string strSource, CC_Coupon coupon)
        {
            try
            {
                string customerCon = GetCustomerConn(strCustomerId);

                LoggingSessionInfo loggingSessionInfo    = new LoggingSessionInfo();
                LoggingManager     CurrentLoggingManager = new LoggingManager();
                loggingSessionInfo.ClientID                = strCustomerId;
                CurrentLoggingManager.Connection_String    = customerCon;
                loggingSessionInfo.CurrentLoggingManager   = CurrentLoggingManager;
                loggingSessionInfo.CurrentUser             = new BS.Entity.User.UserInfo();
                loggingSessionInfo.CurrentUser.customer_id = strCustomerId;

                DataTable dtCoupon = new DataTable();
                dtCoupon.Columns.Add("CouponID", typeof(string));
                dtCoupon.Columns.Add("CouponCode", typeof(string));
                dtCoupon.Columns.Add("CouponDesc", typeof(string));
                dtCoupon.Columns.Add("BeginDate", typeof(DateTime));
                dtCoupon.Columns.Add("EndDate", typeof(DateTime));
                dtCoupon.Columns.Add("CouponUrl", typeof(string));
                dtCoupon.Columns.Add("ImageUrl", typeof(string));
                dtCoupon.Columns.Add("Status", typeof(Int32));
                dtCoupon.Columns.Add("CreateTime", typeof(DateTime));
                dtCoupon.Columns.Add("CreateBy", typeof(string));
                dtCoupon.Columns.Add("LastUpdateTime", typeof(DateTime));
                dtCoupon.Columns.Add("LastUpdateBy", typeof(string));
                dtCoupon.Columns.Add("IsDelete", typeof(Int32));
                dtCoupon.Columns.Add("CouponTypeID", typeof(string));
                dtCoupon.Columns.Add("CoupnName", typeof(string));
                dtCoupon.Columns.Add("DoorID", typeof(string));
                dtCoupon.Columns.Add("CouponPwd", typeof(string));
                dtCoupon.Columns.Add("CollarCardMode", typeof(string));
                dtCoupon.Columns.Add("CustomerID", typeof(string));
                DataTable dtVipCoupon = new DataTable();
                dtVipCoupon.Columns.Add("VipCouponMapping", typeof(string));
                dtVipCoupon.Columns.Add("VIPID", typeof(string));
                dtVipCoupon.Columns.Add("CouponID", typeof(string));
                dtVipCoupon.Columns.Add("UrlInfo", typeof(string));
                dtVipCoupon.Columns.Add("IsDelete", typeof(Int32));
                dtVipCoupon.Columns.Add("LastUpdateBy", typeof(string));
                dtVipCoupon.Columns.Add("LastUpdateTime", typeof(DateTime));
                dtVipCoupon.Columns.Add("CreateBy", typeof(string));
                dtVipCoupon.Columns.Add("CreateTime", typeof(DateTime));
                dtVipCoupon.Columns.Add("FromVipId", typeof(string));
                dtVipCoupon.Columns.Add("ObjectId", typeof(string));
                dtVipCoupon.Columns.Add("CouponSourceId", typeof(string));

                RedisCouponBLL redisCouponBLL = new RedisCouponBLL();
                var            response       = redisCouponBLL.RedisGetCoupon(coupon);


                if (response.Code == ResponseCode.Success && response.Result.CouponTypeId != null)
                {
                    //String uperStr = StringUtil.GetRandomUperStr(4);
                    //String strInt = StringUtil.GetRandomStrInt(8);
                    //string strCouponCode = uperStr + "-" + strInt;
                    string strCouponCode = string.Empty;
                    strCouponCode = GetCouponNum(loggingSessionInfo, strCustomerId);
                    string strCouponId = Guid.NewGuid().ToString();

                    DataRow dr_Coupon = dtCoupon.NewRow();
                    dr_Coupon["CouponID"]   = strCouponId;
                    dr_Coupon["CouponCode"] = strCouponCode;
                    dr_Coupon["CouponDesc"] = response.Result.CouponTypeDesc;
                    if (response.Result.ServiceLife > 0)
                    {
                        dr_Coupon["BeginDate"] = DateTime.Now;
                        dr_Coupon["EndDate"]   = DateTime.Now.Date.AddDays(response.Result.ServiceLife - 1).ToShortDateString() + " 23:59:59.998";
                    }
                    else
                    {
                        dr_Coupon["BeginDate"] = response.Result.BeginTime;
                        dr_Coupon["EndDate"]   = response.Result.EndTime;
                    }
                    dr_Coupon["CouponUrl"]      = "";
                    dr_Coupon["ImageUrl"]       = "";
                    dr_Coupon["Status"]         = 2;
                    dr_Coupon["CreateTime"]     = DateTime.Now;
                    dr_Coupon["CreateBy"]       = "Redis";
                    dr_Coupon["LastUpdateTime"] = DateTime.Now;
                    dr_Coupon["LastUpdateBy"]   = "Redis";
                    dr_Coupon["IsDelete"]       = 0;
                    dr_Coupon["CouponTypeID"]   = response.Result.CouponTypeId;
                    dr_Coupon["CoupnName"]      = response.Result.CouponTypeName;
                    dr_Coupon["DoorID"]         = "";
                    dr_Coupon["CouponPwd"]      = "";
                    dr_Coupon["CollarCardMode"] = "";
                    dr_Coupon["CustomerID"]     = strCustomerId;
                    dtCoupon.Rows.Add(dr_Coupon);

                    DataRow dr_VipCoupon = dtVipCoupon.NewRow();
                    dr_VipCoupon["VipCouponMapping"] = Guid.NewGuid().ToString().Replace("-", "");
                    dr_VipCoupon["VIPID"]            = strVipId;
                    dr_VipCoupon["CouponID"]         = strCouponId;
                    dr_VipCoupon["UrlInfo"]          = "";
                    dr_VipCoupon["IsDelete"]         = 0;
                    dr_VipCoupon["LastUpdateBy"]     = "Redis";
                    dr_VipCoupon["LastUpdateTime"]   = DateTime.Now;
                    dr_VipCoupon["CreateBy"]         = "Redis";
                    dr_VipCoupon["CreateTime"]       = DateTime.Now;
                    dr_VipCoupon["FromVipId"]        = "";
                    dr_VipCoupon["ObjectId"]         = strObjectId;
                    dr_VipCoupon["CouponSourceId"]   = GetSourceId(strSource);


                    dtVipCoupon.Rows.Add(dr_VipCoupon);
                    if (strSource != "Activity")
                    {
                        try
                        {
                            ///优惠券到账通知
                            var CommonBLL = new CommonBLL();
                            var bllVip    = new VipBLL(loggingSessionInfo);
                            var vip       = bllVip.GetByID(strVipId);

                            string strValidityData = Convert.ToDateTime(dr_Coupon["BeginDate"].ToString()).ToShortDateString() + "-" + Convert.ToDateTime(dr_Coupon["EndDate"].ToString()).ToShortDateString();
                            CommonBLL.CouponsArrivalMessage(response.Result.CouponCode, response.Result.CouponTypeName, strValidityData, response.Result.CouponCategory == null ? "" : response.Result.CouponCategory, vip.WeiXinUserId, loggingSessionInfo);
                        }
                        catch (Exception ex)
                        {
                            BaseService.WriteLog("优惠券到账通知异常:" + ex.Message);
                        }
                    }
                }

                if (dtCoupon != null && dtCoupon.Rows.Count > 0)
                {
                    SqlBulkCopy(customerCon, dtCoupon, "Coupon");

                    var bllCouponType = new CouponTypeBLL(loggingSessionInfo);
                    bllCouponType.UpdateCouponTypeIsVoucher(strCustomerId);
                }
                if (dtVipCoupon != null && dtVipCoupon.Rows.Count > 0)
                {
                    SqlBulkCopy(customerCon, dtVipCoupon, "VipCouponMapping");
                }
            }
            catch (Exception ex)
            {
                BaseService.WriteLog("vip绑定优惠券异常" + ex.Message);
            }
            BaseService.WriteLog("---------------------------vip绑定优惠券结束---------------------------");
        }
示例#19
0
        protected override EmptyResponseData ProcessRequest(DTO.Base.APIRequest <SetCouponRP> pRequest)
        {
            var rd   = new EmptyResponseData();
            var para = pRequest.Parameters;
            var loggingSessionInfo       = new SessionManager().CurrentUserLoginInfo;
            var couponTypeBLL            = new CouponTypeBLL(loggingSessionInfo);
            var couponBLL                = new CouponBLL(loggingSessionInfo);
            var couponTypeUnitMappingBLL = new CouponTypeUnitMappingBLL(loggingSessionInfo);
            CouponTypeItemMappingBLL    bllCouponTypeItemMapping    = new CouponTypeItemMappingBLL(loggingSessionInfo);
            CouponTypeItemMappingEntity entityCouponTypeItemMapping = null;
            var redisCouponBLL = new JIT.CPOS.BS.BLL.RedisOperationBLL.Coupon.RedisCouponBLL();

            if (couponTypeBLL.ExistsCouponTypeName(para.CouponTypeName, loggingSessionInfo.ClientID) > 0)
            {
                throw new APIException(-1, "优惠券名称不可重复!");
            }
            var pTran = couponTypeBLL.GetTran();//事务

            using (pTran.Connection)
            {
                try
                {
                    CouponTypeEntity couponTypeEntity = null;
                    //保存券产品表
                    if (string.IsNullOrEmpty(para.CouponTypeID))//生成优惠券
                    {
                        couponTypeEntity = new CouponTypeEntity();

                        couponTypeEntity.CouponTypeName = para.CouponTypeName;
                        couponTypeEntity.CouponTypeDesc = para.CouponTypeDesc;
                        couponTypeEntity.CouponCategory = para.CouponCategory;
                        couponTypeEntity.ParValue       = para.ParValue;
                        couponTypeEntity.IsVoucher      = 0;
                        couponTypeEntity.UsableRange    = para.UsableRange;
                        if (para.BeginTime != DateTime.MinValue)
                        {
                            couponTypeEntity.BeginTime = para.BeginTime;
                        }
                        if (para.EndTime != DateTime.MinValue)
                        {
                            para.EndTime             = para.EndTime.AddHours(23).AddMinutes(59).AddSeconds(59);
                            couponTypeEntity.EndTime = para.EndTime;
                        }
                        couponTypeEntity.ServiceLife      = para.ServiceLife;
                        couponTypeEntity.ConditionValue   = para.ConditionValue;
                        couponTypeEntity.SuitableForStore = para.SuitableForStore;
                        couponTypeEntity.CustomerId       = loggingSessionInfo.ClientID;

                        couponTypeEntity.IsNotLimitQty = para.IsNotLimitQty;
                        if (para.IsNotLimitQty != null && para.IsNotLimitQty == 1)
                        {
                            couponTypeEntity.IssuedQty = 1000;
                        }
                        else
                        {
                            couponTypeEntity.IssuedQty = para.IssuedQty;
                        }

                        couponTypeEntity.IsRepeatable = 0;
                        couponTypeEntity.IsMixable    = 0;
                        couponTypeEntity.ValidPeriod  = 0;

                        couponTypeEntity.CouponTypeID = couponTypeBLL.CreateReturnID(couponTypeEntity, pTran);

                        redisCouponBLL.RedisSetSingleCoupon(new CC_Coupon()
                        {
                            CustomerId     = couponTypeEntity.CustomerId,
                            CouponTypeId   = couponTypeEntity.CouponTypeID.ToString(),
                            CouponTypeDesc = couponTypeEntity.CouponTypeDesc,
                            CouponTypeName = couponTypeEntity.CouponTypeName,
                            BeginTime      = couponTypeEntity.BeginTime.ToString(),
                            EndTime        = couponTypeEntity.EndTime.ToString(),
                            ServiceLife    = couponTypeEntity.ServiceLife ?? 0,
                            CouponLenth    = couponTypeEntity.IssuedQty ?? 0,
                            CouponCategory = couponTypeEntity.CouponCategory
                        });
                        //保存适用门店
                        if (para.SuitableForStore == 2)
                        {
                            CouponTypeUnitMappingEntity mapping = null;
                            foreach (var obj in para.ObjectIDList)
                            {
                                mapping = new CouponTypeUnitMappingEntity()
                                {
                                    CouponTypeID = couponTypeEntity.CouponTypeID,
                                    ObjectID     = obj.ObjectID,
                                    CustomerID   = loggingSessionInfo.ClientID
                                };
                                couponTypeUnitMappingBLL.Create(mapping, pTran);
                            }
                        }
                        if (!string.IsNullOrEmpty(para.BindType) && para.BindTypeIdList != null)
                        {
                            foreach (var objId in para.BindTypeIdList)
                            {
                                entityCouponTypeItemMapping = new CouponTypeItemMappingEntity()
                                {
                                    CouponTypeID = couponTypeEntity.CouponTypeID,
                                    BindType     = para.BindType,
                                    ObjectId     = objId.ObjectID
                                };
                                bllCouponTypeItemMapping.Create(entityCouponTypeItemMapping);
                            }
                        }
                    }
                    else//追加优惠券
                    {
                        couponTypeEntity            = couponTypeBLL.GetByID(para.CouponTypeID);
                        couponTypeEntity.IssuedQty += para.IssuedQty;
                        couponTypeBLL.Update(couponTypeEntity);


                        redisCouponBLL.RedisSetSingleCoupon(new CC_Coupon()
                        {
                            CustomerId     = couponTypeEntity.CustomerId,
                            CouponTypeId   = couponTypeEntity.CouponTypeID.ToString(),
                            CouponTypeDesc = couponTypeEntity.CouponTypeDesc,
                            CouponTypeName = couponTypeEntity.CouponTypeName,
                            BeginTime      = couponTypeEntity.BeginTime.ToString(),
                            EndTime        = couponTypeEntity.EndTime.ToString(),
                            ServiceLife    = couponTypeEntity.ServiceLife ?? 0,
                            CouponLenth    = para.IssuedQty,
                            CouponCategory = couponTypeEntity.CouponCategory
                        });
                    }

                    pTran.Commit();//提交事物

                    //批量生成券
                    //if (couponTypeEntity != null)
                    //{
                    //    Hashtable htCouponInfo = new Hashtable();
                    //    htCouponInfo["CouponTypeID"] = couponTypeEntity.CouponTypeID;
                    //    htCouponInfo["CouponName"] = couponTypeEntity.CouponTypeName;
                    //    htCouponInfo["CouponDesc"] = couponTypeEntity.CouponTypeDesc;
                    //    if (couponTypeEntity.BeginTime != DateTime.MinValue)
                    //        htCouponInfo["BeginTime"] = couponTypeEntity.BeginTime;
                    //    else
                    //        htCouponInfo["BeginTime"] = null;
                    //    if (couponTypeEntity.EndTime != DateTime.MinValue)
                    //        htCouponInfo["EndTime"] = couponTypeEntity.EndTime;
                    //    else
                    //        htCouponInfo["EndTime"] = null;
                    //    htCouponInfo["IssuedQty"] = para.IssuedQty;
                    //    couponBLL.GenerateCoupon(htCouponInfo);
                    //}
                }
                catch (Exception ex)
                {
                    pTran.Rollback();
                    throw new APIException(ex.Message);
                }
            }
            return(rd);
        }