dengjunjie
2025-10-24 8b00a760cb23067c3ea46a2fd905ae9ff1a713a2
н¨Îļþ¼Ð/WIDESEA_WMSServer/WIDESEA_SquareCabinServices/CabinOrderServices.cs
@@ -1,5 +1,6 @@
using HslCommunication;
using MailKit.Search;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using System;
@@ -7,12 +8,21 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Common;
using WIDESEA_Common.LocationEnum;
using WIDESEA_Common.OrderEnum;
using WIDESEA_Common.StockEnum;
using WIDESEA_Common.TaskEnum;
using WIDESEA_Common.WareHouseEnum;
using WIDESEA_Core;
using WIDESEA_Core.BaseRepository;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Helper;
using WIDESEA_DTO.SquareCabin;
using WIDESEA_IBasicService;
using WIDESEA_ISquareCabinServices;
using WIDESEA_IWMsInfoServices;
using WIDESEA_Model.Models;
using static System.Net.WebRequestMethods;
@@ -24,113 +34,264 @@
{
    public class CabinOrderServices : ServiceBase<Dt_CabinOrder, IRepository<Dt_CabinOrder>>, ICabinOrderServices
    {
        static string SearchDate = "";
        private readonly IBasicService _basicService;
        private readonly IMedicineGoodsServices _medicineGoodsServices;
        private readonly IUnitOfWorkManage _unitOfWorkManage;
        private readonly IInventory_BatchServices _inventory_BatchServices;
        private readonly IInventoryInfoService _inventoryInfoService;
        private readonly ICabinOrderDetailServices _cabinOrderDetailServices;
        private readonly ISupplyTaskService _supplyTaskService;
        private readonly ISupplyTaskHtyService _supplyTaskHtyService;
        public IRepository<Dt_CabinOrder> Repository => BaseDal;
        public CabinOrderServices(IRepository<Dt_CabinOrder> BaseDal) : base(BaseDal)
        public CabinOrderServices(IRepository<Dt_CabinOrder> BaseDal, IBasicService basicService, IMedicineGoodsServices medicineGoodsServices, IUnitOfWorkManage unitOfWorkManage, IInventory_BatchServices inventory_BatchServices, IInventoryInfoService inventoryInfoService, ICabinOrderDetailServices cabinOrderDetailServices, ICabinOrderHtyServices cabinOrderHtyServices, ICabinOrderDetailHtyServices cabinOrderDetailHtyServices, ISupplyTaskService supplyTaskService, ISupplyTaskHtyService supplyTaskHtyService) : base(BaseDal)
        {
            _basicService = basicService;
            _medicineGoodsServices = medicineGoodsServices;
            _unitOfWorkManage = unitOfWorkManage;
            _inventory_BatchServices = inventory_BatchServices;
            _inventoryInfoService = inventoryInfoService;
            _cabinOrderDetailServices = cabinOrderDetailServices;
            _supplyTaskService = supplyTaskService;
            _supplyTaskHtyService = supplyTaskHtyService;
        }
        /// <summary>
        /// pda查询出库单信息
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent GetCabinOrders(SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                int pageNo = saveModel.MainData["pageNo"].ObjToInt();
                string warehouseCode = saveModel.MainData["warehouseId"].ToString();
                string orderNo = saveModel.MainData["orderNo"].ToString();
                List<Dt_CabinOrder> dt_ReceiveOrders = new List<Dt_CabinOrder>();
                if (string.IsNullOrEmpty(orderNo))
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_CabinOrder>().Where(x => (x.OdrderStatus == "新建" || x.OdrderStatus == "开始") && x.Warehouse_no == warehouseCode).Includes(x => x.Details).OrderByDescending(x => x.CreateDate).ToPageList(pageNo, 5);
                }
                else
                {
                    dt_ReceiveOrders = Db.Queryable<Dt_CabinOrder>().Where(x => (x.Order_no.Contains(orderNo) || x.Supplier_no.Contains(orderNo)) && (x.OdrderStatus == "新建" || x.OdrderStatus == "开始") && x.Warehouse_no == warehouseCode).OrderByDescending(x => x.CreateDate).Includes(x => x.Details).ToPageList(pageNo, 5);
                }
                content.OK(data: dt_ReceiveOrders);
            }
            catch (Exception)
            {
                throw;
            }
            return content;
        }
        /// <summary>
        /// pda查看入库详情表
        /// </summary>
        /// <param name="pageNo"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public WebResponseContent GetCabinOrderDetail(int pageNo, string orderNo)
        {
            WebResponseContent content = new WebResponseContent();
            Dt_CabinOrder cabinOrder = Db.Queryable<Dt_CabinOrder>().Includes(x => x.Details).First(x => x.Order_no == orderNo);
            List<Dt_CabinOrderDetail> cabinOrderDetails = cabinOrder.Details.Where(x => x.Status == 2 && x.OrderDetailStatus != "已完成").ToList();
            content.OK(data: cabinOrderDetails);
            return content;
        }
        /// <summary>
        /// Pad入库完成
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public WebResponseContent FeedbackIn([FromBody] SaveModel saveModel)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                var LocationCode = saveModel.MainData["LocationCode"].ToString();
                var orderNo = saveModel.MainData["orderNo"].ToString();
                var batchNo = saveModel.MainData["batchNo"].ToString();
                var materielCode = saveModel.MainData["materielCode"].ToString();
                var Inqty = saveModel.MainData["Inqty"].ObjToInt();
                var warehouseCode = saveModel.MainData["warehouseCode"].ToString();
                Dt_CabinOrder cabinOrder = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == orderNo && x.Warehouse_no == warehouseCode).Includes(x => x.Details).First();
                if (cabinOrder == null || cabinOrder.OdrderStatus == "已完成")
                    return WebResponseContent.Instance.Error($"入库单已完成");
                Dt_CabinOrderDetail cabinOrderDetail = cabinOrder.Details.Where(x => x.Goods_no == materielCode && x.Batch_num == batchNo && x.Status == 2).First();
                if (cabinOrderDetail == null || cabinOrderDetail.OrderDetailStatus == "已完成")
                    return WebResponseContent.Instance.Error($"入库单明细已完成");
                Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == cabinOrderDetail.Goods_no);
                if (materielInfo == null) return WebResponseContent.Instance.Error($"请维护物料编号【{cabinOrderDetail.Goods_no}】的物料信息");
                cabinOrderDetail.Order_Inqty += Inqty;
                if (cabinOrderDetail.Order_Inqty > cabinOrderDetail.Order_qty)
                    return WebResponseContent.Instance.Error($"入库数量不可超出单据数量");
                #region å¤„理入库单,货位,库存,库存批次信息
                _unitOfWorkManage.BeginTran();
                #region å…¥åº“单
                cabinOrder.OdrderStatus = "开始";
                cabinOrderDetail.OrderDetailStatus = "开始";
                if (cabinOrderDetail.Order_Inqty == cabinOrderDetail.Order_qty)
                {
                    cabinOrderDetail.OrderDetailStatus = "已完成";
                }
                _cabinOrderDetailServices.Repository.UpdateData(cabinOrderDetail);
                var cabinOrder1 = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == cabinOrder.Order_no && x.Warehouse_no == warehouseCode).Includes(x => x.Details).First();
                if (!cabinOrder1.Details.Where(x => x.OrderDetailStatus != "已完成").Any()) cabinOrder.OdrderStatus = "已完成";
                Repository.UpdateData(cabinOrder);
                #endregion
                #region è´§ä½
                var location = _basicService.LocationInfoService.Repository.QueryFirst(x => x.LocationCode == LocationCode);
                if (location == null) return WebResponseContent.Instance.Error($"请维护货位编号【{LocationCode}】的货位信息");
                if (location.EnableStatus == EnableStatusEnum.Disable.ObjToInt())
                    return WebResponseContent.Instance.Error($"货位编号【{LocationCode}】已禁用,请恢复正常再使用");
                if (location.WarehouseCode != cabinOrderDetail.Reservoirarea)
                    return WebResponseContent.Instance.Error($"货位编号【{LocationCode}】所属库房与当前入库单所属库房不匹配");
                if (location.LocationStatus == LocationStatusEnum.Free.ObjToInt())
                {
                    location.LocationStatus = LocationStatusEnum.InStock.ObjToInt();
                    _basicService.LocationInfoService.UpdateData(location);
                }
                #endregion
                #region åº“å­˜
                Dt_InventoryInfo inventoryInfo = _inventoryInfoService.Repository.QueryFirst(x => x.BatchNo == cabinOrderDetail.Batch_num && x.MaterielCode == cabinOrderDetail.Goods_no && x.LocationCode == LocationCode);
                if (inventoryInfo != null)
                {
                    inventoryInfo.StockQuantity += Inqty;
                    inventoryInfo.AvailableQuantity += Inqty;
                    inventoryInfo.InDate = DateTime.Now;
                    _inventoryInfoService.UpdateData(inventoryInfo);
                }
                else
                {
                    inventoryInfo = new Dt_InventoryInfo()
                    {
                        LocationCode = LocationCode,
                        MaterielCode = materielInfo.MaterielCode,
                        MaterielName = materielInfo.MaterielName,
                        MaterielSpec = materielInfo.MaterielSpec,
                        OutboundQuantity = 0,
                        StockQuantity = Inqty,
                        AvailableQuantity = Inqty,
                        StockStatus = StockStatusEmun.入库完成.ObjToInt(),
                        ValidityPeriod = cabinOrderDetail.Exp_date,
                        WarehouseCode = cabinOrderDetail.Reservoirarea,
                        SupplyQuantity = 0,
                        InDate = DateTime.Now,
                        BatchNo = cabinOrderDetail.Batch_num,
                        Creater = App.User.UserName,
                        CreateDate = DateTime.Now,
                    };
                    _inventoryInfoService.AddData(inventoryInfo);
                }
                #endregion
                #region ä»»åŠ¡è®°å½•
                #region MyRegion
                //Dt_SupplyTask supplyTask = new Dt_SupplyTask()
                //{
                //    WarehouseCode = cabinOrderDetail.Reservoirarea,
                //    TaskNum = cabinOrderDetail.Id,
                //    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                //    BatchNo = inventoryInfo.BatchNo,
                //    MaterielName = inventoryInfo.MaterielName,
                //    MaterielCode = inventoryInfo.MaterielCode,
                //    MaterielSpec = inventoryInfo.MaterielSpec,
                //    TaskType = TaskTypeEnum.InPick.ObjToInt(),
                //    CreateDate = DateTime.Now,
                //    Creater = App.User.UserName,
                //    LocationCode = location.LocationCode,
                //    OrderNo = cabinOrder.Order_no,
                //    StockQuantity = Inqty,
                //    SupplyQuantity = 0,
                //    Remark = "入库"
                //};
                //_supplyTaskService.AddData(supplyTask);
                #endregion
                Dt_SupplyTask_Hty supplyTask_Hty = new Dt_SupplyTask_Hty()
                {
                    WarehouseCode = cabinOrderDetail.Reservoirarea,
                    TaskNum = cabinOrderDetail.Id,
                    OperateType = OperateTypeEnum.人工完成.ToString(),
                    InsertTime = DateTime.Now,
                    TaskStatus = SupplyStatusEnum.InFinish.ObjToInt(),
                    BatchNo = inventoryInfo.BatchNo,
                    MaterielName = inventoryInfo.MaterielName,
                    MaterielCode = inventoryInfo.MaterielCode,
                    MaterielSpec = inventoryInfo.MaterielSpec,
                    TaskType = TaskTypeEnum.InPick.ObjToInt(),
                    CreateDate = DateTime.Now,
                    Creater = App.User.UserName,
                    LocationCode = location.LocationCode,
                    OrderNo = cabinOrder.Order_no,
                    StockQuantity = Inqty,
                    SupplyQuantity = 0,
                    Remark = "入库"
                };
                _supplyTaskHtyService.AddData(supplyTask_Hty);
                #endregion
                #region åº“存批次
                Dt_Inventory_Batch inventory_Batch = _inventory_BatchServices.Repository.QueryFirst(x => x.BatchNo == inventoryInfo.BatchNo && x.MaterielCode == inventoryInfo.MaterielCode);
                if (inventory_Batch != null)
                {
                    inventory_Batch.StockQuantity += Inqty;
                    inventory_Batch.AvailableQuantity += Inqty;
                    _inventory_BatchServices.UpdateData(inventory_Batch);
                }
                else
                {
                    inventory_Batch = new Dt_Inventory_Batch()
                    {
                        BatchNo = inventoryInfo.BatchNo,
                        CreateDate = inventoryInfo.CreateDate,
                        Creater = inventoryInfo.Creater,
                        MaterielCode = inventoryInfo.MaterielCode,
                        ERPStockQuantity = 0,
                        MaterielName = inventoryInfo.MaterielName,
                        MaterielSpec = inventoryInfo.MaterielSpec,
                        OutboundQuantity = inventoryInfo.OutboundQuantity,
                        ProductionDate = inventoryInfo.ProductionDate,
                        Status = false,
                        StockQuantity = inventoryInfo.StockQuantity,
                        AvailableQuantity = inventoryInfo.StockQuantity,
                        ValidityPeriod = inventoryInfo.ValidityPeriod,
                        SupplyQuantity = inventoryInfo.SupplyQuantity,
                    };
                    _inventory_BatchServices.AddData(inventory_Batch);
                }
                #endregion
                _unitOfWorkManage.CommitTran();
                #endregion
                content.OK(cabinOrderDetail.Order_Inqty.ToString());
            }
            catch (Exception ex)
            {
                _unitOfWorkManage.RollbackTran();
                content.Error(ex.Message);
            }
            return content;
        }
        static string SearchDate = "2025-10-10 00:00:00";
        /// <summary>
        /// èŽ·å–ä¸Šæ¸¸ç³»ç»Ÿçš„å…¥åº“å•
        /// </summary>
        /// <param name="searchDate"></param>
        /// <returns></returns>
        //public WebResponseContent GetUpstreamOrder(DateTime searchDate)
        //{
        //    var responseContent = new WebResponseContent();
        //    try
        //    {
        //        // è¯·æ±‚地址
        //        var url = "http://127.0.0.1:9090/GYZ2/95fck/inOrder";
        //        //// è¯·æ±‚参数
        //        var requestData = new
        //        {
        //            searchDate = searchDate.ToString("yyyy-MM-dd HH:mm:ss")
        //        };
        //        // å‘起请求
        //        var result = HttpHelper.Post(url, requestData.ToJsonString());
        //        // ååºåˆ—化
        //        var response = JsonConvert.DeserializeObject<UpstreamResponse<UpstreamOrderInfo>>(result);
        //        if (response.resultCode != "0")
        //        {
        //            // è°ƒç”¨å¼‚常接口
        //            SendErrorToUpstream(1, "", response.resultMsg ?? "上游接口返回失败", "");
        //            return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
        //        }
        //        if (response.data == null || !response.data.Any())
        //        {
        //            return responseContent.OK("无新入库单数据");
        //        }
        //        Db.Ado.BeginTran();
        //        List<Dt_CabinOrder> _CabinOrders = new List<Dt_CabinOrder>();
        //        foreach (var order in response.data)
        //        {
        //            try
        //            {
        //                // æ’入入库单表
        //                var entityOrder = new Dt_CabinOrder
        //                {
        //                    Order_no = order.order_no,
        //                    Order_type = order.order_type,
        //                    Supplier_no = order.supplier_no,
        //                    Account_tiem = order.account_time,
        //                    OdrderStatus = "新建",
        //                };
        //                //var orderId = Db.Insertable(entityOrder).ExecuteReturnIdentity(); //就是返回主键ID。
        //                // æ’入入库明细表
        //                var detailEntities = order.details.Select(d => new Dt_CabinOrderDetail
        //                {
        //                    //OrderId= orderId,
        //                    Goods_no = d.goods_no,
        //                    Order_qty = d.order_qty,
        //                    Batch_num = d.batch_num,
        //                    Exp_date = d.exp_date,
        //                    Warehouse_no = d.warehouse_no,
        //                    Status = 0,
        //                }).ToList();
        //                entityOrder.Details.AddRange(detailEntities); //建立主对象与子对象的关联关系
        //                _CabinOrders.Add(entityOrder);
        //                //自己
        //                /// Db.Insertable(detailEntities).ExecuteCommand();
        //                //这里要调用一个接口将上面的信息传给wcs,然后改变状态
        //            }
        //            catch (Exception innerEx)
        //            {
        //                // é’ˆå¯¹æŸæ¡è®¢å•报错时,推送异常给上游
        //                SendErrorToUpstream(1, order.order_no, innerEx.Message, "");
        //                throw; // æŠ›å‡ºå¼‚常,让外层捕获回滚
        //            }
        //        }
        //        // æ‰¹é‡æ’入(SqlSugar自动处理主外键关系)
        //        Db.Insertable(_CabinOrders).ExecuteCommand();
        //        Db.Ado.CommitTran();
        //        //如果EdiIn完成那么就调用CompleteOrder接口
        //        return responseContent.OK("同步入库单成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        // å…¨å±€å¼‚常时,也推送异常给上游
        //        SendErrorToUpstream(1, "", ex.Message, "");
        //        Db.Ado.RollbackTran();
        //        return responseContent.Error("同步失败: " + ex.Message);
        //    }
        //}
        public WebResponseContent GetUpstreamOrder()
        {
            var responseContent = new WebResponseContent();
@@ -138,14 +299,16 @@
            {
                // è¯·æ±‚地址
                var url = "http://121.37.118.63:80/GYZ2/95fck/inOrder";
                //if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //var url = "http://127.0.0.1:4523/m2/5660322-5340849-default/363009261";
                if (string.IsNullOrEmpty(SearchDate)) SearchDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //// è¯·æ±‚参数
                var requestData = new
                {
                    //searchDate = SearchDate
                    searchDate = "2022-10-10 20:45:16"  // æ­£ç¡®çš„æ ¼å¼
                    searchDate = SearchDate
                    //searchDate = "2022-10-10 20:45:16"  // æ­£ç¡®çš„æ ¼å¼
                };
                //SearchDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
                SearchDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss");
                // å‘起请求
                var result = HttpHelper.Post(url, requestData.ToJsonString());
@@ -187,36 +350,23 @@
                    foreach (var order in newOrders)
                    {
                        var entityOrder = new Dt_CabinOrder
                        if (order.order_type == "1") //正常入库
                        {
                            Order_no = order.order_no,
                            //入库单类型
                            Order_type = order.order_type,
                            Supplier_no = order.supplier_no,
                            Account_tiem = order.account_time,
                            OdrderStatus = "新建",
                            Supplier_name=order.supplier_name,
                            Warehouse_no = order.warehouse_no,
                            Details = order.details.Select(d => new Dt_CabinOrderDetail
                            {
                                //OrderId è¦æ‹¿åˆ°å…¥åº“单表中的id,如何拿不到就将这个字段改了,改成入库单号
                                // SqlSugar InsertNav工作原理先插入主表 (Dt_CabinOrder)//获取生成的主键ID//自动设置子表的关联字段 (OrderId)//再插入(Dt_CabinOrderDetail)
                                Goods_no = d.goods_no,
                                Order_qty = d.order_qty,
                                Batch_num = d.batch_num,
                                Exp_date = d.exp_date,
                                OrderDetailStatus="新建",
                                Status = order.warehouse_no== "001" ? 0 : 2, //如果是001房那么就是未同步状态,如果不是001房那么就是无需同步状态
                            }).ToList()
                        };
                        _CabinOrders.Add(entityOrder);
                        orderNos.Add(order.order_no);
                            responseContent = CreateInboundOrder(order);
                            List<Dt_CabinOrder>? dt_CabinOrders = responseContent.Data as List<Dt_CabinOrder>;
                            if (dt_CabinOrders != null) _CabinOrders.AddRange(dt_CabinOrders);
                        }
                        else
                        {
                            //创建出库单
                        }
                    };
                    BaseDal.Db.InsertNav(_CabinOrders).Include(x => x.Details).ExecuteCommand();
                    //在下发给wcs 
                  //var reslut=  EdiIn(); //发给下游
                                        //如果这个方法成功了,那么就调用CompleteOrder接口,然后改变
                    //EdiIn(); //发给下游
                    //如果这个方法成功了,那么就调用CompleteOrder接口,然后改变
                    Db.Ado.CommitTran();
                    return responseContent.OK("同步入库单成功");
                }
