• 拆单发货逻辑


    控制器:

    /// <summary>
            /// 根据id查询所有商品
            /// </summary>
            /// <param name="id">订单编号</param>
            /// <returns></returns>
            [Privilege(PrivilegeCode.None)]
            public ActionResult GetOrderItem(int id, string deliveryTypeName)
            {
                //取商品信息
                int orderId = id.GetHashCode();
                ViewBag.deliveryTypeName = deliveryTypeName;
                var listItem = Hyt.BLL.Web.SoOrderBo.Instance.GetOrderItemListByOrderSysNo(orderId);
                return View("_OrderShipDialog",listItem);
            }

    发货按钮控制器:

     /// <summary>
            /// 订单发货
            /// </summary>
            /// <param name="id">订单发货</param>
            /// <returns>视图</returns>
            [Privilege(PrivilegeCode.SO1001101, PrivilegeCode.OR1001982)]
            public JsonResult Ship(int orderId, string expressNo, string productList, string fstatus)
            {
                
                var result = new Result
                {
                    Status = false
                };
                if (productList == "[]")
                {
                    result.Status = false;
                    result.Message = "请勾选商品!";
                    return Json(result, JsonRequestBehavior.AllowGet);
                }
                using (var tran = new TransactionScope())
                {
                    if (fstatus == "1")
                    {
                        //全部发货
                        result = BLL.Order.SoOrderBo.Instance.Ship(orderId, expressNo);
                    }
                    else
                    {
                        //部分发货
                        result = BLL.Order.SoOrderBo.Instance.SomeShip(orderId, expressNo, productList, fstatus);
                    }
    
                    if (!result.Status)
                    {
                        return Json(result, JsonRequestBehavior.AllowGet);
                    }
                    if (result.Status)
                    {
                        //修改主订单状态
                        OrderBLL.Instance.GetIsOrderShip(orderId);
                        result.Message = "发货成功!";
                        #region 利嘉(你他购)推送订单状态
                        int type = 2;//绑数据类型:2:订单
                        string state = "7";//订单状态,7:已经发货待确认中
                        var model = BLL.Web.MKNitagoDateBindBo.Instance.Select(type, orderId);
                        if (model != null)
                        {
                            NitagaPostOrderState orderstate = new NitagaPostOrderState();
                            string sAPIResult = orderstate.OrderState(model.NitagoDateSysNo, state);
                            JsonData returnDate = JsonMapper.ToObject(sAPIResult);
                            int backcode = 0;
                            if (((System.Collections.IDictionary)returnDate).Contains("backcode"))
                            {
                                backcode = Convert.ToInt32(returnDate["backcode"].ToString());
                                if (backcode == 0)
                                {
                                    if (((System.Collections.IDictionary)returnDate).Contains("error"))
                                    {
                                        string error = (string)returnDate["error"];
                                        BLL.Log.SysLog.Instance.Error(Model.WorkflowStatus.LogStatus.系统日志来源.外部应用, "推送订单状态:" + orderId + "到你他购失败!" + error, new Exception());
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    tran.Complete();
                }
                return Json(result, JsonRequestBehavior.AllowGet);
            }


    BLL:

         /// <summary>
            /// 发货
            /// </summary>
            /// <param name="orderSysNo">订单编号</param>
            /// <param name="expressNo">快递单号</param>
            /// <returns></returns>
            public Result Ship(int orderSysNo, string expressNo)
            {
                //获取的订单详情
                var orderInfo = BLL.Web.SoOrderBo.Instance.GetEntity(orderSysNo);
                return Ship(orderSysNo, expressNo, orderInfo);
            }
    
            /// <summary>
            /// 部分发货
            /// </summary>
            /// <param name="orderSysNo">订单编号</param>
            /// <param name="expressNo">快递单号</param>
            /// <param name="productList">商品详情</param>
            /// <param name="fstatus">发货状态</param>
            /// <returns></returns>
            /// <remarks>2018-05-21 创建</remarks>
            public Result SomeShip(int orderSysNo, string expressNo, string productList, string fstatus)
            {
                //获取的商品详情
                var orderInfo = BLL.Web.SoOrderBo.Instance.GetEntity(orderSysNo);
                var orderiteminfo = orderInfo.OrderItemList;
                List<DismantlingPara> dplist = new List<DismantlingPara>();
                List<SoOrderItem> ordernewitem = new List<SoOrderItem>();
                SoOrderItem sitem = new SoOrderItem();
                dplist = JsonSerializationHelper.JSONStringToList<DismantlingPara>(productList);
                foreach (var item in dplist)
                {
                    sitem = orderiteminfo.Where(p => p.SysNo == item.sysNo).FirstOrDefault();
                    sitem.RealStockOutQuantity = item.quantity;
                    ordernewitem.Add(sitem);
                }
                orderInfo.OrderItemList = ordernewitem;
                //orderiteminfo.Clear();
                
                return SomeShip(orderSysNo, expressNo, orderInfo);
            }

    创建出库单:

    #region 创建出库单
            /// <summary>
            /// 创建出库单
            /// </summary>
            /// <param name="data">出库商品列表</param>
            /// <param name="warehouseSysNo">仓库编号</param>
            /// <param name="deliveryTypeSysNo">出库单配送方式</param>
            /// <returns>操作是否成功</returns>
            /// <remarks>2016-03-22 杨浩 创建</remarks>
            public Result CreateOutStock(IList<SoOrderItem> data, int warehouseSysNo, int? deliveryTypeSysNo)
            {
                var res = new Hyt.Model.Result<WhStockOut> { Status = true };
                var identity = string.Format("创建订单{0}的出库单", data[0].OrderSysNo);
                if (YwbUtil.Enter(identity) == false)
                {
                    res.Status = false;
                    res.Message = "其它人正在处理这个订单,请稍后重试";
                    res.StatusCode = 0;
                    return res;
                }
    
                try
                {
                    SyUser syUser = new SyUser();
                    if(BLL.Authentication.AdminAuthenticationBo.Instance.Current!=null)
                    {
                        syUser=BLL.Authentication.AdminAuthenticationBo.Instance.Current.Base;
                    }
                    var outStock = SoOrderBo.Instance.CreateOutStock(data, warehouseSysNo, syUser, deliveryTypeSysNo);
                    res.Data = outStock;
                    res.StatusCode = outStock.SysNo;
                    SysLog.Instance.Info(LogStatus.系统日志来源.后台, "创建出库单", LogStatus.系统日志目标类型.出库单, outStock.SysNo, 0);
    
                }
                catch (Exception ex)
                {
                    res.Status = false;
                    res.Message = ex.Message;
                    res.StatusCode = 0;
                }
                YwbUtil.Exit(identity);
    
                return res;
            }
    
            /// <summary>
            /// 创建出库单
            /// </summary>
            /// <param name="data">出库商品列表</param>
            /// <param name="warehouseSysNo">仓库编号</param>
            /// <param name="deliveryTypeSysNo">出库单配送方式</param>
            /// <returns>操作是否成功</returns>
            /// <remarks>2016-03-22 杨浩 创建</remarks>
            public Result SomeCreateOutStock(IList<SoOrderItem> data, int warehouseSysNo, int? deliveryTypeSysNo)
            {
                var res = new Hyt.Model.Result<WhStockOut> { Status = true };
                var identity = string.Format("创建订单{0}的出库单", data[0].OrderSysNo);
                if (YwbUtil.Enter(identity) == false)
                {
                    res.Status = false;
                    res.Message = "其它人正在处理这个订单,请稍后重试";
                    res.StatusCode = 0;
                    return res;
                }
    
                try
                {
                    SyUser syUser = new SyUser();
                    if (BLL.Authentication.AdminAuthenticationBo.Instance.Current != null)
                    {
                        syUser = BLL.Authentication.AdminAuthenticationBo.Instance.Current.Base;
                    }
                    var outStock = SoOrderBo.Instance.SomeCreateOutStock(data, warehouseSysNo, syUser, deliveryTypeSysNo);
                    res.Data = outStock;
                    res.StatusCode = outStock.SysNo;
                    SysLog.Instance.Info(LogStatus.系统日志来源.后台, "创建出库单", LogStatus.系统日志目标类型.出库单, outStock.SysNo, 0);
    
                }
                catch (Exception ex)
                {
                    res.Status = false;
                    res.Message = ex.Message;
                    res.StatusCode = 0;
                }
                YwbUtil.Exit(identity);
    
                return res;
            }
    
    
    
    
            #endregion
    View Code

    出库:

    #region  出库
            /// <summary>
            /// 单出库单出库
            /// </summary>
            /// <param name="sysNo">出库单系统编号</param>
            /// <param name="checkedStockItemSysNo">选中的出库单明细系统编号,商品数量字符串</param>
            /// <param name="deliveryTypeSysNo">配送方式系统编号</param>
            /// <param name="isThirdpartyExpress">是否为第三方快递</param>
            /// <param name="stamp">出库时的时间戳</param>
            /// <returns>返回操作状态(Result.StatusCode>=0成功,小于 0失败)</returns>
            /// <remarks>2016-03-22 杨浩 创建</remarks>
            public Result StockOut(int sysNo, string checkedStockItemSysNo, int deliveryTypeSysNo, int isThirdpartyExpress, string stamp)
            {
                var result = new Hyt.Model.Result<int> { StatusCode = -1 };
    
                if (string.IsNullOrEmpty(checkedStockItemSysNo))
                {
                    result.Message = "没有扫描任何商品, 不能出库。";
                    return result;
                }
                if (checkedStockItemSysNo.LastIndexOf(';', checkedStockItemSysNo.Length - 1) > 0)
                {
                    checkedStockItemSysNo = checkedStockItemSysNo.Remove(checkedStockItemSysNo.Length - 1, 1);
                }
                //出库单明细系统编号与商品数量集合字符串
                var stockItemSysNoAndProductNumList = checkedStockItemSysNo.Split(';');
                if (stockItemSysNoAndProductNumList.Length == 0)
                {
                    result.Message = "没有扫描任何商品, 不能出库。";
                    return result;
                }
                //检查是否所有的商品数量是否都为0或者为空
                var isItemScaned = false;
                foreach (var s in stockItemSysNoAndProductNumList)
                {
                    string productNum = s.Split(',')[1];
                    if (!string.IsNullOrEmpty(productNum) && productNum != "0")
                    {
                        isItemScaned = true;
                        break;
                    }
                }
                if (!isItemScaned)
                {
                    result.Message = "没有扫描任何商品, 不能出库。";
                    return result;
                }
    
                var master = WhWarehouseBo.Instance.Get(sysNo);
                //检查时间戳是否改变
                if (master.Stamp.ToString() != stamp)
                {
                    result.Message = "此出库单已被其他人修改,请关闭当前窗口后刷新页面!";
                    return result;
                }
                if (master.Status != (int)WarehouseStatus.出库单状态.待出库)
                {
                    result.Message = "此出库单不是待出库状态,不能出库!";
                    return result;
                }
    
                //第三方快递,订单未收收款,不允许出库
                if (isThirdpartyExpress == 1)
                {
                    var order = SoOrderBo.Instance.GetEntity(master.OrderSysNO);
                    if (order.PayStatus != OrderStatus.销售单支付状态.已支付.GetHashCode())
                    {
                        result.Message = "第三方快递订单未收款,不能出库。";
                        return result;
                    }
                }
    
                //判断库存数量 王耀发 2016-3-14 创建
                //GeneralConfig config = BLL.Config.Config.Instance.GetGeneralConfig();
                int warehouseSysNo = master.WarehouseSysNo;
                
                #region   注释
                //减库存标识:1-支付后减库存,0-出库后减库存
                //if (config.ReducedInventory == 0)
                //{
                //    bool flag = false;
                //    foreach (var Item in outData)
                //    {
                //        PdProductStock entity = IPdProductStockDao.Instance.GetEntityByWP(warehouseSysNo, Item.ProductSysNo);
                //        if (entity != null)
                //        {
                //            if (entity.StockQuantity < Item.ProductQuantity)
                //            {
                //                result.Message = Item.ProductName + "库存不够,不能出库。";
                //                flag = true;
                //                break;
                //            }
                //        }
                //        else
                //        {
                //            result.Message = Item.ProductName + "对应库存不存在,不能出库。";
                //            flag = true;
                //            break;
                //        }
                //    }
                //    if (flag)
                //    {
                //        return result;
                //    }
                //}
                #endregion
    
                foreach (var item in master.Items)
                {
                    foreach (var s in stockItemSysNoAndProductNumList)
                    {
                        if (item.SysNo == Convert.ToInt32(s.Split(',')[0])
                            && !string.IsNullOrEmpty(s.Split(',')[1])
                            && Convert.ToInt32(s.Split(',')[1]) > 0)
                        {
                            item.IsScaned = true;
                            item.ScanedQuantity =
                                Convert.ToInt32(string.IsNullOrEmpty(s.Split(',')[1]) ? "0" : s.Split(',')[1]);
                        }
                    }
                }
    
                try
                {
                    master.DeliveryTypeSysNo = deliveryTypeSysNo;
                    master.StockOutDate = DateTime.Now;
                    master.StockOutBy = 0;
                    master.LastUpdateBy = 0;
                    master.LastUpdateDate = DateTime.Now;
                    master.Status = (int)WarehouseStatus.出库单状态.待拣货;
    
                    //WhWarehouseBo.Instance.OutStock(master, CurrentUser.Base.SysNo);
                    WhWarehouseBo.Instance.OutStock(master);
    
                    //#region 出库更新库存 吴琨
                    //IList<WhStockOutItem> outData = Hyt.BLL.Warehouse.WhWarehouseBo.GetWhStockOutItemByOut(sysNo);
                    //foreach (var item in outData)
                    //{
                    //    IScProductDao.Instance.UplockingStockQuantity(item.ProductSysNo, warehouseSysNo, item.ProductQuantity);
                    //}
                    //#endregion
    
    
                    //减库存 王耀发 2016-3-11 创建
                    //减库存标识:1-支付后减库存,0-出库后减库存 更新库存数量 王耀发 2016-3-11 创建 
                    //if (config.ReducedInventory == 0)
                    //{
                    //    foreach (var Item in outData)
                    //    {
                    //        Hyt.BLL.Warehouse.PdProductStockBo.Instance.UpdateStockQuantity(warehouseSysNo, Item.ProductSysNo, Item.ProductQuantity);
                    //    }
                    //}
                    //SoOrderBo.Instance.WriteSoTransactionLog(master.TransactionSysNo, "出库单" + master.SysNo + "已出库,待拣货",
                    //                                         CurrentUser.Base.UserName);
                    //SoOrderBo.Instance.WriteSoTransactionLog(master.TransactionSysNo, "您的订单已出库,待拣货",
                    //                                         CurrentUser.Base.UserName);
                    var delivery = DeliveryTypeBo.Instance.GetDeliveryType(deliveryTypeSysNo);
                    var deliveryName = (delivery == null)
                        ? "未能找到编号为" + deliveryTypeSysNo + "的配送方式"
                        : delivery.DeliveryTypeName;
                    var logTxt = "订单生成配送方式:<span style="color:red">" + deliveryName + "</span>,待拣货打包";
                    SoOrderBo.Instance.WriteSoTransactionLog(master.TransactionSysNo, logTxt,
                        "系统");
                    result.Status = true;
                    result.Message = master.SysNo + " 出库成功。";
                    result.StatusCode = 0;
                    result.Data = master.SysNo;//保存出库单系统编号
                }
                catch (Exception ex)
                {
                    result.Message = ex.Message;
                    SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message, LogStatus.系统日志目标类型.出库单, master.SysNo, ex,
                        0);
                }
    
                return result;
            }
            #endregion
    View Code

    确认发货:

     #region 确认发货
            /// <summary>
            /// 确认发货(Ajax调用)
            /// </summary>
            ///<param name="warehouseSysNo">仓库系统编号</param>
            /// <param name="deliveryUserSysNo">配送员系统编号.</param>
            /// <param name="deliverTypeSysno">配送方式系统编号.</param>
            /// <param name="items">配送单明细 (单据类型,单据编号,快递单号)</param>
            /// <param name="isForce">是否允许超出配送信用额度配送 </param>
            /// <remarks>2016-06-27 杨浩 创建</remarks>
            /// <remarks>2016-04-6 杨云奕 修改,添加事务执行判断</remarks>
            public Hyt.Model.Result ConfrimDelivery(int warehouseSysNo, int deliveryUserSysNo, int deliverTypeSysno, string[] items, bool isForce, bool IsUserTransactionScope=true)
            {
                var result = new Hyt.Model.Result<int>();
                try
                {
                    var itemList = new List<Hyt.Model.LgDeliveryItem> { };
                    string NeedInStock = string.Empty;
                    foreach (var note in items.Select(item => item.Split(',')))
                    {
                        if (note.Length < 2)
                        {
                            result.Message = "配送单明细数据错误,不能创建配送单";
                        }
                        Hyt.Model.LgDeliveryItem item = new Hyt.Model.LgDeliveryItem
                        {
                            NoteType = int.Parse(note[0]),
                            NoteSysNo = int.Parse(note[1]),
                            ExpressNo = note.Length >= 3 ? note[2].Trim() : ""
                        };
    
                        #region 判断快递单号是否重复(2014-04-11 朱成果)
                        if (!string.IsNullOrEmpty(item.ExpressNo) && item.NoteType == (int)LogisticsStatus.配送单据类型.出库单)
                        {
                            var flg = Hyt.BLL.Logistics.LgDeliveryBo.Instance.IsExistsExpressNo(deliverTypeSysno, item.ExpressNo);
                            if (flg)
                            {
                                result.Status = false;
                                result.Message = "快递单号" + item.ExpressNo + "已经被使用,请更换快递单号";
                                return result;
                            }
                        }
                        #endregion
    
                        #region 配送单作废会生成出库单对应的入库单,再次将此入库单加入配送,需检查此入库单是否已经完成入库(2014-04-11 朱成果)
    
                        if (item.NoteType == (int)LogisticsStatus.配送单据类型.出库单)
                        {
                            var rr = Hyt.BLL.Logistics.LgDeliveryBo.Instance.CheckInStock(item.NoteSysNo);
                            if (rr.Status)
                            {
                                if (!string.IsNullOrEmpty(NeedInStock))
                                {
                                    NeedInStock += ",";
                                }
                                NeedInStock += rr.StatusCode;
                            }
                        }
    
                        #endregion
    
                        itemList.Add(item);
                    }
                    if (!string.IsNullOrEmpty(NeedInStock)) //未入库的单子
                    {
                        result.Status = false;
                        result.Message = "请将先前配送单作废,拒收,未送达生成的入库单(" + NeedInStock + ")完成入库";
                        return result;
                    }
                    var options = new TransactionOptions
                    {
                        IsolationLevel = IsolationLevel.ReadCommitted,
                        Timeout = TransactionManager.DefaultTimeout
                    };
    
                    //配送方式  
                    var delivertType = DeliveryTypeBo.Instance.GetDeliveryType(deliverTypeSysno);
    
                    int deliverySysno;
                    var deliveryMsgs = new List<Hyt.BLL.Logistics.LgDeliveryBo.DeliveryMsg>();
    
                    ///事务执行判断,当为true时表示执行事务
                    if (IsUserTransactionScope)
                    {
                        using (var tran = new TransactionScope(TransactionScopeOption.Required, options))
                        {
                            //deliverySysno = LgDeliveryBo.Instance.CreateLgDelivery(warehouseSysNo, deliveryUserSysNo,
                            //    delivertType,
                            //    CurrentUser.Base.SysNo, itemList, isForce, Request.ServerVariables["REMOTE_ADDR"]);
    
                            deliverySysno = LgDeliveryBo.Instance.NewCreateLgDelivery(warehouseSysNo, deliveryUserSysNo,
                                delivertType,
                                0, itemList, isForce, ref deliveryMsgs, "");
    
                            result.Status = true;
                            result.Data = deliverySysno;
                            result.Message = "确认发货完成";
                            tran.Complete();
                        }
                    }
                    else //当为False时表示不执行事务
                    {
                        deliverySysno = LgDeliveryBo.Instance.NewCreateLgDelivery(warehouseSysNo, deliveryUserSysNo,
                                delivertType,
                                0, itemList, isForce, ref deliveryMsgs, "");
    
                        result.Status = true;
                        result.Data = deliverySysno;
                        result.Message = "确认发货完成";
                    }
                    //2014-05-09 黄波/何永东/杨文兵 添加
                    try
                    {
                        #region 发送相关短消息
                        //发送相关消息
                        foreach (var msg in deliveryMsgs)
                        {
                            //Order.SoOrderBo.Instance.WriteSoTransactionLog(msg.StockOutTransactionSysNo,
                            //                                                      "出库单" + msg.StockOutSysNo + "已配送,待结算",
                            //                                                      msg.OperationUserName);
                            //获取订单信息
                            SoOrder SData = Hyt.BLL.Order.SoOrderBo.Instance.GetEntityNoCache(msg.OrderSysNo);
                            //不是三方快递
                            if (msg.IsThirdPartyExpress == 0)
                            {
    
                                //smsBo.发送自建物流发货通知短信(msg.MobilePhoneNum, msg.OrderSysNo.ToString(),msg.UserName, msg.UserMobilePhoneNum);
                                //new BLL.Extras.EmailBo().发送百城当日达发货邮件(msg.CustomerEmailAddress, msg.CustomerSysNo.ToString(),
                                //                                    msg.OrderSysNo.ToString(), msg.UserName,
                                //                                    msg.UserMobilePhoneNum);
                                
                                //2015-10-30 王耀发 创建 对应分销商
                                CBDsDealer Dealer = new Hyt.BLL.Distribution.DsDealerBo().GetDsDealer(SData.DealerSysNo);
                                if (Dealer == null)
                                {
                                    Dealer = new CBDsDealer();
                                }
                                string context = "尊敬的客户,您在商城下达的订单(" + SData.OrderNo.ToString() + ")已经由" + msg.DeliveryTypeName + "开始处理,单号" + msg.ExpressNo + ",您可前往" + msg.TraceUrl + "查看物流状态,谢谢!";
                                Hyt.BLL.Extras.SmsBO.Instance.DealerSendMsg(msg.MobilePhoneNum, Dealer.DealerName, context, DateTime.Now);
    
                                SData.Status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.出库待接收;
                                SData.OnlineStatus = Constant.OlineStatusType.已发货;
                                UpdateOrder(SData);
                            }
    
                            if (msg.IsThirdPartyExpress == 1)
                            {
                                //2015-10-30 王耀发 创建 对应分销商
                                CBDsDealer Dealer = new Hyt.BLL.Distribution.DsDealerBo().GetDsDealer(SData.DealerSysNo);
                                if(Dealer==null)
                                {
                                    Dealer = new CBDsDealer();
                                }
                                string context = "尊敬的客户,您在商城下达的订单(" + SData.OrderNo.ToString() + ")已经由" + msg.DeliveryTypeName + "开始处理,单号" + msg.ExpressNo + ",您可前往" + msg.TraceUrl + "查看物流状态,谢谢!";
                                Hyt.BLL.Extras.SmsBO.Instance.DealerSendMsg(msg.MobilePhoneNum, Dealer.DealerName, context, DateTime.Now);
    
                            }
    
                            #region 发送微信模板消息
    
                            GeneralConfig config = BLL.Config.Config.Instance.GetGeneralConfig();
                            if (config.IsSendWeChatTempMessage == 1)
                            {
                                SendMessage(SData.SysNo, msg.DeliveryTypeName, msg.ExpressNo);
                            }
    
                            #endregion
                        }
    
                        #endregion
    
                       
                        //回填物流信息
                        try
                        {
                            LgDeliveryBo.Instance.BackFillLogisticsInfo(deliverySysno, deliverTypeSysno);
                        }
                        catch (Exception ex)
                        {
                            Hyt.BLL.Log.SysLog.Instance.Error(LogStatus.系统日志来源.分销工具, ex.Message, ex);
                        }
    
                        //调用快递100的订阅服务
                        try
                        {
                            //LgDeliveryBo.Instance.CallKuaiDi100(itemList, warehouseSysNo, delivertType);
                        }
                        catch (Exception ex)
                        {
                            Hyt.BLL.Log.SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message, ex);
                        }
                    }
                    catch (Exception ex)
                    {
                        SysLog.Instance.Error(LogStatus.系统日志来源.分销工具, ex.Message, ex);
                    }
                }
                catch (Exception ex)
                {
                    result.Status = false;
                    result.Message = "发生错误!" + ex.Message;
                    SysLog.Instance.Error(LogStatus.系统日志来源.后台, ex.Message, ex);
                }
    
                return result;
    
            }
            #endregion
    View Code

    分配出库:

     #region 订单出库
    
    
            /// <summary>
            /// 订单分配出库(当前处理不使用事物提交,事物请包裹在外面)
            /// </summary>
            /// <param name="datas">出库商品列表:Model.Quantity 为出库数量</param>
            /// <param name="warehouseSysNo">仓库编号</param>
            /// <param name="user">操作人</param>
            /// <param name="isSendMessage">是否发送短信(true为发送)</param>
            ///  <param name="outstockdeliveryTypeSysNo">出库单配送方式 为空获取订单的配送方式</param>
            /// <returns></returns>
            /// <remarks>
            /// 2013-06-24 杨浩 创建
            /// 2013-12-19 杨浩 修改订单日志
            /// </remarks>
            public WhStockOut CreateOutStock(IList<Model.SoOrderItem> datas, int warehouseSysNo, SyUser user,bool isSendMessage,int? outstockdeliveryTypeSysNo = null)
            {
                if (datas == null || datas.Count() < 1) return null;
                if (warehouseSysNo < 1) throw new ArgumentNullException("必需选择一个仓库");
                var so = Hyt.BLL.Order.SoOrderBo.Instance.GetEntity(datas[0].OrderSysNo);
                if (
                    !(so.Status == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.待创建出库单 ||
                      so.Status == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.部分创建出库单))
                {
                    throw new Exception("当前状态下的订单不允许出库。");
                }
                var soItems = SoOrderBo.Instance.GetOrderItemsByOrderId(so.SysNo);
                var payType = PaymentTypeBo.Instance.GetEntity(so.PayTypeSysNo);
                int currectDeliveryTypeSysNo = so.DeliveryTypeSysNo;
                if (outstockdeliveryTypeSysNo.HasValue && outstockdeliveryTypeSysNo.Value > 0)
                {
                    //是否选择了出库单配送方式
                    currectDeliveryTypeSysNo = outstockdeliveryTypeSysNo.Value;
                }
                if (currectDeliveryTypeSysNo == Hyt.Model.SystemPredefined.DeliveryType.第三方快递 && so.PayStatus != Hyt.Model.WorkflowStatus.OrderStatus.销售单支付状态.已支付.GetHashCode())
                {
                    throw new Exception("第三方快递配送,必须先完成订单付款。");
                }
                WhStockOut whStockOut = new WhStockOut()
                {
                    ContactBeforeDelivery = so.ContactBeforeDelivery,
                    CreatedBy = user.SysNo,
                    CreatedDate = DateTime.Now,
                    ReceiveAddressSysNo = so.ReceiveAddressSysNo,
                    CustomerMessage = so.CustomerMessage,
                    DeliveryRemarks = so.DeliveryRemarks,
                    DeliveryTime = so.DeliveryTime,
                    DeliveryTypeSysNo = currectDeliveryTypeSysNo,
                    IsCOD = payType.PaymentType == (int)Hyt.Model.WorkflowStatus.BasicStatus.支付方式类型.到付 ? 1 : 0,
                    IsPrintedPackageCover = 0,
                    IsPrintedPickupCover = 0,
                    LastUpdateBy = user.SysNo,
                    LastUpdateDate = DateTime.Now,
                    OrderSysNO = so.SysNo,
                    Receivable =
                        payType.PaymentType == (int)Hyt.Model.WorkflowStatus.BasicStatus.支付方式类型.到付
                            ? so.CashPay
                            : 0m,
                    Remarks = so.Remarks,
                    Status = (int)Hyt.Model.WorkflowStatus.WarehouseStatus.出库单状态.待出库,
                    TransactionSysNo = so.TransactionSysNo,
                    WarehouseSysNo = warehouseSysNo,
                    //InvoiceSysNo = so.InvoiceSysNo
                };
                int otherSysNo;
                bool existNeedPaid = Hyt.BLL.Order.ShopOrderBo.Instance.GetUnPaidStockOutNo(so.SysNo, out otherSysNo);//存在需要支付的出库单
                if (so.PayStatus == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单支付状态.已支付)
                {
                    //已支付
                    whStockOut.Receivable = 0;
                }
                else if ((so.DeliveryTypeSysNo == Hyt.Model.SystemPredefined.DeliveryType.门店自提 || so.DeliveryTypeSysNo == Hyt.Model.SystemPredefined.DeliveryType.自提) && existNeedPaid)
                {
                    //门店自提已创建有收款的出库单,收款金额为0
                    //未付款 不处理,全部收款金额为订单金额
                    whStockOut.Receivable = 0;
                }
                if (so.Status == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.待创建出库单)
                {
                    whStockOut.InvoiceSysNo = so.InvoiceSysNo;//发票在第一张出库单上
                }
                var outStockItemAmount = CalculateOutStockItemAmount(so, soItems, datas);
                whStockOut.StockOutAmount = outStockItemAmount.Sum(m => m.Value);
                //note:调用保存出库单主表的方法
                whStockOut.SysNo = Hyt.DataAccess.Warehouse.IOutStockDao.Instance.InsertMain(whStockOut); //朱成果 添加
                //记录出库单操作日志 杨浩 2014-12-22 添加
                WhStockOutLogBo.Instance.WriteLog(whStockOut.SysNo, "订单分配出库,在出库单主表添加一条记录", user);
                foreach (var data in datas)
                {
                    var whStockOutItem = new WhStockOutItem()
                    {
                        CreatedBy = user.SysNo,
                        CreatedDate = DateTime.Now,
                        LastUpdateBy = user.SysNo,
                        LastUpdateDate = DateTime.Now,
                        Measurement = "",
                        OrderSysNo = so.SysNo,
                        OriginalPrice = data.OriginalPrice,
                        ProductName = data.ProductName,
                        ProductQuantity = data.Quantity,
                        //2013-11-22 吴文强 分摊后的实际销售金额
                        RealSalesAmount = outStockItemAmount[data.SysNo],
                        ProductSysNo = data.ProductSysNo,
                        Status = 1,
                        StockOutSysNo = whStockOut.SysNo,
                        TransactionSysNo = so.TransactionSysNo,
                        Weight = 0m,
                        OrderItemSysNo = data.SysNo
                    };
    
                    //调用保存出库单明细表的方法
                    Hyt.DataAccess.Warehouse.IOutStockDao.Instance.InsertItem(whStockOutItem); //朱成果 添加
                    var soItem = soItems.First(p => p.SysNo == data.SysNo);
                    //更新当前出库明细中的出库数量
                    soItem.RealStockOutQuantity += data.Quantity;
                    //出库数量到数据库
                    Hyt.DataAccess.Order.ISoOrderItemDao.Instance.UpdateOutStockQuantity(soItem.SysNo,
                                                                                         soItem.RealStockOutQuantity);
                    // 朱成果 更新出库数量
                }
                //记录出库单操作日志 缪竞华 2014-12-22 添加 
                WhStockOutLogBo.Instance.WriteLog(whStockOut.SysNo, "订单分配出库,在出库单明细表添加记录", user);
                //更新销售单主表
                so.Status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已创建出库单;
                so.OnlineStatus = Constant.OlineStatusType.待出库;
                foreach (var soItem in soItems)
                {
                    if (soItem.RealStockOutQuantity > soItem.Quantity) throw new Exception("异常:实际出库数量大于订购数量");
                    if (soItem.RealStockOutQuantity < soItem.Quantity)
                    {
                        so.Status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.部分创建出库单;
                        so.OnlineStatus = Constant.OlineStatusType.待出库;
                    }
                }
    
                //调用更新销售单主表方法
                so.DefaultWarehouseSysNo = warehouseSysNo;//修改仓库
                so.DeliveryTypeSysNo = currectDeliveryTypeSysNo;//修改配送方式
                UpdateOrder(so); //更新订单 余勇 修改为调用业务层方法 //Hyt.DataAccess.Order.ISoOrderDao.Instance.Update(so); //更新订单状态,默认出库仓库
    
                // Hyt.DataAccess.Order.ISoOrderDao.Instance.UpdateOrderStatus(so.SysNo, so.Status); //更新订单出库状态
                if (so.Status == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已创建出库单)
                {
                    //将已处理的订单在任务池删除
                    SyJobPoolManageBo.Instance.DeleteJobPool(so.SysNo, (int)SystemStatus.任务对象类型.客服订单提交出库);
                    SyJobDispatcherBo.Instance.WriteJobLog(string.Format("已创建出库单,审核任务完成,销售单编号:{0}", so.SysNo), so.SysNo, null, user.SysNo);
                }
                var warehouseName = WhWarehouseBo.Instance.GetWarehouseEntity(warehouseSysNo).WarehouseName;
                WriteSoTransactionLog(so.TransactionSysNo
                                      , string.Format(Constant.ORDER_TRANSACTIONLOG_OUTSTOCK_CREATE, warehouseName, whStockOut.SysNo)
                                      , user.UserName);
                #region 发送订单分配到仓库短信提醒
    
                //if (isSendMessage)
                //{
                //    var config = WhWarehouseConfigBo.Instance.GetEntityByWarehouseSysNo(warehouseSysNo);
                //    if (config != null && config.IsReceiveMessage == (int)Hyt.Model.WorkflowStatus.WarehouseStatus.是否接收分配出库短信.是 && !string.IsNullOrEmpty(config.ReceiveMobileNo))
                //    {
                //        Hyt.BLL.Extras.SmsBO.Instance.发生订单分配仓库提醒短信(config.ReceiveMobileNo, String.Empty, whStockOut.SysNo.ToString());
                //    }
                //}
                #endregion
    
                //Hyt.BLL.QiMen.QiMenBo.Instance.NoticeOutStock(whStockOut, user);//通知奇门
    
                return whStockOut;
            }
    View Code

    部分分配出库:

     /// <summary>
            /// 订单部分出库(当前处理不使用事物提交,事物请包裹在外面)
            /// </summary>
            /// <param name="datas">出库商品列表:Model.Quantity 为出库数量</param>
            /// <param name="warehouseSysNo">仓库编号</param>
            /// <param name="user">操作人</param>
            ///  <param name="outstockdeliveryTypeSysNo">出库单配送方式 为空获取订单的配送方式</param>
            /// <returns></returns>
            /// <remarks>
            /// 2013-06-24 杨文兵 创建
            /// 2013-06-25 朱成果 修改
            /// 2013-12-19 黄志勇 修改订单日志
            /// </remarks>
            public WhStockOut SomeCreateOutStock(IList<Model.SoOrderItem> datas, int warehouseSysNo, SyUser user, int? outstockdeliveryTypeSysNo = null)
            {
                if (datas == null || datas.Count() < 1) return null;
                if (warehouseSysNo < 1) throw new ArgumentNullException("必需选择一个仓库");
                var so = SoOrderBo.Instance.GetEntity(datas[0].OrderSysNo);
                //取订单明细
                var soItems = SoOrderBo.Instance.GetOrderItemsByOrderId(so.SysNo);
               
                //取支付方式
                var payType = PaymentTypeBo.Instance.GetEntity(so.PayTypeSysNo);
                int currectDeliveryTypeSysNo = so.DeliveryTypeSysNo;
                if (outstockdeliveryTypeSysNo.HasValue && outstockdeliveryTypeSysNo.Value > 0)
                {
                    //是否选择了出库单配送方式
                    currectDeliveryTypeSysNo = outstockdeliveryTypeSysNo.Value;
                }
                if (currectDeliveryTypeSysNo == DeliveryType.第三方快递 && so.PayStatus != OrderStatus.销售单支付状态.已支付.GetHashCode())
                {
                    throw new Exception("第三方快递配送,必须先完成订单付款。");
                }
                //出库单
                WhStockOut whStockOut = new WhStockOut()
                {
                    ContactBeforeDelivery = so.ContactBeforeDelivery,
                    CreatedBy = user.SysNo,
                    CreatedDate = DateTime.Now,
                    ReceiveAddressSysNo = so.ReceiveAddressSysNo,
                    CustomerMessage = so.CustomerMessage,
                    DeliveryRemarks = so.DeliveryRemarks,
                    DeliveryTime = so.DeliveryTime,
                    DeliveryTypeSysNo = currectDeliveryTypeSysNo,
                    IsCOD = payType.PaymentType == (int)BasicStatus.支付方式类型.到付 ? 1 : 0,
                    IsPrintedPackageCover = 0,
                    IsPrintedPickupCover = 0,
                    LastUpdateBy = user.SysNo,
                    LastUpdateDate = DateTime.Now,
                    OrderSysNO = so.SysNo,
                    Receivable =
                        payType.PaymentType == (int)BasicStatus.支付方式类型.到付
                            ? so.CashPay
                            : 0m,
                    Remarks = so.Remarks,
                    Status = (int)WarehouseStatus.出库单状态.待出库,
                    TransactionSysNo = so.TransactionSysNo,
                    WarehouseSysNo = warehouseSysNo,
    
                    //InvoiceSysNo = so.InvoiceSysNo
                };
                int otherSysNo;
                bool existNeedPaid = ShopOrderBo.Instance.GetUnPaidStockOutNo(so.SysNo, out otherSysNo);//存在需要支付的出库单
                if (so.PayStatus == (int)OrderStatus.销售单支付状态.已支付)
                {
                    //已支付
                    whStockOut.Receivable = 0;
                }
                else if ((so.DeliveryTypeSysNo == DeliveryType.门店自提 || so.DeliveryTypeSysNo == DeliveryType.自提) && existNeedPaid)
                {
                    //门店自提已创建有收款的出库单,收款金额为0
                    //未付款 自建物流不处理,全部收款金额为订单金额
                    whStockOut.Receivable = 0;
                }
                if (so.Status == (int)OrderStatus.销售单状态.待创建出库单)
                {
                    whStockOut.InvoiceSysNo = so.InvoiceSysNo;//发票在第一张出库单上
                }
    
                var outStockItemAmount = SomeCalculateOutStockItemAmount(so, datas, datas);
                whStockOut.StockOutAmount = outStockItemAmount.Sum(m => m.Value);
                //note:调用保存出库单主表的方法
                whStockOut.SysNo = IOutStockDao.Instance.InsertMain(whStockOut); //朱成果 添加
                foreach (var data in datas)
                {
                    var whStockOutItem = new WhStockOutItem()
                    {
                        CreatedBy = user.SysNo,
                        CreatedDate = DateTime.Now,
                        LastUpdateBy = user.SysNo,
                        LastUpdateDate = DateTime.Now,
                        Measurement = "",
                        OrderSysNo = so.SysNo,
                        OriginalPrice = data.OriginalPrice,
                        ProductName = data.ProductName,
                        ProductQuantity = data.RealStockOutQuantity,
                        //2013-11-22 吴文强 分摊后的实际销售金额
                        RealSalesAmount = outStockItemAmount[data.SysNo],
                        ProductSysNo = data.ProductSysNo,
                        Status = 1,
                        StockOutSysNo = whStockOut.SysNo,
                        TransactionSysNo = so.TransactionSysNo,
                        Weight = 0m,
                        OrderItemSysNo = data.SysNo,
                        PdProductSpecPricesSysNo = data.ProductSpecPricesSysNo
                    };
    
                    //调用保存出库单明细表的方法
                    whStockOutItem.SysNo = IOutStockDao.Instance.InsertItem(whStockOutItem); //朱成果 添加
                    var soItem = soItems.First(p => p.SysNo == data.SysNo);
                    //更新当前出库明细中的出库数量
                    soItem.RealStockOutQuantity += data.RealStockOutQuantity;
                    //出库数量到数据库
                    ISoOrderItemDao.Instance.UpdateOutStockQuantity(soItem.SysNo,
                                                                                         soItem.RealStockOutQuantity);
                    // 朱成果 更新出库数量
                    ///添加出库单明细出库实体中 2016-04-06 杨云奕 添加
                    whStockOut.Items = new List<WhStockOutItem>();
                    whStockOut.Items.Add(whStockOutItem);
                }
                //更新销售单主表
                so.Status = (int)OrderStatus.销售单状态.已创建出库单;
                so.OnlineStatus = Constant.OlineStatusType.待出库;
                foreach (var soItem in soItems)
                {
                    if (soItem.RealStockOutQuantity > soItem.Quantity) throw new Exception("异常:实际出库数量大于订购数量");
                    if (soItem.RealStockOutQuantity < soItem.Quantity)
                    {
                        
                    }
                    //判断所有商品是否全部发货
                    //获取订单明细列表
                    var itemList = SoOrderItemBo.Instance.GetOrderItemList(so.SysNo);
                    var order = BLL.Order.SoOrderBo.Instance.GetOrderByOrderNo(itemList[0].OrderNo);
                    var warehouseList = WhWarehouseBo.Instance.GetWhStockOutItemListT(order.SysNo);
                    if (warehouseList.Sum(p => p.ProductQuantity) < itemList.Sum(p => p.Quantity))
                    {
                        //部分发货
                        so.Status = (int)OrderStatus.销售单状态.部分创建出库单;
                        so.OnlineStatus = Constant.OlineStatusType.待出库;
                    }
                    else//全部发货
                    {
                        so.Status = (int)OrderStatus.销售单状态.已创建出库单;
                        so.OnlineStatus = Constant.OlineStatusType.待出库;
                    }
                    //var realcount = soItems.Where(s => s.Quantity == s.RealStockOutQuantity).Count();
    
    
                    //var realQuantity = soItem.RealStockOutQuantity;
                    //realQuantity += realQuantity;
                    //var quantity = soItem.Quantity;
                    //quantity += quantity;
                    //if (realQuantity == quantity)
                    //{
                    //    so.Status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已创建出库单;
                    //    so.OnlineStatus = Constant.OlineStatusType.待出库;
                    //}
                }
                
                //调用更新销售单主表方法
                so.DefaultWarehouseSysNo = warehouseSysNo;//修改仓库
                so.DeliveryTypeSysNo = currectDeliveryTypeSysNo;//修改配送方式
                UpdateOrder(so); //更新订单 余勇 修改为调用业务层方法 
                if (so.Status == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已创建出库单)
                {
                    //将已处理的订单在任务池删除
                    SyJobPoolManageBo.Instance.DeleteJobPool(so.SysNo, (int)SystemStatus.任务对象类型.客服订单提交出库);
                    SyJobDispatcherBo.Instance.WriteJobLog(string.Format("已创建出库单,审核任务完成,销售单编号:{0}", so.SysNo), so.SysNo, null, user.SysNo);
                }
                var warehouseName = WhWarehouseBo.Instance.GetWarehouseEntity(warehouseSysNo).WarehouseName;
                WriteSoTransactionLog(so.TransactionSysNo
                                      , string.Format(Constant.ORDER_TRANSACTIONLOG_OUTSTOCK_CREATE, warehouseName, whStockOut.SysNo)
                                      , user.UserName);
    
                return whStockOut;
            }
    View Code

    计算出库金额:

    /// <summary>
            /// 计算出库单实际销售金额
            /// </summary>
            /// <param name="order">订单</param>
            /// <param name="orderItems">销售单明细</param>
            /// <param name="outStockOrderItems">创建出库单的销售单明细</param>
            /// <returns>出库单明细实际销售金额</returns>
            /// <remarks>2013-11-22 吴文强 创建</remarks>
            public System.Collections.Generic.Dictionary<int, decimal> CalculateOutStockItemAmount(SoOrder order, IList<SoOrderItem> orderItems,
                                                                   IList<SoOrderItem> outStockOrderItems)
            {
                //需要分摊的商品总数(不包含赠品和销售金额为0的商品)
                var totalApportionNum = 0;
                var allStockOutQuantity = 0;
                //订单赠品价格合计
                decimal orderGiftAmount = 0;
                //订单销售明细价格合计
                decimal orderSalesAmount = 0;
    
                orderGiftAmount = orderItems.Where(t => t.ProductSalesType == (int)CustomerStatus.商品销售类型.赠品)
                                            .Sum(t => t.SalesAmount - t.DiscountAmount + t.ChangeAmount);
                orderSalesAmount = order.CashPay;// -order.GetFreight().RealFreightAmount;
                //订单金额为负数时,订单金额作为0做分摊计算。 总金额
                orderSalesAmount = orderSalesAmount < 0 ? 0 : orderSalesAmount;
    
                foreach (var orderItem in orderItems)
                {
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        totalApportionNum += orderItem.Quantity;
                    }
                }
    
                var outStockAmount = new System.Collections.Generic.Dictionary<int, decimal>();
    
                //获取当前销售单明细编号已创建分配出库的出库单明细
                var allStockOutItems =
                    WhWarehouseBo.Instance.GetStockOutItems(outStockOrderItems.Select(soi => soi.SysNo).ToArray());
    
                var newOrderGiftAmount = orderGiftAmount > orderSalesAmount - orderGiftAmount ? 0 : orderGiftAmount;
    
                //明细销售总金额-总明细总折扣金额+明细总调价金额
                var itemTotalSalesAmount = orderItems.Sum(t => t.SalesAmount - t.DiscountAmount + t.ChangeAmount) - newOrderGiftAmount;
    
                //需分摊金额(明细总销售金额-(订单现金支付金额-运费))
                var apportionAmount = itemTotalSalesAmount - (orderSalesAmount - newOrderGiftAmount);
    
                //已创建出库单数
                var stockOutItems = WhWarehouseBo.Instance.GetStockOutItems(orderItems.Select(oi => oi.SysNo).ToArray());
    
                //已出库非赠品金额合计
                decimal stockNotGiftAmount = 0;
    
                //计算已出库的商品数量(不包含赠品和销售金额为0的商品)
                foreach (var stockOutItem in stockOutItems)
                {
                    var orderItem = orderItems.First(oi => oi.SysNo == stockOutItem.OrderItemSysNo);
    
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                       && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        allStockOutQuantity += stockOutItem.ProductQuantity;
                        stockNotGiftAmount += stockOutItem.RealSalesAmount;
                    }
                }
    
                //当前非赠品金额合计
                decimal currNotGiftAmount = 0;
    
                //循环出库商品
                foreach (var outStockOrderItem in outStockOrderItems)
                {
                    decimal currItemAmount = 0;
                    var orderItem = orderItems.First(oi => oi.SysNo == outStockOrderItem.SysNo);
    
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        allStockOutQuantity += outStockOrderItem.Quantity;
                    }
    
                    //最后一个商品出库时:订单商品数量==已出库商品数
                    //出库金额=订单支付金额-所有已创建出库金额
                    if (totalApportionNum == allStockOutQuantity &&
                        (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        outStockAmount.Add(outStockOrderItem.SysNo,
                                           decimal.Round(
                                              orderSalesAmount
                                              - stockNotGiftAmount
                                              - currNotGiftAmount
                                              - newOrderGiftAmount
                                              , 2));
                        continue;
                    }
    
                    var itemSalesAmount = orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount;
    
                    //当前明细需分摊金额
                    decimal itemRealSalesAmount = 0;
                    if (itemTotalSalesAmount != 0 &&
                        (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        itemRealSalesAmount = itemTotalSalesAmount == apportionAmount
                                                  ? 0
                                                  : (itemSalesAmount -
                                                    itemSalesAmount / itemTotalSalesAmount * apportionAmount).RoundToShe(2);
                    }
                    else
                    {
                        itemRealSalesAmount = itemSalesAmount;
                    }
    
                    if (orderItem.Quantity == orderItem.RealStockOutQuantity + outStockOrderItem.RealStockOutQuantity)
                    {
                        //当前销售单已全出库时:计算剩余明细金额
                        var stockOutAmount =
                            allStockOutItems.Where(soi => soi.OrderItemSysNo == orderItem.SysNo)
                                            .Sum(soi => soi.RealSalesAmount);
                        //查询出库单当已出库金额
                        currItemAmount = itemRealSalesAmount - stockOutAmount;
                    }
                    else
                    {
                        //当前销售单已全出库时:计算部分明细金额
                        currItemAmount = (itemRealSalesAmount / orderItem.Quantity * outStockOrderItem.RealStockOutQuantity).RoundToShe(2);
                    }
    
                    outStockAmount.Add(outStockOrderItem.SysNo, currItemAmount);
    
                    if (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                    {
                        currNotGiftAmount += (currItemAmount);
                    }
                }
    
                return outStockAmount;
            }
            /// <summary>
            /// 计算出库单实际销售金额
            /// </summary>
            /// <param name="order">订单</param>
            /// <param name="orderItems">销售单明细</param>
            /// <param name="outStockOrderItems">创建出库单的销售单明细</param>
            /// <returns>出库单明细实际销售金额</returns>
            /// <remarks>2013-11-22 吴文强 创建</remarks>
            public System.Collections.Generic.Dictionary<int, decimal> SomeCalculateOutStockItemAmount(SoOrder order, IList<SoOrderItem> orderItems,
                                                                   IList<SoOrderItem> outStockOrderItems)
            {
                //需要分摊的商品总数(不包含赠品和销售金额为0的商品)
                var totalApportionNum = 0;
                var allStockOutQuantity = 0;
                //订单赠品价格合计
                decimal orderGiftAmount = 0;
                //订单销售明细价格合计
                decimal orderSalesAmount = 0;
    
                orderGiftAmount = orderItems.Where(t => t.ProductSalesType == (int)CustomerStatus.商品销售类型.赠品)
                                            .Sum(t => t.SalesAmount - t.DiscountAmount + t.ChangeAmount);
                orderSalesAmount = order.CashPay;// -order.GetFreight().RealFreightAmount;
                //订单金额为负数时,订单金额作为0做分摊计算。 总金额
                orderSalesAmount = orderSalesAmount < 0 ? 0 : orderSalesAmount;
    
                foreach (var orderItem in orderItems)
                {
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        totalApportionNum += orderItem.RealStockOutQuantity;
                    }
                }
    
                var outStockAmount = new System.Collections.Generic.Dictionary<int, decimal>();
    
                //获取当前销售单明细编号已创建分配出库的出库单明细
                var allStockOutItems =
                    WhWarehouseBo.Instance.GetStockOutItems(outStockOrderItems.Select(soi => soi.SysNo).ToArray());
    
                var newOrderGiftAmount = orderGiftAmount > orderSalesAmount - orderGiftAmount ? 0 : orderGiftAmount;
    
                //明细销售总金额-总明细总折扣金额+明细总调价金额
                var itemTotalSalesAmount = orderItems.Sum(t => t.SalesAmount - t.DiscountAmount + t.ChangeAmount) - newOrderGiftAmount;
    
                //需分摊金额(明细总销售金额-(订单现金支付金额-运费))
                var apportionAmount = itemTotalSalesAmount - (orderSalesAmount - newOrderGiftAmount);
    
                //已创建出库单数
                var stockOutItems = WhWarehouseBo.Instance.GetStockOutItems(orderItems.Select(oi => oi.SysNo).ToArray());
    
                //已出库非赠品金额合计
                decimal stockNotGiftAmount = 0;
    
                //计算已出库的商品数量(不包含赠品和销售金额为0的商品)
                foreach (var stockOutItem in stockOutItems)
                {
                    var orderItem = orderItems.First(oi => oi.SysNo == stockOutItem.OrderItemSysNo);
    
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                       && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        allStockOutQuantity += stockOutItem.ProductQuantity;
                        stockNotGiftAmount += stockOutItem.RealSalesAmount;
                    }
                }
    
                //当前非赠品金额合计
                decimal currNotGiftAmount = 0;
    
                //循环出库商品
                foreach (var outStockOrderItem in outStockOrderItems)
                {
                    decimal currItemAmount = 0;
                    var orderItem = orderItems.First(oi => oi.SysNo == outStockOrderItem.SysNo);
    
                    if ((orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        allStockOutQuantity += outStockOrderItem.Quantity;
                    }
    
                    //最后一个商品出库时:订单商品数量==已出库商品数
                    //出库金额=订单支付金额-所有已创建出库金额
                    if (totalApportionNum == allStockOutQuantity &&
                        (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        outStockAmount.Add(outStockOrderItem.SysNo,
                                           decimal.Round(
                                              orderSalesAmount
                                              - stockNotGiftAmount
                                              - currNotGiftAmount
                                              - newOrderGiftAmount
                                              , 2));
                        continue;
                    }
    
                    var itemSalesAmount = orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount;
    
                    //当前明细需分摊金额
                    decimal itemRealSalesAmount = 0;
                    if (itemTotalSalesAmount != 0 &&
                        (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                        && (orderItem.SalesAmount - orderItem.DiscountAmount + orderItem.ChangeAmount) > 0)
                    {
                        itemRealSalesAmount = itemTotalSalesAmount == apportionAmount
                                                  ? 0
                                                  : (itemSalesAmount -
                                                    itemSalesAmount / itemTotalSalesAmount * apportionAmount).RoundToShe(2);
                    }
                    else
                    {
                        itemRealSalesAmount = itemSalesAmount;
                    }
    
                    if (orderItem.Quantity == orderItem.RealStockOutQuantity + outStockOrderItem.RealStockOutQuantity)
                    {
                        //当前销售单已全出库时:计算剩余明细金额
                        var stockOutAmount =
                            allStockOutItems.Where(soi => soi.OrderItemSysNo == orderItem.SysNo)
                                            .Sum(soi => soi.RealSalesAmount);
                        //查询出库单当已出库金额
                        currItemAmount = itemRealSalesAmount - stockOutAmount;
                    }
                    else
                    {
                        //当前销售单已全出库时:计算部分明细金额
                        currItemAmount = (itemRealSalesAmount / orderItem.Quantity * outStockOrderItem.RealStockOutQuantity).RoundToShe(2);
                    }
    
                    outStockAmount.Add(outStockOrderItem.SysNo, currItemAmount);
    
                    if (orderItem.ProductSalesType != (int)CustomerStatus.商品销售类型.赠品
                        || orderGiftAmount > orderSalesAmount - orderGiftAmount)
                    {
                        currNotGiftAmount += (currItemAmount);
                    }
                }
    
                return outStockAmount;
            }
    View Code

    出库单作废,签收更新订单状态:

    #region 出库单作废,签收更新订单状态
            /// <summary>
            /// 出库单作废更新订单状态 (需要订一个合适的接口名字)
            /// </summary>
            /// <param name="whStockOutSysNo">出库单SysNo</param>
            /// <param name="user">操作人</param>
            /// <param name="reason">作废原因</param>
            ///<remarks>2013-06-28 杨文兵 创建</remarks> 
            ///<remarks>2013-06-28 朱成果 修改</remarks>
            ///<remarks>2013-07-03 何方 修改方法名</remarks>
            public void UpdateSoStatusForSotckOutCancel(int whStockOutSysNo, SyUser user, string reason = null)
            {
                //1.获取出库单主表 和明细表
                var whStockOutEntity = Hyt.DataAccess.Warehouse.IOutStockDao.Instance.GetModel(whStockOutSysNo);
                if (whStockOutEntity == null || whStockOutEntity.Items == null)
                {
                    throw new ArgumentNullException("出库单或者出库单明细为空");
                }
                if (whStockOutEntity.Status != (int)Hyt.Model.WorkflowStatus.WarehouseStatus.出库单状态.作废)
                {
                    throw new Exception("出库单没有完成作废!");
                }
                //销售单明细
                var orderItems = Hyt.DataAccess.Order.ISoOrderItemDao.Instance.GetOrderItemsByOrderSysNo(whStockOutEntity.OrderSysNO);
    
                string transactionSysNo = string.Empty;
                foreach (WhStockOutItem item in whStockOutEntity.Items)
                {
    
                    // var oItem = orderItems.FirstOrDefault(p => p.ProductSysNo == item.ProductSysNo);
                    var oItem = orderItems.FirstOrDefault(p => p.SysNo == item.OrderItemSysNo);
                    if (oItem == null)
                    {
                        throw new Exception("销售单明细数据有误!");
                    }
                    if (oItem.RealStockOutQuantity < item.ProductQuantity)
                    {
                        throw new Exception("出库单商品数量大于实际出库数量!");
                    }
    
                    transactionSysNo = oItem.TransactionSysNo;
                    oItem.RealStockOutQuantity = oItem.RealStockOutQuantity - item.ProductQuantity;
                    Hyt.DataAccess.Order.ISoOrderItemDao.Instance.UpdateOutStockQuantity(oItem.SysNo, oItem.RealStockOutQuantity);
                }
                //4.更新销售单主表状态 为 待出库 或者部分出库
                int status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.待创建出库单;
                foreach (var p in orderItems)
                {
                    if (p.RealStockOutQuantity > 0)
                    {
                        status = (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.部分创建出库单;
                        break;
                    }
                }
                var order = SoOrderBo.Instance.GetEntity(whStockOutEntity.OrderSysNO);
                order.Status = status;
                //order.DefaultWarehouseSysNo = 0;//缺货订单
                //if (!string.IsNullOrEmpty(reason))
                //{
                //    order.InternalRemarks = reason;//缺货原因对内备注
                //}
                UpdateOrder(order); //更新订单 余勇 修改为调用业务层方法 Hyt.DataAccess.Order.ISoOrderDao.Instance.Update(order);//更新订单信息
                if (user != null)
                {
                    WriteSoTransactionLog(transactionSysNo
                        , string.Format(Constant.ORDER_OUTSTOCK_CANCEL, whStockOutSysNo, string.IsNullOrEmpty(reason) ? string.Empty : reason)
                                        , user.UserName);
                }
    
            }
    
            /// <summary>
            /// 出库单签收时候更新订单状态
            /// </summary>
            /// <param name="entity">出库单实体</param>
            /// <param name="user">操作人</param>
            /// <remarks>2013-06-28 朱成果 修改</remarks>
            /// <remarks>2014-01-17 黄志勇 更新新增会员明细</remarks>
            public void UpdateSoStatusForSotckOutSign(WhStockOut entity, SyUser user)
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("出库单为空");
                }
                if (entity.Status != (int)Hyt.Model.WorkflowStatus.WarehouseStatus.出库单状态.已签收)
                {
                    throw new Exception("出库单未完成签收");
                }
                if (user != null)
                {
                    var order = GetEntity(entity.OrderSysNO);//获取订单详情
                    //2015-10-08 王耀发禁用
                    //if (order.DeliveryTypeSysNo != Hyt.Model.SystemPredefined.DeliveryType.第三方快递)
                    //{
                    //    WriteSoTransactionLog(entity.TransactionSysNo
                    //                       , string.Format(Constant.ORDER_OUTSTOCK_SIGN, entity.SysNo)
                    //                       , user.UserName);
                    //}
                    if (Hyt.DataAccess.Order.ISoOrderDao.Instance.CheckedOrderFinish(entity.OrderSysNO))//满足完结状态
                    {
    
                        #region 扣除分销商预存款 2013-09-13 朱成果
                        if (order.OrderSource == (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单来源.分销商升舱)
                        {
                            Hyt.BLL.MallSeller.DsOrderBo.Instance.CompleteOrder(order.SysNo, order.CashPay > 0);
                        }
                        #endregion
    
                        //所有第三方快递订单前台状态显示为已发货
                        UpdateOnlineStatusByOrderID(entity.OrderSysNO,
                            order.DeliveryTypeSysNo == Hyt.Model.SystemPredefined.DeliveryType.第三方快递
                                ? Constant.OlineStatusType.已发货
                                : Constant.OlineStatusType.已完成);   //更新订单前台显示状态 余勇修改为调用业务层方法
                        UpdateOrderStatus(entity.OrderSysNO, (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已完成);  //更新订单状态 余勇修改为调用业务层方法
                        //Hyt.DataAccess.Order.ISoOrderDao.Instance.UpdateOrderStatus(entity.OrderSysNO, (int)Hyt.Model.WorkflowStatus.OrderStatus.销售单状态.已完成); //更新订单完结状态
    
                        //送积分 2015-11-2 王耀发 注释 改为收款送积分
                        //Hyt.BLL.LevelPoint.PointBo.Instance.OrderIncreasePoint(order.CustomerSysNo, order.SysNo, (int)order.CashPay, order.TransactionSysNo);//增加积分
    
                        WriteSoTransactionLog(entity.TransactionSysNo
                                       , string.Format(Constant.ORDER_FINISH, entity.OrderSysNO)
                                       , user.UserName);
                    }
                    LgSettlementBo.Instance.WriteShopNewCustomerDetail(order.CustomerSysNo, entity.StockOutAmount);
                }
            }
            #endregion
    View Code

    更新订单前台状态:

    #region 更新订单前台显示状态
    
            //public SoOrder UpdateOrderOnlineStatus(SoOrder order, OrderStatus.销售单状态 OrderStatus)
            //{
            //    order.OnlineStatus=""
            //    return order;
            //}
            /// <summary>
            /// 根据订单号更新订单前台显示状态
            /// </summary>
            /// <param name="orderID">订单号</param>
            ///  <param name="onlineStatus">前台显示状态</param>
            /// <remarks>2013-07-04 朱成果  创建</remarks> 
            public void UpdateOnlineStatusByOrderID(int orderID, string onlineStatus)
            {
                Hyt.DataAccess.Order.ISoOrderDao.Instance.UpdateOnlineStatusByOrderID(orderID, onlineStatus);
                var cacheKey = string.Format("CACHE_SOORDER_{0}", orderID);
                Hyt.Infrastructure.Memory.MemoryProvider.Default.Remove(cacheKey);
            }
    
            /// <summary>
            /// 根据事物编号更新订单前台显示状态
            /// </summary>
            /// <param name="transactionSysNo">事物编号</param>
            ///  <param name="onlineStatus">前台显示状态</param>
            /// <remarks>2013-07-04 朱成果  创建</remarks> 
            public void UpdateOnlineStatusByTransactionSysNo(string transactionSysNo, string onlineStatus)
            {
                Hyt.DataAccess.Order.ISoOrderDao.Instance.UpdateOnlineStatusByTransactionSysNo(transactionSysNo, onlineStatus);
    
                var sysno = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(transactionSysNo, "T0*", ""));
                var cacheKey = string.Format("CACHE_SOORDER_{0}", sysno);
                Hyt.Infrastructure.Memory.MemoryProvider.Default.Remove(cacheKey);
            }
            #endregion
    View Code

    更新订单价格信息,发票总额:

    #region 更新订单价格信息,发票总额
            /// <summary>
            /// 更新订单价格信息,返回优惠及打折后的金额
            /// </summary>
            /// <param name="orderId">订单编号</param>
            /// <param name="isUpdateInvoice">是否更新发票金额</param>
            /// <returns>订单.CashPay</returns>
            /// <remarks>2013-06-24 朱成果 创建</remarks>
            public decimal SynchronousOrderAmount(int orderId, bool isUpdateInvoice = false)
            {
                decimal money = Hyt.DataAccess.Order.ISoOrderItemDao.Instance.SynchronousOrderAmount(orderId);
                //更新发票信息
                if (isUpdateInvoice)
                {
                    var fn = Hyt.DataAccess.Order.IFnInvoiceDao.Instance.GetFnInvoiceByOrderID(orderId);
                    if (fn != null)
                    {
                        fn.InvoiceAmount = money;
                        fn.LastUpdateDate = DateTime.Now;
                        //Hyt.DataAccess.Order.IFnInvoiceDao.Instance.UpdateEntity(fn);
                        Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderInvoice(fn); //更新发票 余勇 修改 改为调用业务层方法
                    }
                }
                return money;
            }
            #endregion
    View Code

    创建销售单相关数据:

     /// <summary>
            /// 创建销售单
            /// 影响数据表:"收货(常用)地址","订单收货地址表","销售单","销售单明细","发票","销售单优惠券"
            ///             ,"惠源币日志","客户"的"惠源币","收款单"
            /// 支付状态:未支付(10);销售单状态:待审核(10);前台显示状态:待审核(到付销售单),待支付(预付销售单)
            /// </summary>
            /// <param name="orderCreatorSysNo">下单人编号</param>
            /// <param name="customerSysNo">会员编号</param>
            /// <param name="receiveAddress">订单收货地址</param>
            /// <param name="defaultWarehouseSysNo">默认仓库编号</param>
            /// <param name="deliveryTypeSysNo">配送方式编号</param>
            /// <param name="payTypeSysNo">支付方式编号</param>
            /// <param name="shoppingCart">购物车对象</param>
            /// <param name="experienceCoin">使用惠源币数量</param>
            /// <param name="invoice">发票</param>
            /// <param name="orderSource">下单来源</param>
            /// <param name="orderSourceSysNo">下单来源编号</param>
            /// <param name="salesType">销售方式</param>
            /// <param name="salesSysNo">销售方式编号</param>
            /// <param name="isHiddenToCustomer">此销售单对用户是否隐藏</param>
            /// <param name="customerMessage">客户留言</param>
            /// <param name="internalRemarks">对内备注</param>
            /// <param name="deliveryRemarks">配送备注</param>
            /// <param name="deliveryTime">配送时间段</param>
            /// <param name="contactBeforeDelivery">配送前是否联系</param>
            /// <param name="remarks">备注</param>
            /// <param name="changePriceItem">调价项 Key=购物车编号 value=调价值</param>
            /// <returns>订单对象</returns>
            /// <remarks>2013-09-09 吴文强 创建方法</remarks>
            /// <remarks>2013-09-23 黄志勇 修改</remarks>
            public SoOrder CreateOrderFromOuter(int orderCreatorSysNo, int customerSysNo,
                                       SoReceiveAddress receiveAddress,
                                       int? defaultWarehouseSysNo, int deliveryTypeSysNo, int payTypeSysNo,
                                       List<SoOrderItem> orderItemList, int experienceCoin, FnInvoice invoice,
                                       OrderStatus.销售单来源 orderSource, int? orderSourceSysNo,
                                       OrderStatus.销售方式 salesType, int? salesSysNo,
                                       OrderStatus.销售单对用户隐藏 isHiddenToCustomer, string customerMessage,
                                       string internalRemarks, string deliveryRemarks, string deliveryTime,
                                       OrderStatus.配送前是否联系 contactBeforeDelivery,
                                       string remarks, System.Collections.Generic.Dictionary<int, decimal> changePriceItem = null)
            {                          //,decimal FreightAmount
    
                var customer = CrCustomerBo.Instance.GetModel(customerSysNo);
    
    
                //1.判断配送方式是否支持支付方式
                if (OrderStatus.销售单来源.门店下单 != orderSource)//门店下单转快递不能通过,排除掉
                {
                    if (BsDeliveryPaymentBo.Instance.GetBsDeliveryPaymentCount(payTypeSysNo, deliveryTypeSysNo) == 0)
                        throw new ArgumentException("配送方式和支付方式不匹配");
                }
               
                var currentTime = DateTime.Now;
                //订单主表基本信息
                var so = new SoOrder();
            
                so.ContactBeforeDelivery = (int)contactBeforeDelivery;
                so.CustomerSysNo = customerSysNo;
                so.LevelSysNo = customer.LevelSysNo;
                so.DeliveryTypeSysNo = deliveryTypeSysNo;
                so.PayTypeSysNo = payTypeSysNo;
                so.DeliveryRemarks = deliveryRemarks;
                so.DeliveryTime = deliveryTime;
                so.CustomerMessage = customerMessage;
                so.InternalRemarks = internalRemarks;
                so.CreateDate = currentTime;
                so.LastUpdateBy = orderCreatorSysNo;
                so.LastUpdateDate = currentTime;
                so.OrderCreatorSysNo = orderCreatorSysNo;
                so.OrderSource = (int)orderSource;
                so.IsHiddenToCustomer = (int)isHiddenToCustomer;
                if (orderSourceSysNo.HasValue) so.OrderSourceSysNo = orderSourceSysNo.Value;
                so.PayStatus = (int)OrderStatus.销售单支付状态.未支付;  //支付方式需要处理
                so.SalesType = (int)salesType;
                if (salesSysNo.HasValue) so.SalesSysNo = salesSysNo.Value;
                if (OrderStatus.销售单来源.门店下单 == orderSource && deliveryTypeSysNo != (int)Hyt.Model.SystemPredefined.DeliveryType.第三方快递)//排除门店下单转快递
                {
                    so.Status = (int)OrderStatus.销售单状态.待创建出库单;
                    so.AuditorSysNo = orderCreatorSysNo;
                    so.AuditorDate = DateTime.Now;
    
                }
                else
                    so.Status = (int)OrderStatus.销售单状态.待审核;
                so.SendStatus = (int)OrderStatus.销售单推送状态.未推送;
                var payType = PaymentTypeBo.Instance.GetPaymentTypeFromMemory(payTypeSysNo);
                so.OnlineStatus = payType.PaymentType == (int)BasicStatus.支付方式类型.到付 ? Constant.OlineStatusType.待审核 : Constant.OlineStatusType.待支付;
                //默认仓库
                if (defaultWarehouseSysNo == null || defaultWarehouseSysNo == default(int))
                {
                    if (receiveAddress != null)
                    {
                        var warehouse = Hyt.BLL.Warehouse.WhWarehouseBo.Instance.GetWhWareHouse(receiveAddress.AreaSysNo, null, so.DeliveryTypeSysNo, WarehouseStatus.仓库状态.启用).FirstOrDefault();
                        so.DefaultWarehouseSysNo = warehouse == null ? 0 : warehouse.SysNo;
                    }
                }
                else
                {
                    so.DefaultWarehouseSysNo = (int)defaultWarehouseSysNo;
                }
                //保存发票信息
                if (invoice != null)
                {
                    IFnInvoiceDao.Instance.InsertEntity(invoice);
                    so.InvoiceSysNo = invoice.SysNo;
                }
                //保存收货地址 非门店下单的订单收货地址不允许为空
                if (orderSource != OrderStatus.销售单来源.门店下单 && receiveAddress == null)
                {
                    throw new Exception("收货地址不能为空!");
                }
                ISoReceiveAddressDao.Instance.InsertEntity(receiveAddress);
                so.ReceiveAddressSysNo = receiveAddress.SysNo;
    
                //保存订单
                ISoOrderDao.Instance.InsertEntity(so);
                so = SoOrderBo.Instance.GetEntity(so.SysNo);
                //调用获取销售单明细数据接口,并保存明细数据
                //List<SoOrderItem> orderItemList = ShoppingCartToOrderItem(customerSysNo, so.SysNo, so.TransactionSysNo, shoppingCart, changePriceItem);
                foreach (var orderItem in orderItemList)
                {
                    so.ProductAmount+=orderItem.SalesAmount;
                    ISoOrderItemDao.Instance.Insert(orderItem);
                    if (OrderStatus.销售单来源.门店下单 == orderSource && deliveryTypeSysNo != (int)Hyt.Model.SystemPredefined.DeliveryType.第三方快递)//排除门店下单转快递
                    {
                        Hyt.BLL.Web.PdProductBo.Instance.UpdateProductSales(orderItem.ProductSysNo, orderItem.Quantity);//更新销量
                    }
                }
                //更新销售单主表金额相关字段
                //so.ProductAmount = shoppingCart.ProductAmount;
                so.ProductDiscountAmount = 0;
                so.ProductChangeAmount = 0;//调价金额合计
                so.FreightDiscountAmount = 0;
                so.FreightChangeAmount = 0;
                so.OrderAmount = so.ProductAmount;
                so.FreightAmount =0;
                so.TaxFee =0;
                so.OrderDiscountAmount = 0;
                so.CouponAmount = 0;
                so.CoinPay = 0;
                so.CashPay = so.OrderAmount - so.CoinPay;
                if (so.CashPay < 0)
                {
                    throw new Exception("支付金额不能小于零");
                }
                UpdateOrder(so); //更新订单 余勇 修改为调用业务层方法 ISoOrderDao.Instance.Update(so);
    
                if (invoice != null)//记录发票事物编号
                {
                    invoice.InvoiceAmount = so.CashPay;
                    invoice.TransactionSysNo = so.TransactionSysNo;
                    //Hyt.DataAccess.Order.IFnInvoiceDao.Instance.UpdateEntity(invoice);
                    Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderInvoice(invoice); //更新发票 余勇 修改 改为调用业务层方法
                }
    
                ////使用了优惠券
                //if (string.IsNullOrEmpty(shoppingCart.CouponCode) == false)
                //{
                //    var coupon = Hyt.BLL.Promotion.PromotionBo.Instance.GetCoupon(shoppingCart.CouponCode);
                //    if (coupon != null)
                //    {
                //        ISoOrderDao.Instance.InsertSoCoupon(new SoCoupon()
                //        {
                //            CouponSysNo = coupon.SysNo,
                //            OrderSysNo = so.SysNo
                //        });
                //    }
                //}
    
             
    
                //创建收款单
                Finance.FnReceiptVoucherBo.Instance.CreateReceiptVoucherByOrder(so);//创建订单收款单
    
                //插入订单池
                if (so.OrderSource != (int)OrderStatus.销售单来源.业务员补单 && so.OrderSource != (int)(int)OrderStatus.销售单来源.门店下单)//业务员补单不进行任务分配
                {
                    int assignTo = 0;//指定下一个订单操作人
                    if (so.OrderSource == (int)OrderStatus.销售单来源.客服下单) assignTo = orderCreatorSysNo;//客服下单 默认分配给自己
                    if (assignTo > 0)//已经指定了分配人
                    {
                        SyJobPoolPublishBo.Instance.OrderAuditBySysNo(so.SysNo, assignTo);
                        SyJobDispatcherBo.Instance.WriteJobLog(string.Format("{0}创建订单并给自己分配订单审核任务,销售单编号:{1}", SyUserBo.Instance.GetUserName(orderCreatorSysNo),
                           so.SysNo), so.SysNo, null, orderCreatorSysNo);
                    }
                    else//未指定,系统根据规则自动分配
                    {
                        //写订单池记录
                        SyJobPoolPublishBo.Instance.OrderAuditBySysNo(so.SysNo);
                        SyJobDispatcherBo.Instance.WriteJobLog(string.Format("{0}创建订单并生成订单审核任务,销售单编号:{1}", SyUserBo.Instance.GetUserName(orderCreatorSysNo),
                          so.SysNo), so.SysNo, null, orderCreatorSysNo);
    
                    }
    
                }
                //门店下单转快递 ,加入任务池
                else if (so.OrderSource == (int)OrderStatus.销售单来源.门店下单 && so.DeliveryTypeSysNo == (int)DeliveryType.第三方快递)
                {
                    SyJobPoolPublishBo.Instance.OrderAuditBySysNo(so.SysNo);
                    SyJobDispatcherBo.Instance.WriteJobLog(string.Format("{0}门店下单转快递生成订单审核任务,销售单编号:{1}", SyUserBo.Instance.GetUserName(orderCreatorSysNo),
                         so.SysNo), so.SysNo, null, orderCreatorSysNo);
                }
                var isSysUser = so.OrderSource == (int)OrderStatus.销售单来源.门店下单 ||
                                so.OrderSource == (int)OrderStatus.销售单来源.客服下单 ||
                                so.OrderSource == (int)OrderStatus.销售单来源.业务员下单 ||
                                so.OrderSource == (int)OrderStatus.销售单来源.业务员补单 ||
                                so.OrderSource == (int)OrderStatus.销售单来源.分销商升舱;
                if (isSysUser && orderCreatorSysNo > 0)//系统用户创建
                {
                    var userName = SyUserBo.Instance.GetUserName(orderCreatorSysNo);
                    WriteSoTransactionLog(so.TransactionSysNo
                                   , string.Format(Constant.ORDER_TRANSACTIONLOG_CREATE, so.SysNo)
                                   , userName);
                }
                else//会员创建
                {
                    WriteSoTransactionLog(so.TransactionSysNo
                                    , string.Format(Constant.ORDER_TRANSACTIONLOG_CREATE, so.SysNo)
                                    , "会员:" + so.CustomerSysNo);
                }
    
                //更新促销使用信息
                //UpdateUsedPromtionInfo(orderItemList, shoppingCart);
    
                //0.检查参数传入是否正确
    
                //1.根据receiveAddress创建"订单收货地址表"
    
                //2.创建"销售单"
    
                //3.创建"销售单明细"
    
                //4.创建"发票"
    
                //5.创建"销售单优惠券"
    
                //6.创建"惠源币日志"
                //扣减"客户"中的"惠源币"
    
                //7.创建"收款单"
                return so;
            }
    View Code

    获取商品毛重:

    public decimal TotalOrderProductWeight(int orderSysNo)
            {
               return ISoOrderDao.Instance.TotalOrderProductWeight(orderSysNo);
            }
    View Code

    获取物流编号和物流编码:

    /// <summary>
            /// 获取物流单号及物流编码
            /// </summary>
            /// <param name="ordersysno"></param>
            /// <returns></returns>
            public Hyt.Model.Common.LgExpressModel GetDeliveryCodeData(int ordersysno)
            {
                return ISoOrderDao.Instance.GetDeliveryCodeData(ordersysno);
            }
    
            public List<SoOrder> GetAllOrderBySysNos(string SysNos)
            {
                return ISoOrderDao.Instance.GetAllOrderBySysNos(SysNos);
            }
    View Code

    查询销售单表:

    /// <summary>
            /// 查询销售单表
            /// </summary>
            /// <param name="sysNo"></param>
            /// <returns></returns>
            public  SoOrder GetModel(int sysNo)
            {
                return ISoOrderDao.Instance.GetModel(sysNo);
            }
    View Code

    是否全部发货:

    /// <summary>
            /// 是否全部发货
            /// </summary>
            /// <param name="orderSysno">订单系统编号</param>
            /// <returns></returns>
            /// <remarks>2017-08-24 杨浩 创建</remarks>
            public bool IsAllShip(int orderSysno)
            {
                return ISoOrderDao.Instance.IsAllShip(orderSysno);
            }
    View Code

    创建付款单:

    /// <summary>
            /// 创建付款单
            /// </summary>
            /// <param name="models"></param>
            /// <returns></returns>
            public  int AddFnPaymentVoucher(FnPaymentVoucher models)
            {
                return ISoOrderDao.Instance.AddFnPaymentVoucher(models);
            }
    View Code

    创建付款单明细:

    /// <summary>
            /// 创建付款明细单
            /// </summary>
            /// <param name="models"></param>
            /// <returns></returns>
            public  int AddFnPaymentVoucherItem(FnPaymentVoucherItem models)
            {
                return ISoOrderDao.Instance.AddFnPaymentVoucherItem(models);
            }
    View Code

    更新订单状态:

    /// <summary>
            /// 更新订单为已完成
            /// </summary>
            /// <returns></returns>
            public bool UpSoOrderStaus(int SysNo)
            {
                return ISoOrderDao.Instance.UpSoOrderStaus(SysNo);
            }
    View Code

    获取所有不存在主订单的销售订单:

    /// <summary>
            /// 获取所有不存在主订单的销售订单
            /// </summary>
            /// <returns></returns>
            public List<SoOrder> GetOrder()
            {
                return ISoOrderDao.Instance.GetOrder();
            }
    
            public  List<SoOrder> GetOrderList(int id)
            {
                return ISoOrderDao.Instance.GetOrderList(id);
            }
    View Code

    更新关联主订单:

     public  bool UpSoOrderMainItem(int SysNo, int SysNoMain)
            {
                return ISoOrderDao.Instance.UpSoOrderMainItem(SysNo, SysNoMain);
            }
    View Code
    奋斗
  • 相关阅读:
    dedecms自定义表单提交获取时间跟ip地址
    JQuery购物车多物品数量的加减+总价计算
    jquery手机触屏滑动拼音字母城市选择器代码
    js实现图片上传实时显示
    js实现发送验证码倒计时效果
    JS 仿支付宝input文本输入框放大组件
    js实现倒计时效果
    jquery统计输入文字的个数并对其进行判断
    【Linux】Linux系统安全设置
    java泛型(generics)
  • 原文地址:https://www.cnblogs.com/aimerh/p/9176417.html
Copyright © 2020-2023  润新知