예제 #1
0
        /// <summary>
        /// 添加订单评价  InsertResourcesCommodityEvaluation
        /// </summary>
        /// <param name="row"></param>
        /// RpdCode             订单明细表ID【必填】
        /// ResourcesID         商品编码【必填】
        /// EvaluateContent     评价内容
        /// UploadImg           上传图片
        /// Star                商品评星
        /// EvaluateDate        评价时间
        /// 返回:
        ///     false:错误信息
        ///     true:操作成功
        /// <returns></returns>
        private string InsertResourcesCommodityEvaluation(DataRow row)
        {
            if (!row.Table.Columns.Contains("RpdCode") || string.IsNullOrEmpty(row["RpdCode"].ToString()))
            {
                return(JSONHelper.FromString(false, "评价内容不能为空"));
            }

            string RpdCode = row["RpdCode"].ToString();

            IDbConnection con = new SqlConnection(PubConstant.GetConnectionString("BusinessContionString"));
            string        str = "";

            try
            {
                Tb_Resources_CommodityEvaluation RCE = new Tb_Resources_CommodityEvaluation();

                foreach (string item in RpdCode.Split(','))
                {
                    string[] str_Ev = item.Split(':');
                    RCE.Id              = Guid.NewGuid().ToString();
                    RCE.RpdCode         = str_Ev[0];
                    RCE.Star            = AppGlobal.StrToDec(str_Ev[2]);
                    RCE.EvaluateDate    = DateTime.Now;
                    RCE.IsDelete        = 0;
                    RCE.EvaluateContent = str_Ev[1];

                    Tb_Charge_ReceiptDetail m = con.Query <Tb_Charge_ReceiptDetail>("select * from Tb_Charge_ReceiptDetail where RpdCode=@ResourcesID", new { ResourcesID = str_Ev[0] }).SingleOrDefault <Tb_Charge_ReceiptDetail>();
                    if (m != null)
                    {
                        RCE.ResourcesID = m.ResourcesID;
                    }

                    con.Insert <Tb_Resources_CommodityEvaluation>(RCE);
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }

            if (str != "")
            {
                return(JSONHelper.FromString(false, str));
            }
            else
            {
                return(JSONHelper.FromString(true, "操作成功"));
            }
        }
        /// <summary>
        /// 生成商家订单
        /// </summary>
        public string GenerateBusinessOrder(DataSet Ds, string communityId, string BussId, string UserId, string txnTime, ref bool IsOk, ref decimal Amount, ref decimal CouponAmount, ref string OrderId, string Name, string Mobile, string DeliverAddress)
        {
            DataRow Row = Ds.Tables[0].Rows[0];

            int?corpId = null;

            if (Row.Table.Columns.Contains("CorpId") && !string.IsNullOrEmpty(Row["CorpId"].ToString()))
            {
                corpId = AppGlobal.StrToInt(Row["CorpId"].ToString());
            }

            var iid = Guid.NewGuid().ToString();

            // 生成商家收款订单
            Tb_Charge_Receipt Receipt = new Tb_Charge_Receipt
            {
                Id             = iid,
                CorpId         = corpId,
                BussId         = BussId.ToString(),
                UserId         = UserId,
                OrderId        = Guid.NewGuid().ToString().Replace("-", ""),
                ReceiptSign    = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString(),
                Name           = Name,
                IsPay          = "未付款",
                IsReceive      = "未收货",
                IsDeliver      = "未发货",
                ReceiptMemo    = Row["ReceiptMemo"].ToString(),
                ReceiptType    = "通用票据",
                ReceiptDate    = DateTime.Now,
                PayDate        = null,
                MchId          = c.partner,
                Partner        = c.partner,
                PrepayStr      = "",
                txnTime        = txnTime.ToString(),
                ReturnCode     = "",
                ReturnMsg      = "",
                Express        = "",
                ExpressNum     = "",
                Mobile         = Mobile,         //联系电话
                DeliverAddress = DeliverAddress, //收货地址
                IsDelete       = 0
            };

            // 是否使用优惠券抵扣
            if (Row.Table.Columns.Contains("UseCoupon"))
            {
                Receipt.IsUseCoupon = AppGlobal.StrToInt(Row["UseCoupon"].ToString());
            }


            using (IDbConnection conn = new SqlConnection(ConnectionDb.GetBusinessConnection()))
            {
                // 保存订单信息
                conn.Insert(Receipt);

                if (!string.IsNullOrEmpty(communityId))
                {
                    conn.Execute("UPDATE Tb_Charge_Receipt SET CommunityId=@CommunityId WHERE ID=@IID",
                                 new { CommunityId = communityId, IID = iid });
                }

                /*
                 *  计算此时的订单金额,此时不应该保存商品的价格信息;
                 *  如果用户不付款,且订单未取消期间,商家更改了商品单价或可优惠价或规格追加价,付款时则需要重新计算
                 *
                 *  1、获取用户在该商家的可用优惠券余额
                 *  2、获取商品此时的单价和可优惠价,对应的规格型号的追加单价
                 *  3、计算当前订单内的商品是否支持优惠券抵扣,如果支持,计算最多能抵扣的价格并更新优惠券余额
                 */

                // 1、获取用户优惠券余额
                dynamic balanceInfo = conn.Query <dynamic>(@"SELECT isnull(Balance1,0) AS Balance1,isnull(Balance2,0) AS Balance2
                                                            FROM
                                                              (SELECT Balance1=(SELECT Balance FROM Tb_Resources_CouponBalance
                                                              WHERE UserId=@UserId
                                                                    AND CorpId=@CorpId AND BussId=@BussId),
                                                                    Balance2=(SELECT Balance FROM Tb_Resources_CouponBalance
                                                              WHERE UserId=@UserId
                                                                    AND CorpId=@CorpId AND BussId IS NULL)) as x;",
                                                           new { UserId = Receipt.UserId, CorpId = corpId, BussId = Receipt.BussId }).FirstOrDefault();

                decimal totalAmount         = 0.0m; // 商品总价
                decimal userCouponBalance   = 0.0m; // 用户可用优惠券余额
                decimal totalUseCouponMoney = 0.0m; // 当前能使用优惠券抵扣的钱

                decimal bussBalance = 0.0m;         // 商家专用券余额
                decimal corpBalance = 0.0m;         // 物管通用券余额

                if (balanceInfo != null)
                {
                    bussBalance       = balanceInfo.Balance1;
                    corpBalance       = balanceInfo.Balance2;
                    userCouponBalance = bussBalance + corpBalance;
                }

                // 2、获取商品价格信息
                foreach (DataRow DetailRow in Ds.Tables["Product"].Rows)
                {
                    // 订单商品详情
                    Tb_Charge_ReceiptDetail ReceiptDetail = new Tb_Charge_ReceiptDetail();
                    ReceiptDetail.RpdCode      = Guid.NewGuid().ToString();
                    ReceiptDetail.ReceiptCode  = Receipt.Id;
                    ReceiptDetail.ShoppingId   = DetailRow["ShoppingId"].ToString();
                    ReceiptDetail.ResourcesID  = DetailRow["Id"].ToString();
                    ReceiptDetail.RpdMemo      = DetailRow["RpdMemo"].ToString();
                    ReceiptDetail.Quantity     = DataSecurity.StrToInt(DetailRow["Quantity"].ToString());
                    ReceiptDetail.OffsetMoney  = 0.0m;
                    ReceiptDetail.OffsetMoney2 = 0.0m;

                    // 商品的单价和可优惠单价
                    string sql = @"SELECT * FROM Tb_Resources_Details 
                                   WHERE isnull(IsDelete,0)=0 AND IsRelease='是' AND IsStopRelease='否' AND ResourcesID=@ResourcesID";
                    Tb_Resources_Details ResourcesDetail = conn.Query <Tb_Resources_Details>(sql, new { ResourcesID = ReceiptDetail.ResourcesID }).FirstOrDefault();

                    // 商品存在,期间未失效
                    if (ResourcesDetail != null)
                    {
                        // 库存不足,跳过
                        if (ReceiptDetail.Quantity > ResourcesDetail.ResourcesCount)
                        {
                            continue;
                        }

                        ReceiptDetail.SalesPrice    = ResourcesDetail.ResourcesSalePrice;
                        ReceiptDetail.DiscountPrice = ResourcesDetail.ResourcesDisCountPrice;

                        bool IsInGroupBuyTime = false;

                        if (ResourcesDetail.IsGroupBuy == "是")
                        {
                            if (ResourcesDetail.GroupBuyStartDate.HasValue && ResourcesDetail.GroupBuyStartDate.Value <= DateTime.Now &&
                                ResourcesDetail.GroupBuyEndDate.HasValue && ResourcesDetail.GroupBuyEndDate.Value >= DateTime.Now)
                            {
                                IsInGroupBuyTime         = true;
                                ReceiptDetail.GroupPrice = ResourcesDetail.GroupBuyPrice;
                            }
                        }

                        // 1、商品单价
                        decimal price = 0.0m;

                        if (IsInGroupBuyTime)
                        {
                            price = (ResourcesDetail.GroupBuyPrice.Value - ResourcesDetail.ResourcesDisCountPrice) * ReceiptDetail.Quantity;
                        }
                        else
                        {
                            price = (ResourcesDetail.ResourcesSalePrice - ResourcesDetail.ResourcesDisCountPrice) * ReceiptDetail.Quantity;
                        }

                        // 2、商品规格追加价格
                        sql = "SELECT * FROM View_Tb_ResourcesSpecificationsPrice WHERE ShoppingId=@ShoppingId";
                        MobileSoft.Model.Resources.Tb_ResourcesSpecificationsPrice propertyInfo = conn.Query <MobileSoft.Model.Resources.Tb_ResourcesSpecificationsPrice>(sql, new { ShoppingId = DetailRow["ShoppingId"].ToString() }).FirstOrDefault();

                        if (propertyInfo != null && propertyInfo.Price.HasValue)
                        {
                            price = price + propertyInfo.Price.Value * ReceiptDetail.Quantity;
                        }

                        // 当前商品需要抵扣的金额
                        decimal currCouponMoney = 0.0m;

                        string isSupportCoupon = "";
                        // 3、商品支持抵扣券 并且 还有用户还有足够的优惠券余额
                        if (ResourcesDetail.IsSupportCoupon == "1")
                        {
                            isSupportCoupon = "是";
                        }
                        else
                        {
                            isSupportCoupon = "否";
                        }
                        if (isSupportCoupon == "是" &&
                            Receipt.IsUseCoupon.HasValue &&
                            Receipt.IsUseCoupon.Value > 0 &&
                            userCouponBalance > 0)
                        {
                            // 计算当前商品需要抵扣的金额
                            currCouponMoney = (ResourcesDetail.MaximumCouponMoney.HasValue ? ResourcesDetail.MaximumCouponMoney.Value : 0) * ReceiptDetail.Quantity;

                            if (bussBalance > 0)
                            {
                                if (bussBalance >= currCouponMoney)
                                {
                                    // 优惠券使用明细
                                    ReceiptDetail.OffsetMoney  = currCouponMoney;
                                    ReceiptDetail.OffsetMoney2 = 0.0m;

                                    totalUseCouponMoney += currCouponMoney;

                                    bussBalance       -= currCouponMoney;
                                    userCouponBalance -= currCouponMoney;
                                }
                                else
                                {
                                    // 先用专用券抵扣
                                    ReceiptDetail.OffsetMoney = bussBalance;

                                    totalUseCouponMoney += bussBalance;

                                    userCouponBalance -= bussBalance;

                                    // 专用券不够差额
                                    decimal differ = currCouponMoney - bussBalance;

                                    // 专用券不够,通用券余额大于0
                                    if (corpBalance > 0)
                                    {
                                        // 通用券足够抵扣
                                        if (corpBalance >= differ)
                                        {
                                            ReceiptDetail.OffsetMoney2 = differ;

                                            totalUseCouponMoney += differ;

                                            corpBalance       -= differ;
                                            userCouponBalance -= differ;
                                        }
                                        // 通用券不足以抵扣
                                        else
                                        {
                                            ReceiptDetail.OffsetMoney2 = corpBalance;

                                            totalUseCouponMoney += corpBalance;

                                            userCouponBalance -= corpBalance;
                                            corpBalance        = 0;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // 没有专用券,但是有通用券
                                if (corpBalance > 0)
                                {
                                    // 通用券足够抵扣
                                    if (corpBalance > currCouponMoney)
                                    {
                                        ReceiptDetail.OffsetMoney2 = currCouponMoney;

                                        totalUseCouponMoney += currCouponMoney;

                                        corpBalance       -= currCouponMoney;
                                        userCouponBalance -= currCouponMoney;
                                    }
                                    // 通用券不足以抵扣
                                    else
                                    {
                                        ReceiptDetail.OffsetMoney2 = corpBalance;

                                        totalUseCouponMoney += corpBalance;

                                        userCouponBalance -= corpBalance;
                                        corpBalance        = 0;
                                    }
                                }
                            }
                        }

                        // 订单商品总价追加
                        totalAmount += price;

                        // 插入订单内商品数据
                        conn.Insert(ReceiptDetail);
                    }

                    // 删除购物车
                    conn.Execute("UPDATE Tb_ShoppingCar SET IsDelete=1 WHERE Id=@ShoppingId", new { ShoppingId = ReceiptDetail.ShoppingId });
                }

                // 3、更新用户优惠券信息
                if (totalUseCouponMoney > 0)
                {
                    conn.Execute("proc_Resources_CouponBalance_Use",
                                 new { UserId = Receipt.UserId, CorpId = corpId, BussId = Receipt.BussId, UseMoney = totalUseCouponMoney },
                                 null, null, CommandType.StoredProcedure);
                }

                // ref参数处理
                IsOk         = true;
                Amount       = totalAmount;
                CouponAmount = totalUseCouponMoney;
                OrderId      = Receipt.OrderId;
            }

            return("生成订单成功");
        }
예제 #3
0
        /// <summary>
        /// 生成商家订单
        /// </summary>
        /// <param name="Ds"></param>
        /// <param name="BussId"></param>
        /// <param name="UserId"></param>
        /// <param name="txnTime"></param>
        /// <param name="IsOk"></param>
        /// <param name="Amount"></param>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public string GenerateBusinessOrder(DataSet Ds, string communityId, string BussId, string UserId, string txnTime, ref bool IsOk, ref string Amount, ref string OrderId, WxPayConfig wxPayConfig)
        {
            DataRow Row = Ds.Tables[0].Rows[0];

            IDbConnection Conn            = new SqlConnection(ConnectionDb.GetBusinessConnection());
            string        BusinessOrderId = Guid.NewGuid().ToString();

            //生成商家收款订单
            string            Id            = Guid.NewGuid().ToString();
            Tb_Charge_Receipt EntityReceipt = new Tb_Charge_Receipt();

            EntityReceipt.Id      = Id;
            EntityReceipt.BussId  = BussId.ToString();
            EntityReceipt.OrderId = BusinessOrderId;

            // 是否使用抵扣券
            if (Row.Table.Columns.Contains("UseCoupon"))
            {
                EntityReceipt.IsUseCoupon = AppGlobal.StrToInt(Row["UseCoupon"].ToString());
            }

            OrderId = BusinessOrderId;

            string ReceiptSign = "";//获得订单号
            //获取票据号
            DynamicParameters dp = new DynamicParameters();

            dp.Add("@Id", BussId);
            dp.Add("@OrderLength", 32);
            dp.Add("@Num", "", DbType.String, ParameterDirection.Output);
            using (IDbConnection IDbConn = new SqlConnection(ConnectionDb.GetBusinessConnection()))
            {
                IDbConn.Execute("Proc_GetOrderNum", dp, null, null, CommandType.StoredProcedure);
                ReceiptSign = dp.Get <string>("@Num");
            }
            EntityReceipt.ReceiptSign = ReceiptSign.ToString();

            EntityReceipt.UserId = UserId.ToString();


            IDbConnection ConnUnified = new SqlConnection(ConnectionDb.GetUnifiedConnectionString());
            string        QueryUser   = "******";
            Tb_User       EntityUser  = ConnUnified.Query <Tb_User>(QueryUser, new { UserId = UserId }).SingleOrDefault();

            //查找用户名称
            EntityReceipt.Name      = EntityUser.Name.ToString();
            EntityReceipt.Mobile    = EntityUser.Mobile.ToString();
            EntityReceipt.IsPay     = "未付款";
            EntityReceipt.IsReceive = "未收货";

            EntityReceipt.Amount         = 0;
            EntityReceipt.ReceiptMemo    = Row["ReceiptMemo"].ToString();
            EntityReceipt.ReceiptType    = "通用票据";
            EntityReceipt.ReceiptDate    = DateTime.Now;
            EntityReceipt.MchId          = wxPayConfig.MCHID;
            EntityReceipt.Partner        = wxPayConfig.MCHID;
            EntityReceipt.PrepayStr      = "";
            EntityReceipt.txnTime        = txnTime.ToString();
            EntityReceipt.ReturnCode     = "";
            EntityReceipt.ReturnMsg      = "";
            EntityReceipt.IsDeliver      = "未发货";
            EntityReceipt.Express        = "";
            EntityReceipt.ExpressNum     = "";
            EntityReceipt.DeliverAddress = "";

            EntityReceipt.PayDate = DateTime.Now;

            EntityReceipt.IsDelete = 0;

            Conn.Insert(EntityReceipt);

            if (!string.IsNullOrEmpty(communityId))
            {
                Conn.Execute("UPDATE Tb_Charge_Receipt SET CommunityId=@CommunityId WHERE ID=@IID",
                             new { CommunityId = communityId, IID = EntityReceipt.Id });
            }

            decimal TotalAmount = 0.00M;

            //收成商家收款明细

            foreach (DataRow DetailRow in Ds.Tables[1].Rows)
            {
                Tb_Charge_ReceiptDetail EntityReceiptDetail = new Tb_Charge_ReceiptDetail();
                EntityReceiptDetail.RpdCode     = Guid.NewGuid().ToString();
                EntityReceiptDetail.ReceiptCode = Id;
                EntityReceiptDetail.ResourcesID = DetailRow["Id"].ToString();
                EntityReceiptDetail.Quantity    = DataSecurity.StrToInt(DetailRow["Quantity"].ToString());

                string QueryResourcesSql = "SELECT * FROM Tb_Resources_Details WHERE ResourcesID=@ResourcesID";
                Tb_Resources_Details T   = Conn.Query <Tb_Resources_Details>(QueryResourcesSql, new { ResourcesID = DetailRow["Id"].ToString() }).SingleOrDefault();

                EntityReceiptDetail.SalesPrice    = T.ResourcesSalePrice;
                EntityReceiptDetail.DiscountPrice = T.ResourcesDisCountPrice;
                EntityReceiptDetail.GroupPrice    = T.GroupBuyPrice;
                EntityReceiptDetail.DetailAmount  = T.ResourcesSalePrice - T.ResourcesDisCountPrice;
                EntityReceiptDetail.RpdMemo       = DetailRow["RpdMemo"].ToString();
                Conn.Insert(EntityReceiptDetail);
                //计算订单的总金额
                TotalAmount = TotalAmount + DataSecurity.StrToDecimal(EntityReceiptDetail.DetailAmount.ToString());
            }

            //更新订单总金额
            EntityReceipt.Amount = TotalAmount;
            Amount = Convert.ToString(TotalAmount * 100);
            IsOk   = true;
            Conn.Update(EntityReceipt);
            return("生成订单成功");
        }
예제 #4
0
        /// <summary>
        /// 生成订单        SetOrder
        /// </summary>
        /// <param name="row"></param>
        /// ShoppingDetailed            购物车明细编号【必填】
        /// UserAddressId               收货地址编号【必填】
        /// UserId                      用户编号【必填】
        /// 返回:
        ///     true:""
        ///     false:errmessage
        /// <returns></returns>
        private string SetOrder(DataRow row)
        {
            if (!row.Table.Columns.Contains("ShoppingDetailed") || string.IsNullOrEmpty(row["ShoppingDetailed"].ToString()))
            {
                return(JSONHelper.FromString(false, "购物车明细编号不能为空"));
            }
            if (!row.Table.Columns.Contains("UserAddressId") || string.IsNullOrEmpty(row["UserAddressId"].ToString()))
            {
                return(JSONHelper.FromString(false, "收货地址编号不能为空"));
            }
            if (!row.Table.Columns.Contains("UserId") || string.IsNullOrEmpty(row["UserId"].ToString()))
            {
                return(JSONHelper.FromString(false, "用户编号不能为空"));
            }

            IDbConnection con = new SqlConnection(PubConstant.GetConnectionString("BusinessContionString"));
            string        str = "";

            try
            {
                //获取收货地址
                Tb_User_Address UserAddress = BussinessCommon.GetAddressModel(row["UserAddressId"].ToString());

                //获取购物明细
                DataTable Dt_ShoppingDetailed = BussinessCommon.GetShoppingDetailedView(" Id in (" + BussinessCommon.GetShoppingDetailedIdS(row["ShoppingDetailed"].ToString()) + ")");

                if (Dt_ShoppingDetailed == null || Dt_ShoppingDetailed.Rows.Count <= 0)
                {
                    return(JSONHelper.FromString(false, "生成订单失败:未找到购物明细"));
                }


                Tb_Charge_Receipt Order = new Tb_Charge_Receipt();

                //根据商家ID分组
                var query = from t in Dt_ShoppingDetailed.AsEnumerable()
                            group t by new { t1 = t.Field <string>("BussId") } into m
                    select new
                {
                    BussId = m.Key.t1
                };
                if (query.ToList().Count > 0)
                {
                    query.ToList().ForEach(q =>
                    {
                        //生成订单
                        Order             = new Tb_Charge_Receipt();
                        Order.Id          = Guid.NewGuid().ToString();
                        Order.BussId      = q.BussId;
                        Order.OrderId     = Guid.NewGuid().ToString();
                        Order.ReceiptSign = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString();
                        Order.UserId      = row["UserId"].ToString();
                        if (UserAddress != null)
                        {
                            if (UserAddress.Address != "" && UserAddress.Address.Split(',').Length > 0)
                            {
                                Order.Name           = UserAddress.Address.Split(',')[0];
                                Order.DeliverAddress = UserAddress.Address.Split(',')[1];
                            }
                            Order.Mobile = UserAddress.Mobile;
                        }
                        else
                        {
                            throw new Exception("该收货地址不存在");
                        }
                        Order.ReceiptDate = DateTime.Now;
                        Order.IsReceive   = "未收货";
                        Order.IsDeliver   = "未发货";
                        Order.IsPay       = "未付款";
                        Order.IsDelete    = 0;
                        //查询此商家的所有购物车明细
                        DataRow[] dr = Dt_ShoppingDetailed.Select("BussId=" + q.BussId);
                        //生成订单明细
                        foreach (DataRow item in dr)
                        {
                            Tb_Charge_ReceiptDetail OrderDetail = new Tb_Charge_ReceiptDetail();
                            OrderDetail.RpdCode       = Guid.NewGuid().ToString();
                            OrderDetail.ReceiptCode   = Order.Id;
                            OrderDetail.ResourcesID   = item["ResourcesID"].ToString();
                            OrderDetail.Quantity      = AppGlobal.StrToInt(item["Number"].ToString());
                            OrderDetail.SalesPrice    = AppGlobal.StrToDec(item["ResourcesSalePrice"].ToString());
                            OrderDetail.DiscountPrice = AppGlobal.StrToDec(item["ResourcesDisCountPrice"].ToString());
                            OrderDetail.GroupPrice    = AppGlobal.StrToDec(item["GroupBuyPrice"].ToString());
                            OrderDetail.DetailAmount  = AppGlobal.StrToDec(item["SubtotalMoney"].ToString());;
                            OrderDetail.RpdMemo       = "";
                            OrderDetail.RpdIsDelete   = 0;
                            //累计订单金额【取销售价格】
                            Order.Amount += AppGlobal.StrToDec(OrderDetail.SalesPrice.ToString()) * AppGlobal.StrToDec(OrderDetail.Quantity.ToString());
                            //生成订单明细
                            con.Insert <Tb_Charge_ReceiptDetail>(OrderDetail);
                        }
                        //生成订单
                        con.Insert <Tb_Charge_Receipt>(Order);
                        //判断此商家中是否存在该客户
                        string sqlStr      = "select BussId from Tb_Customer_List where BussId='" + q.BussId + "' and UserId='" + row["UserId"] + "' and Mobile='" + UserAddress.Mobile + "'";
                        List <string> list = con.Query <string>(sqlStr, null, null, true, null, CommandType.Text).ToList <string>();
                        //如果不存在,将此客户添加至此商家的客户资料中
                        if (list.Count <= 0)
                        {
                            Tb_Customer_List cust = new Tb_Customer_List();
                            cust.Id       = Guid.NewGuid().ToString();
                            cust.BussId   = q.BussId;
                            cust.UserId   = row["UserId"].ToString();
                            cust.Mobile   = UserAddress.Mobile;
                            cust.CustName = "";
                            con.Insert <Tb_Customer_List>(cust);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                str = ex.Message;
            }
            if (str != "")
            {
                return(JSONHelper.FromString(false, str));
            }
            else
            {
                return(JSONHelper.FromString(true, ""));
            }
        }
예제 #5
0
        /// <summary>
        /// 生成商家订单
        /// </summary>
        public string SubmitOrder_Changcheng(DataSet Ds)
        {
            DataRow Row = Ds.Tables[0].Rows[0];

            string txnTime = DateTime.Now.ToString("yyyyMMddHHmmss");

            string BussId         = Row["BussId"].ToString();
            string UserId         = Row["UserId"].ToString();
            string Name           = Row["Name"].ToString();
            string Mobile         = Row["Mobile"].ToString();
            string DeliverAddress = Row["DeliverAddress"].ToString();

            int dispatchingType = 0;

            if (Row.Table.Columns.Contains("DispatchingType") && !string.IsNullOrEmpty(Row["DispatchingType"].ToString()))
            {
                int.TryParse(Row["DispatchingType"].ToString(), out dispatchingType);
            }

            String expectedDeliveryTime = String.Empty;

            if (Row.Table.Columns.Contains("ExpectedDeliveryTime") && !string.IsNullOrEmpty(Row["ExpectedDeliveryTime"].ToString()))
            {
                expectedDeliveryTime = Row["ExpectedDeliveryTime"].ToString();
            }

            String province = String.Empty;

            if (Row.Table.Columns.Contains("Province") && !string.IsNullOrEmpty(Row["Province"].ToString()))
            {
                province = Row["Province"].ToString();
            }

            decimal freight = 0M;

            if (Row.Table.Columns.Contains("Freight") && !string.IsNullOrEmpty(Row["Freight"].ToString()) && decimal.TryParse(Row["Freight"].ToString(), out freight))
            {
            }

            int?   corpId      = null;
            string communityId = null;

            if (Row.Table.Columns.Contains("CorpId") && !string.IsNullOrEmpty(Row["CorpId"].ToString()))
            {
                corpId = AppGlobal.StrToInt(Row["CorpId"].ToString());
            }
            if (Row.Table.Columns.Contains("CommunityId") && !string.IsNullOrEmpty(Row["CommunityId"].ToString()))
            {
                communityId = Row["CommunityId"].ToString();
            }

            var iid = Guid.NewGuid().ToString();
            var alipayBusinessOrder_Changcheng = new AlipayBusinessOrder_Changcheng();
            var config = alipayBusinessOrder_Changcheng.GetGenerateConfig(BussId);
            // 生成商家收款订单
            Tb_Charge_Receipt Receipt = new Tb_Charge_Receipt
            {
                Id              = iid,
                CorpId          = corpId,
                BussId          = BussId.ToString(),
                UserId          = UserId,
                OrderId         = Guid.NewGuid().ToString(),
                ReceiptSign     = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString(),
                Name            = Name,
                IsPay           = "未付款",
                IsReceive       = "未收货",
                IsDeliver       = "未发货",
                ReceiptMemo     = Row["ReceiptMemo"].ToString(),
                ReceiptType     = "通用票据",
                ReceiptDate     = DateTime.Now,
                PayDate         = null,
                MchId           = config == null ? "" : config.partner,
                Partner         = config == null ? "" : config.partner,
                PrepayStr       = "",
                txnTime         = txnTime.ToString(),
                ReturnCode      = "",
                ReturnMsg       = "",
                Express         = "",
                ExpressNum      = "",
                Mobile          = Mobile,                    //联系电话
                DeliverAddress  = province + DeliverAddress, //收货地址
                IsDelete        = 0,
                CommunityID     = communityId,
                DispatchingType = dispatchingType,
                //Freight = freight//运费
            };

            if (dispatchingType != 0 && dispatchingType == (int)BusiinessDispatchingEnum.Dispatching)
            {
                Receipt.RequestDeliveryTime = expectedDeliveryTime;
            }
            if (dispatchingType != 0 && dispatchingType == (int)BusiinessDispatchingEnum.TakeTheir)
            {
                Receipt.EstimatedPickUpTime = expectedDeliveryTime;
            }


            // 是否使用优惠券抵扣
            if (Row.Table.Columns.Contains("UseCoupon"))
            {
                Receipt.IsUseCoupon = AppGlobal.StrToInt(Row["UseCoupon"].ToString());
            }

            List <String> shoppingIdS = new List <String>();

            foreach (DataRow DetailRow in Ds.Tables["Product"].Rows)
            {
                shoppingIdS.Add(DetailRow["ShoppingId"].ToString());
            }

            if (dispatchingType == 1)
            {
                var fee = PMSFreight.GetGetFreight(province, shoppingIdS);
                if (fee == -2)
                {
                    return(JSONHelper.FromString(false, "对不起,您的收货地址不在配送范围内"));
                }
                if (fee >= 0 && fee != freight)
                {
                    return(JSONHelper.FromString(false, "运费不统一"));
                }
                Receipt.Freight = fee;
            }

            String moblie = String.Empty;

            using (var conn = new SqlConnection(PubConstant.BusinessContionString))
            {
                conn.Open();
                var trans = conn.BeginTransaction();

                try
                {
                    // 保存订单信息
                    conn.Insert(Receipt, trans);

                    //获取商家的手机号
                    String businessMoblieSql = "  SELECT  BussMobileTel FROM Tb_System_BusinessCorp WHERE bussId=@bussId ";
                    moblie = conn.QueryFirstOrDefault <String>(businessMoblieSql, new { bussId = BussId }, trans);

                    if (!string.IsNullOrEmpty(communityId))
                    {
                        conn.Execute("UPDATE Tb_Charge_Receipt SET CommunityId=@CommunityId WHERE ID=@IID",
                                     new { CommunityId = communityId, IID = iid }, trans);
                    }

                    /*
                     *  计算此时的订单金额,此时不应该保存商品的价格信息;
                     *  如果用户不付款,且订单未取消期间,商家更改了商品单价或可优惠价或规格追加价,付款时则需要重新计算
                     *
                     *  1、获取用户在该商家的可用优惠券余额
                     *  2、获取商品此时的单价和可优惠价,对应的规格型号的追加单价
                     *  3、计算当前订单内的商品是否支持优惠券抵扣,如果支持,计算最多能抵扣的价格并更新优惠券余额
                     */

                    // 1、获取用户优惠券余额
                    dynamic balanceInfo = conn.Query <dynamic>(@"SELECT isnull(Balance1,0) AS Balance1,isnull(Balance2,0) AS Balance2
                    FROM
                    (SELECT Balance1 = (SELECT Balance FROM Tb_Resources_CouponBalance
                        WHERE UserId = @UserId
                        AND CorpId = @CorpId AND BussId = @BussId),
                        Balance2 = (SELECT Balance FROM Tb_Resources_CouponBalance
                            WHERE UserId = @UserId
                            AND CorpId = @CorpId AND BussId IS NULL)) as x; ",
                                                               new { UserId = Receipt.UserId, CorpId = corpId, BussId = Receipt.BussId }, trans).FirstOrDefault();

                    decimal totalAmount         = 0.0m; // 商品总价
                    decimal userCouponBalance   = 0.0m; // 用户可用优惠券余额
                    decimal totalUseCouponMoney = 0.0m; // 当前能使用优惠券抵扣的钱

                    decimal bussBalance = 0.0m;         // 商家专用券余额
                    decimal corpBalance = 0.0m;         // 物管通用券余额

                    if (balanceInfo != null)
                    {
                        bussBalance       = balanceInfo.Balance1;
                        corpBalance       = balanceInfo.Balance2;
                        userCouponBalance = bussBalance + corpBalance;
                    }

                    // 2、获取商品价格信息
                    foreach (DataRow DetailRow in Ds.Tables["Product"].Rows)
                    {
                        // 订单商品详情
                        Tb_Charge_ReceiptDetail ReceiptDetail = new Tb_Charge_ReceiptDetail();
                        ReceiptDetail.RpdCode      = Guid.NewGuid().ToString();
                        ReceiptDetail.ReceiptCode  = Receipt.Id;
                        ReceiptDetail.ShoppingId   = DetailRow["ShoppingId"].ToString();
                        ReceiptDetail.ResourcesID  = DetailRow["Id"].ToString();
                        ReceiptDetail.RpdMemo      = DetailRow["RpdMemo"].ToString();
                        ReceiptDetail.Quantity     = DataSecurity.StrToInt(DetailRow["Quantity"].ToString());
                        ReceiptDetail.OffsetMoney  = 0.0m;
                        ReceiptDetail.OffsetMoney2 = 0.0m;

                        decimal specificationMoney = 0M;


                        // 商品的单价和可优惠单价
                        string sql = @"SELECT * FROM Tb_Resources_Details 
                        WHERE isnull(IsDelete, 0) = 0 AND IsRelease = '是' AND IsStopRelease = '否' AND ResourcesID = @ResourcesID";

                        Tb_Resources_Details ResourcesDetail = conn.Query <Tb_Resources_Details>(sql, new
                        {
                            ResourcesID = ReceiptDetail.ResourcesID
                        }, trans).FirstOrDefault();

                        #region 根据购物车获取具体的某一个规格属性 ,并使用该规格属性上得价格
                        String sqlStr = @"SELECT A.Price,A.DiscountAmount,A.GroupBuyingPrice FROM  Tb_ResourcesSpecificationsPrice AS A
                                        INNER JOIN  (SELECT B.ResourcesID,C.PropertysId,C.SpecId FROM Tb_ShoppingCar AS B
                                        LEFT JOIN Tb_ShoppingDetailed AS C ON B.Id=C.ShoppingId
                                        WHERE B.Id IS NOT NULL AND B.Id=@Id) AS D  ON  D.ResourcesID=A.ResourcesID AND D.PropertysId =A.PropertyId AND D.SpecId=A.SpecId";

                        var praceInfo = conn.QueryFirstOrDefault(sqlStr, new { Id = DetailRow["ShoppingId"].ToString() }, trans);
                        if (null == praceInfo)
                        {
                            return(JSONHelper.FromString(false, "商品没有规格属性"));
                        }

                        ResourcesDetail.ResourcesSalePrice     = (decimal)praceInfo.Price;
                        ResourcesDetail.GroupBuyPrice          = (decimal)praceInfo.GroupBuyingPrice;
                        ResourcesDetail.ResourcesDisCountPrice = (decimal)praceInfo.DiscountAmount;

                        #endregion

                        // 商品存在,期间未失效
                        if (ResourcesDetail != null)
                        {
                            //现在判断库存 修改为判断规格库存
                            sql = @"SELECT ISNULL(Inventory,0) FROM  Tb_ResourcesSpecificationsPrice AS A
                                    INNER JOIN  (SELECT B.ResourcesID,C.PropertysId,C.SpecId FROM Tb_ShoppingCar AS B
                                    LEFT JOIN Tb_ShoppingDetailed AS C ON B.Id=C.ShoppingId
                                    WHERE B.Id IS NOT NULL AND B.Id=@Id) AS D  ON  D.ResourcesID=A.ResourcesID AND D.PropertysId =A.PropertyId AND D.SpecId=A.SpecId;";
                            var inventory = conn.QueryFirstOrDefault <decimal>(sql, new { Id = ReceiptDetail.ShoppingId }, trans);
                            // 库存不足,跳过
                            if (ReceiptDetail.Quantity > inventory)
                            {
                                return(JSONHelper.FromString(false, "部分商品库存不足"));
                            }

                            //String sqlPrice = @"select b.Price from ( select SpecId,PropertysId from Tb_ShoppingDetailed where  ShoppingId=@ShoppingId) AS A
                            //INNER JOIN (SELECT Price,SpecId,PropertyId FROM View_Tb_ResourcesSpecificationsPrice_Filter  WHERE  ISNULL(ISDELETE,0)=0 AND  SpecId IS NOT NULL AND BussId=@BussId AND ResourcesID =@ResourcesID  ) AS  B  ON B.SpecId=A.SpecId AND B.PropertyId=A.PropertysId";
                            //var priceInfo = conn.QueryFirstOrDefault<decimal?>(sqlPrice, new { ShoppingId = ReceiptDetail.ShoppingId, BussId = BussId, ResourcesID = ReceiptDetail.ResourcesID }, trans);

                            //if (priceInfo.HasValue)
                            //{
                            //    ReceiptDetail.SalesPrice = priceInfo.Value;
                            //    ResourcesDetail.ResourcesSalePrice = priceInfo.Value;
                            //}
                            //else
                            //{
                            //    ReceiptDetail.SalesPrice = ResourcesDetail.ResourcesSalePrice;
                            //}
                            ReceiptDetail.SalesPrice    = ResourcesDetail.ResourcesSalePrice;
                            ReceiptDetail.DiscountPrice = ResourcesDetail.ResourcesDisCountPrice;
                            bool IsInGroupBuyTime = false;

                            if (ResourcesDetail.IsGroupBuy == "是")
                            {
                                if (ResourcesDetail.GroupBuyStartDate.HasValue && ResourcesDetail.GroupBuyStartDate.Value <= DateTime.Now &&
                                    ResourcesDetail.GroupBuyEndDate.HasValue && ResourcesDetail.GroupBuyEndDate.Value >= DateTime.Now)
                                {
                                    IsInGroupBuyTime         = true;
                                    ReceiptDetail.GroupPrice = ResourcesDetail.GroupBuyPrice;
                                }
                            }

                            // 1、商品单价
                            decimal price = 0.0m;
                            if (IsInGroupBuyTime)
                            {
                                //团购价不算优惠价格
                                price = (ResourcesDetail.GroupBuyPrice.Value) * ReceiptDetail.Quantity;
                            }
                            else
                            {
                                price = (ResourcesDetail.ResourcesSalePrice - ResourcesDetail.ResourcesDisCountPrice) * ReceiptDetail.Quantity;
                            }

                            // 2、商品规格追加价格

                            /*
                             * 时间:2020-06-03  20-11
                             * 修改人:翟国雄
                             * 逻辑 现在确定价格之后不再增加所谓得规格价格 如果有规格 直接使用规格价格减去优惠价格即可
                             */


                            // 当前商品需要抵扣的金额
                            decimal currCouponMoney = 0.0m;

                            string isSupportCoupon = "";
                            // 3、商品支持抵扣券 并且 还有用户还有足够的优惠券余额
                            if (ResourcesDetail.IsSupportCoupon == "1")
                            {
                                isSupportCoupon = "是";
                            }
                            else
                            {
                                isSupportCoupon = "否";
                            }
                            if (isSupportCoupon == "是" &&
                                Receipt.IsUseCoupon.HasValue &&
                                Receipt.IsUseCoupon.Value > 0 &&
                                userCouponBalance > 0)
                            {
                                // 计算当前商品需要抵扣的金额
                                currCouponMoney = (ResourcesDetail.MaximumCouponMoney.HasValue ? ResourcesDetail.MaximumCouponMoney.Value : 0) * ReceiptDetail.Quantity;

                                if (bussBalance > 0)
                                {
                                    if (bussBalance >= currCouponMoney)
                                    {
                                        // 优惠券使用明细
                                        ReceiptDetail.OffsetMoney  = currCouponMoney;
                                        ReceiptDetail.OffsetMoney2 = 0.0m;

                                        totalUseCouponMoney += currCouponMoney;

                                        bussBalance       -= currCouponMoney;
                                        userCouponBalance -= currCouponMoney;
                                    }
                                    else
                                    {
                                        // 先用专用券抵扣
                                        ReceiptDetail.OffsetMoney = bussBalance;

                                        totalUseCouponMoney += bussBalance;

                                        userCouponBalance -= bussBalance;

                                        // 专用券不够差额
                                        decimal differ = currCouponMoney - bussBalance;

                                        // 专用券不够,通用券余额大于0
                                        if (corpBalance > 0)
                                        {
                                            // 通用券足够抵扣
                                            if (corpBalance >= differ)
                                            {
                                                ReceiptDetail.OffsetMoney2 = differ;

                                                totalUseCouponMoney += differ;

                                                corpBalance       -= differ;
                                                userCouponBalance -= differ;
                                            }
                                            // 通用券不足以抵扣
                                            else
                                            {
                                                ReceiptDetail.OffsetMoney2 = corpBalance;

                                                totalUseCouponMoney += corpBalance;

                                                userCouponBalance -= corpBalance;
                                                corpBalance        = 0;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    // 没有专用券,但是有通用券
                                    if (corpBalance > 0)
                                    {
                                        // 通用券足够抵扣
                                        if (corpBalance > currCouponMoney)
                                        {
                                            ReceiptDetail.OffsetMoney2 = currCouponMoney;

                                            totalUseCouponMoney += currCouponMoney;

                                            corpBalance       -= currCouponMoney;
                                            userCouponBalance -= currCouponMoney;
                                        }
                                        // 通用券不足以抵扣
                                        else
                                        {
                                            ReceiptDetail.OffsetMoney2 = corpBalance;

                                            totalUseCouponMoney += corpBalance;

                                            userCouponBalance -= corpBalance;
                                            corpBalance        = 0;
                                        }
                                    }
                                }
                            }

                            //if (priceInfo.HasValue)
                            //{
                            //    ReceiptDetail.OffsetMoney = ReceiptDetail.OffsetMoney + specificationMoney;
                            //}

                            // 订单商品总价追加
                            totalAmount += price;

                            // 插入订单内商品数据
                            conn.Insert(ReceiptDetail, trans);
                        }

                        // 删除购物车
                        conn.Execute("UPDATE Tb_ShoppingCar SET IsDelete=1 WHERE Id=@ShoppingId",
                                     new
                        {
                            ShoppingId = ReceiptDetail.ShoppingId
                        }, trans);
                    }

                    // 3、更新用户优惠券信息
                    if (totalUseCouponMoney > 0)
                    {
                        conn.Execute("proc_Resources_CouponBalance_Use",
                                     new { UserId = Receipt.UserId, CorpId = corpId, BussId = Receipt.BussId, UseMoney = totalUseCouponMoney }, trans, null, CommandType.StoredProcedure);
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return(JSONHelper.FromString(false, ex.Message + Environment.NewLine + ex.StackTrace));
                }
            }

            //订单信息商家推送
            //OrderInfoPush(corpId, Receipt.Id, moblie);

            return(new ApiResult(true, new { Id = Receipt.Id, OrderId = Receipt.OrderId }).toJson());
        }