@@ -235,6 +385,177 @@
            }
        }
        #region åˆ›å»ºå…¥åº“单
        /// <summary>
        /// åˆ›å»ºå…¥åº“单,返回一个入库单集合到data
        /// </summary>
        public WebResponseContent CreateInboundOrder(UpstreamOrderInfo order)
        {
            WebResponseContent webResponseContent = new WebResponseContent();
            try
            {
                List<Dt_CabinOrder> dt_CabinOrders = new List<Dt_CabinOrder>();
                #region ç‰¹æ®Šè¯å“å…¥ç‰¹æ®Šåº“房
                if (order.warehouse_no == WarehouseEnum.麻精库.ObjToInt().ToString("000") || order.warehouse_no == WarehouseEnum.冷冻库.ObjToInt().ToString("000"))
                {
                    var entityOrder = new Dt_CabinOrder
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = order.warehouse_no,
                        Details = order.details.Select(d => new Dt_CabinOrderDetail
                        {
                            Goods_no = d.goods_no,
                            Order_qty = Math.Abs(d.order_qty),
                            Batch_num = d.batch_num,
                            Exp_date = d.exp_date,
                            OrderDetailStatus = "新建",
                            Status = 2, //如果是001房那么就是未同步状态,如果不是001房那么就是无需同步状态
                        }).ToList()
                    };
                    dt_CabinOrders.Add(entityOrder);
                    webResponseContent.OK(data: dt_CabinOrders);
                }
                #endregion
                else
                {
                    var entityOrder = new Dt_CabinOrder//大件库订单
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = WarehouseEnum.大件库.ObjToInt().ToString("000"),
                        Details = new List<Dt_CabinOrderDetail>()
                    };
                    var entityOrderLK = new Dt_CabinOrder//立库订单
                    {
                        Order_no = order.order_no,
                        Order_type = order.order_type,
                        Supplier_no = order.supplier_no,
                        Account_tiem = order.account_time,
                        OdrderStatus = "新建",
                        Supplier_name = order.supplier_name,
                        Warehouse_no = WarehouseEnum.立库.ObjToInt().ToString("000"),
                        Details = new List<Dt_CabinOrderDetail>()
                    };
                    foreach (var item in order.details)
                    {
                        // å°†ä¸Šæ¸¸å…¥åº“数量转为正数
                        item.order_qty = Math.Abs(item.order_qty);
                        #region æ ¹æ®ç‰©æ–™ç¼–码查询物料信息
                        Dt_MaterielInfo materielInfo = _basicService.MaterielInfoService.Repository.QueryFirst(x => x.MaterielCode == item.goods_no);
                        if (materielInfo == null) throw new Exception($"未找到药品编码【{item.goods_no}】的信息");
                        if (!Enum.IsDefined(typeof(MaterielSourceTypeEnum), materielInfo.MaterielSourceType))
                            throw new Exception($"请设置药品编号【{item.goods_no}】的属性分类");
                        if (materielInfo.BoxQty < 1) throw new Exception($"请设置药品编号【{item.goods_no}】的箱规数量");
                        if (materielInfo.MinQty < 1) throw new Exception($"请设置药品编号【{item.goods_no}】的立库最低库存数");
                        #endregion
                        #region å¤§ä»¶
                        if (materielInfo.MaterielSourceType == MaterielSourceTypeEnum.PurchasePart)//如果物料是大件
                        {
                            Dt_CabinOrderDetail orderDetail = new Dt_CabinOrderDetail()
                            {
                                Reservoirarea = entityOrder.Warehouse_no,
                                Goods_no = item.goods_no,
                                Order_qty = item.order_qty,
                                Batch_num = item.batch_num,
                                Exp_date = item.exp_date,
                                OrderDetailStatus = "新建",
                                Status = 2
                            };
                            entityOrder.Details.Add(orderDetail);
                        }
                        #endregion
                        else
                        {
                            Dt_CabinOrderDetail orderDetail = null;
                            var ys = item.order_qty % materielInfo.BoxQty; //不能整除箱规的散件数
                            var xs = (int)(item.order_qty / materielInfo.BoxQty);//保留整数
                            #region åˆ¤æ–­æ˜¯å¦æœ‰æ•£ä»¶
                            if (ys > 0)
                            {
                                orderDetail = new Dt_CabinOrderDetail()
                                {
                                    Reservoirarea = entityOrderLK.Warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = ys,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
                                    Status = 0
                                };
                                materielInfo.Business_qty += ys;
                            }
                            #endregion
                            #region åˆ¤æ–­ç«‹åº“库存是否大于立库最低库存数
                            while (materielInfo.Business_qty < materielInfo.MinQty && xs > 0) //当业务数量和整箱数都大于0的时候才会停止循环
                            {
                                xs--;
                                if (orderDetail == null)
                                {
                                    orderDetail = new Dt_CabinOrderDetail()
                                    {
                                        Reservoirarea = entityOrderLK.Warehouse_no,
                                        Goods_no = item.goods_no,
                                        Order_qty = materielInfo.BoxQty,
                                        Batch_num = item.batch_num,
                                        Exp_date = item.exp_date,
                                        OrderDetailStatus = "新建",
                                        Status = 0
                                    };
                                    materielInfo.Business_qty += materielInfo.BoxQty;
                                }
                                else
                                {
                                    orderDetail.Order_qty += materielInfo.BoxQty;
                                    materielInfo.Business_qty += materielInfo.BoxQty;
                                }
                            }
                            if (orderDetail != null) entityOrderLK.Details.Add(orderDetail);
                            #endregion
                            #region å‰©ä½™æ•´ä»¶å…¥å¹³åº“
                            if (xs > 0)
                            {
                                orderDetail = new Dt_CabinOrderDetail()
                                {
                                    Reservoirarea = entityOrder.Warehouse_no,
                                    Goods_no = item.goods_no,
                                    Order_qty = materielInfo.BoxQty * xs,
                                    Batch_num = item.batch_num,
                                    Exp_date = item.exp_date,
                                    OrderDetailStatus = "新建",
                                    Status = 2
                                };
                                entityOrder.Details.Add(orderDetail);
                            }
                            #endregion
                        }
                        _basicService.MaterielInfoService.Repository.UpdateData(materielInfo);
                    }
                    if (entityOrder.Details.Count > 0) dt_CabinOrders.Add(entityOrder);
                    if (entityOrderLK.Details.Count > 0) dt_CabinOrders.Add(entityOrderLK);
                    webResponseContent.OK(data: dt_CabinOrders);
                }
            }
            catch (Exception ex)
            {
                webResponseContent.Error(ex.Message);
            }
            return webResponseContent;
        }
        #endregion
        /// <summary>
        /// ä¼ ç»™wcs
        /// </summary>
@@ -250,33 +571,31 @@
                //查出包含全部的入库单,包含全部明细+一个明细对应一个商品
                var orders = BaseDal.Db.CopyNew()
                .Queryable<Dt_CabinOrder>()
                .Where(o => o.OdrderStatus == "新建")
                .Where(o => o.OdrderStatus == "新建" && o.Warehouse_no == WarehouseEnum.立库.ObjToInt().ToString("000"))
                .Includes(o => o.Details, d => d.MedicineGoods)
                .ToList();
                // 3. å†è¿‡æ»¤æŽ‰ä¸ç¬¦åˆæ¡ä»¶çš„æ˜Žç»†ï¼ˆåªä¿ç•™ Status=0)
                foreach (var order in orders)
                {
                    Console.WriteLine($"订单 {order.Order_no} åŽŸæ˜Žç»†æ•°ï¼š{order.Details.Count}");
                    order.Details = order.Details.Where(d => d.Status == 0).ToList();
                    Console.WriteLine($"订单 {order.Order_no} è¿‡æ»¤åŽæ˜Žç»†æ•°ï¼š{order.Details.Count}");
                }
                if (orders == null || !orders.Any())
                {
                    Console.WriteLine("没有符合条件的订单需要推送");
                    return WebResponseContent.Instance.Error("没有符合条件的订单需要推送");
                }
                // 4. éåŽ†è®¢å•ï¼Œç»„è£… DTO å¹¶æŽ¨é€
                foreach (var order in orders)
                {
                    string materialCode = "YY";//默认值
                    //获取当前订单的第一个明细项
                    var firstDetail = order.Details.FirstOrDefault();
                    if (firstDetail?.MedicineGoods != null && !string.IsNullOrEmpty(firstDetail.MedicineGoods.MaterialCode))
                    {
                        //如果条件满足,将物料代码设置为第一个明细项对应的药品物料代码
                        materialCode = firstDetail.MedicineGoods.MaterialCode;
                    }
                    // ä»Žç¬¬ä¸€ä¸ªæœ‰ MedicineGoods çš„æ˜Žç»†ä¸­å–出 MaterielErpType
                    string materialCode = order.Details
                        .Select(d => d.MedicineGoods?.MaterielErpType)
                        .FirstOrDefault(x => !string.IsNullOrEmpty(x)) ?? "YY"; // é»˜è®¤å€¼YY
                    var ediDto = new ToediInInfo
                    {
@@ -300,9 +619,9 @@
                            //产品
                            productCode = d.Goods_no,
                            //sku名称
                            productName = d.MedicineGoods?.Goods_spm,
                            productName = d.MedicineGoods?.MaterielName,
                            //sku规格
                            productSpecifications = d.MedicineGoods?.Model,
                            productSpecifications = d.MedicineGoods?.MaterielSpec,
                            //数量
                            quantity = (int)d.Order_qty,
                            //效期
@@ -311,36 +630,25 @@
                            manufacturer = d.MedicineGoods?.Factory,
                            //房号
                            libraryNo = order.Warehouse_no,
                            //盘盈入库
                            //stocktakingDetails = new List<ToediInStock>()
                            //stocktakingDetails = new List<ToediInStock>()
                            //{
                            //    new ToediInStock
                            //    {
                            //         //料箱号
                            //        palletCode = "PDA001",
                            //        //数量
                            //        quantity = d.Order_qty.ToString()
                            //    }
                            // }
                        }).ToList()
                    };
                    var url = "http://172.16.1.2:9357/file-admin/api/in/ediIn";
                    //var url = "http://127.0.0.1:4523/m2/5660322-5340849-default/363019549";
                    var result = HttpHelper.Post(url, ediDto.ToJsonString());
                    var resp = JsonConvert.DeserializeObject<TowcsResponse<object>>(result);
                    if (resp != null && resp.code == "0")
                    {
                        // æ›´æ–°è¡¨å¤´çŠ¶æ€
                       BaseDal.Db.Updateable<Dt_CabinOrder>()
                          .SetColumns(o => new Dt_CabinOrder { OdrderStatus = "开始" })
                          .Where(o => o.Id == order.Id)
                          .ExecuteCommand();
                        BaseDal.Db.Updateable<Dt_CabinOrder>()
                           .SetColumns(o => new Dt_CabinOrder { OdrderStatus = "开始" })
                           .Where(o => o.Id == order.Id)
                           .ExecuteCommand();
                        // æ›´æ–°æ˜Žç»†çŠ¶æ€ä¸ºå·²åŒæ­¥
                        // æ›´æ–°æ˜Žç»†çŠ¶æ€ä¸ºå·²åŒæ­¥  //这里要是将新建--》开始状态,在后端接口返回我们的时候在返回已完成
                        BaseDal.Db.Updateable<Dt_CabinOrderDetail>()
                          .SetColumns(d => new Dt_CabinOrderDetail { Status = 1, OrderDetailStatus = "已完成" })
                          .SetColumns(d => new Dt_CabinOrderDetail { Status = 1, OrderDetailStatus = "开始" })
                          .Where(d => d.OrderId == order.Id && d.Status == 0)
                          .ExecuteCommand();
@@ -357,7 +665,7 @@
            }
            catch (Exception ex)
            {
                Console.WriteLine("EdiIn å¼‚常:" + ex.Message);
                return new WebResponseContent { Status = false, Message = ex.Message };
            }
@@ -374,119 +682,48 @@
            var responseContent = new WebResponseContent();
            try
            {
                // æŸ¥æ‰¾æ‰€æœ‰â€œå¼€å§‹â€çŠ¶æ€çš„å…¥åº“å•
                var orders = BaseDal.Db.Queryable<Dt_CabinOrder>()
                    .Where(o => o.OdrderStatus == "开始")
                    .ToList();
                if (orders == null || !orders.Any())
                #region æŸ¥æ‰¾æ‰€æœ‰å·²å®Œæˆå…¥åº“单
                var inorders = BaseDal.QueryData(x => x.OdrderStatus == "已完成").Select(x => x.Order_no).Distinct().ToList();
                foreach (var inorder in inorders)
                {
                    return responseContent.OK("暂无需要处理的入库单");
                }
                int successCount = 0;
                int failCount = 0;
                foreach (var order in orders)
                {
                    try
                    //var Orders = BaseDal.QueryData(x => x.Order_no == inorder);
                    var Orders = BaseDal.Db.Queryable<Dt_CabinOrder>().Where(x => x.Order_no == inorder).Includes(x => x.Details).ToList();
                    if (!Orders.Where(x => x.OdrderStatus != "已完成").Any())
                    {
                        BaseDal.Db.Ado.BeginTran();
                        // æŸ¥è¯¢è¯¥å•的明细
                        var details = BaseDal.Db.Queryable<Dt_CabinOrderDetail>()
                            .Where(d => d.OrderId == order.Id)
                            .ToList();
                        // åˆ¤æ–­æ˜¯å¦å…¨éƒ¨å®Œæˆ
                        var totalCount = details.Count;
                        var completedCount = details.Count(d => d.OrderDetailStatus == "已完成");
                        if (totalCount > 0 && completedCount == totalCount)
                        BaseDal.DeleteAndMoveIntoHty(Orders, OperateTypeEnum.自动完成);
                        foreach (var item in Orders)
                        {
                            // æ›´æ–°è¡¨å¤´çŠ¶æ€
                            order.OdrderStatus = "已完成";
                            BaseDal.Db.Updateable(order).ExecuteCommand();
                            // è°ƒç”¨ä¸Šæ¸¸æŽ¥å£
                            var url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                            var result = HttpHelper.Post(url, new { order_no = order.Order_no }.ToJsonString());
                            var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                            if (response.resultCode == "0")
                            {
                                // === æ­¥éª¤ 1:插入历史表 ===
                                // 1.1 æ’入表头历史
                                var orderHistory = new Dt_CabinOrder_Hty
                                {
                                    Id = order.Id,
                                    Order_no = order.Order_no,
                                    Order_type = order.Order_type,
                                    Supplier_no = order.Supplier_no,
                                    Supplier_name = order.Supplier_name,
                                    Account_tiem = order.Account_tiem,
                                    Warehouse_no = order.Warehouse_no,
                                    OdrderStatus = order.OdrderStatus,
                                };
                                var historyId = BaseDal.Db.Insertable(orderHistory).ExecuteReturnIdentity();
                                // 1.2 æ’入明细历史
                                var detailsHistory = details.Select(d => new Dt_CabinOrderDetail_Hty
                                {
                                    Id = d.Id,
                                    Reservoirarea = d.Reservoirarea,
                                    Goods_no = d.Goods_no,
                                    Order_qty = d.Order_qty,
                                    Order_Inqty = d.Order_Inqty,
                                    Batch_num = d.Batch_num,
                                    Exp_date = d.Exp_date,
                                    OrderDetailStatus = d.OrderDetailStatus,
                                    Status = d.Status,
                                }).ToList();
                                BaseDal.Db.Insertable(detailsHistory).ExecuteCommand();
                                // === æ­¥éª¤ 2:删除原始表 ===
                                BaseDal.Db.Deleteable<Dt_CabinOrderDetail>().Where(d => d.OrderId == order.Id).ExecuteCommand();
                                BaseDal.Db.Deleteable<Dt_CabinOrder>().Where(o => o.Id == order.Id).ExecuteCommand();
                                // æäº¤äº‹åŠ¡
                                BaseDal.Db.Ado.CommitTran();
                                successCount++;
                            }
                            else
                            {
                                BaseDal.Db.Ado.RollbackTran();
                                failCount++;
                                SendErrorToUpstream(2, "", $"上游接口返回失败: {response.resultMsg}", order.Order_no);
                            }
                            _cabinOrderDetailServices.Repository.DeleteAndMoveIntoHty(item.Details, OperateTypeEnum.自动完成);
                        }
                        // è°ƒç”¨ä¸Šæ¸¸æŽ¥å£
                        var url = "http://121.37.118.63:80/GYZ2/95fck/inOrderOk";
                        var result = HttpHelper.Post(url, new { order_no = inorder }.ToJsonString());
                        var response = JsonConvert.DeserializeObject<UpstreamOrderResponse>(result);
                        if (response.resultCode == "0")
                        {
                            // æäº¤äº‹åŠ¡
                            BaseDal.Db.Ado.CommitTran();
                        }
                        else
                        {
                            BaseDal.Db.Ado.RollbackTran();
                            SendErrorToUpstream(2, "", $"上游接口返回失败: {response.resultMsg}", inorder);
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseDal.Db.Ado.RollbackTran();
                        failCount++;
                        SendErrorToUpstream(1, "", ex.Message, order.Order_no);
                    }
                }
                return responseContent.OK($"批量处理完成:成功 {successCount} å•,失败 {failCount} å•。");
                #endregion
                return responseContent.OK();
            }
            catch (Exception ex)
            {
                BaseDal.Db.Ado.RollbackTran();
                return responseContent.Error("批量处理失败:" + ex.Message);
            }
        }
        /// <summary>
@@ -518,7 +755,7 @@
    }