yanjinhui
2025-10-23 770b80efd437680e84a674ddf3db90037a833f47
н¨Îļþ¼Ð/WIDESEA_WMSServer/WIDESEA_SquareCabinServices/InventoryServices.cs
@@ -20,8 +20,10 @@
{
    public class InventoryServices : ServiceBase<Dt_Inventory, IRepository<Dt_Inventory>>, IInventoryServices
    {
        public InventoryServices(IRepository<Dt_Inventory> BaseDal) : base(BaseDal)
        private readonly IDeliveryOrderServices _deliveryOrderServices;
        public InventoryServices(IRepository<Dt_Inventory> BaseDal, IDeliveryOrderServices deliveryOrderServices) : base(BaseDal)
        {
            _deliveryOrderServices = deliveryOrderServices;
        }
@@ -38,34 +40,33 @@
            try
            {
                var url = "http://121.37.118.63/GYZ2/95fck/repositoryInfo";
                // å‘起请求
                var result = HttpHelper.Post(url, new { goods_no,batch_num}.ToJsonString());
                var result = HttpHelper.Post(url, new { goods_no, batch_num }.ToJsonString());
                // ååºåˆ—化
                var response = JsonConvert.DeserializeObject<UpstreamResponse<InventoryInfo>>(result);
                if (response.resultCode!="0")
                if (response.resultCode != "0")
                {
                    // è°ƒç”¨å¼‚常接口
                    SendErrorToUpstream(8, "", response.resultMsg ?? "上游接口返回失败", "");
                    return responseContent.Error(response.resultMsg ?? "上游接口返回失败");
                }
                if (response.data == null || !response.data.Any())
                {
                    return responseContent.OK("无新库存数据");
                }
                Db.Ado.BeginTran();
                foreach (var item in response.data)
                {
                    var Inver = new Dt_Inventory
                    {
                        Goods_no = item.goods_no,
                        Batch_num = item.batch_num,
                        Exp_date=item.exp_date,
                        Business_qty = item.business_qty,
                        Actual_qty = item.actural_qty,
                    };
                    AddData(Inver);
                    // ä½¿ç”¨ FirstOrDefault é¿å…æ‰¾ä¸åˆ°è®°å½•时抛出异常
                    var Inver = Db.Queryable<Dt_Inventory_Batch>()
                        .First(x => x.MaterielCode == item.goods_no && x.BatchNo == item.batch_num);
                    if (Inver != null)
                    {
                        Inver.ERPStockQuantity = item.business_qty;
                        Db.Updateable(Inver).ExecuteCommand();
                    }
                }
                Db.Ado.CommitTran();
                return responseContent.OK("库存信息同步完成");
@@ -79,136 +80,49 @@
        }
        /// <summary>
        /// wcs回传给我调用我的方法
        /// wcs回传给我调用我的方法 ä¸ç®¡æ˜¯å…¥åº“ å‡ºåº“ ç›˜ç‚¹éƒ½ä¼šè°ƒç”¨è¿™ä¸ªæŽ¥å£
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        //public ApiResponse<Dt_Inventory> OrderFeedback(EdiOrderCallbackRequest request)
        //{
        //    try
        //    {
        //        if (request == null || request.details == null || !request.details.Any())
        //        {
        //            return new ApiResponse<Dt_Inventory> { code = "500", msg = "请求参数无效" };
        //        }
        //        BaseDal.Db.Ado.BeginTran();//开启事务
        //        foreach (var detail in request.details)
        //        {
        //            // å…ˆæŸ¥åº“存是否存在(按照产品编号和批次来寻找)
        //            var entity = BaseDal.Db.Queryable<Dt_Inventory>()
        //                           .First(x => x.Goods_no == detail.productCode && x.Batch_num == detail.batchNo);
        //            //将集合中的数量进行累加
        //            // å®‰å…¨è½¬æ¢
        //            //正常出入库
        //            decimal orderQty = detail.orderDetails?.Sum(x => decimal.TryParse(x.quantity, out var q) ? q : 0) ?? 0;
        //            //盘点盘亏
        //            decimal diffQty = detail.stocktakingDetails?.Sum(x => Convert.ToDecimal(x.differenceQuantity)) ?? 0;
        //            if (entity == null)
        //            {
        //                // å¦‚果不存在,新建一条
        //                entity = new Dt_Inventory
        //                {
        //                    Goods_no = detail.productCode ?? detail.productName,
        //                    Reservoirarea = "默认库区",
        //                    Batch_num = detail.batchNo,
        //                    //业务库存
        //                    Business_qty = 0,
        //                    //实际库存
        //                    Actual_qty = 0
        //                };
        //            }
        //            switch (request.orderType)
        //            {
        //                case "1": // å…¥åº“
        //                    entity.Business_qty += orderQty;
        //                    entity.Actual_qty += orderQty;
        //                    break;
        //                case "2": // å‡ºåº“
        //                    entity.Business_qty -= orderQty;
        //                    entity.Actual_qty -= orderQty;
        //                    if (entity.Business_qty < 0) entity.Business_qty = 0; // å¯é€‰ï¼šé˜²æ­¢è´Ÿæ•°
        //                    if (entity.Actual_qty < 0) entity.Actual_qty = 0;
        //                    break;
        //                case "3": // ç›˜ç‚¹
        //                    if (detail.stocktakingDetails != null && detail.stocktakingDetails.Any())
        //                    {
        //                        foreach (var stock in detail.stocktakingDetails)
        //                        {
        //                            //每次都只拿一条明细中的数量
        //                            decimal diff = Convert.ToDecimal(stock.differenceQuantity);
        //                            if (stock.IsProfit == "1") // ç›˜ç›ˆ
        //                            {
        //                                entity.Business_qty += diff;//如果盘盈了多了,就将业务数量+,盘亏则相反
        //                                entity.PalletCode = stock.palletCode;
        //                            }
        //                            else // ç›˜äº
        //                            {
        //                                entity.Business_qty -= diff;
        //                                entity.PalletCode = stock.palletCode;
        //                            }
        //                        }
        //                    }
        //                    break;
        //            }
        //            // ä¿å­˜æ•°æ®
        //            if (entity.Id == 0) // æ–°å»º
        //                BaseDal.Db.Insertable(entity).ExecuteCommand();
        //            else // æ›´æ–°
        //                BaseDal.Db.Updateable(entity).ExecuteCommand();
        //        }
        //        BaseDal.Db.Ado.CommitTran(); // æäº¤äº‹åŠ¡
        //        return new ApiResponse<Dt_Inventory> { code = "0", msg = "成功" };
        //    }
        //    catch (Exception ex)
        //    {
        //        BaseDal.Db.Ado.RollbackTran();//回滚事务
        //        return new ApiResponse<Dt_Inventory> { code = "500", msg = ex.Message };
        //    }
        //}
        public ApiResponse<Dt_InventoryInfo> OrderFeedback(EdiOrderCallbackRequest request)
        {
            try
            {
            {
                // 1️⃣ æ ¡éªŒè¯·æ±‚
                if (request == null || request.details == null || !request.details.Any())
                {
                    return new ApiResponse<Dt_InventoryInfo> { code = "500", msg = "请求参数无效" };
                }
                BaseDal.Db.Ado.BeginTran(); // å¼€å¯äº‹åŠ¡
                //查找到全部的
                foreach (var detail in request.details)
                {
                    // å…¥åº“数量(自动取正)
                    var goods = Db.Queryable<Dt_MaterielInfo>().Where(x => x.MaterielCode == detail.productCode).First();
                    // 3️ è®¡ç®—入库数量(取正)遍历 orderDetails ä¸­çš„æ¯ä¸ª EdiOrderBoxDto å¯¹è±¡
                    decimal orderQty = detail.orderDetails?
                        .Sum(x => decimal.TryParse(x.quantity, out var q) ? Math.Abs(q) : 0)
                        ?? 0;
                    // ç›˜ç‚¹å·®å¼‚æ•°
                    decimal diffQty = detail.stocktakingDetails?
                        .Sum(x => Convert.ToDecimal(x.differenceQuantity))
                        ?? 0;
                    // æŸ¥è¯¢çŽ°æœ‰åº“å­˜æ˜Žç»†
                    // 5️⃣ æŸ¥è¯¢åº“存详情
                    var entity = BaseDal.Db.Queryable<Dt_InventoryInfo>()
                        .First(x => x.MaterielCode == detail.productCode && x.BatchNo == detail.batchNo);
                        .First(x => x.MaterielCode == detail.productCode && x.BatchNo == detail.batchNo && x.LocationCode == "立库");
                    //查询物料表
                    var Goods = BaseDal.Db.Queryable<Dt_MaterielInfo>().First(x => x.MaterielCode == detail.productCode);
                    if (entity == null)
                    {
                        //不存在则新建库存明细记录
                        entity = new Dt_InventoryInfo
                        {
                            PalletCode = detail.orderDetails?.FirstOrDefault()?.palletCode ?? "",
                            WarehouseCode = 1.ToString(),  // é»˜è®¤åº“房编号
                            LocationCode = "",
                            StockStatus = 1,   // ç«‹åº“固定为 1
                            WarehouseCode = "001",
                            LocationCode = "立库",
                            StockStatus = 1,
                            MaterielCode = detail.productCode ?? detail.productName,
                            MaterielName = detail.productName ?? "",
                            MaterielSpec = detail.productSpecifications ?? "",
@@ -216,6 +130,7 @@
                            StockQuantity = 0,
                            OutboundQuantity = 0,
                            SupplyQuantity = 0,
                            AvailableQuantity = 0,
                            InDate = DateTime.Now,
                            ProductionDate = detail.finishDate.ToString("yyyy-MM-dd"),
                            ShelfLife = 0,
@@ -224,7 +139,7 @@
                        };
                    }
                    // æ‰¹æ¬¡è¡¨è®°å½•(用于汇总)
                    // 6️⃣ æŸ¥è¯¢åº“存批次信息
                    var batch = BaseDal.Db.Queryable<Dt_Inventory_Batch>()
                        .First(x => x.MaterielCode == detail.productCode && x.BatchNo == detail.batchNo);
@@ -238,6 +153,7 @@
                            BatchNo = detail.batchNo,
                            StockQuantity = 0,
                            OutboundQuantity = 0,
                            AvailableQuantity = 0,
                            SupplyQuantity = 0,
                            ERPStockQuantity = 0,
                            Status = false,
@@ -247,56 +163,65 @@
                        };
                    }
                    // 7️⃣ æŒ‰è®¢å•类型执行不同逻辑
                    switch (request.orderType)
                    {
                        case "1": // å…¥åº“
                            entity.StockQuantity += (float)orderQty;
                        case "1": //入库
                            entity.StockQuantity = orderQty; //实际库存
                            entity.AvailableQuantity = orderQty;
                            entity.InDate = DateTime.Now;
                            entity.Remark = "入库单回传";
                            batch.StockQuantity += (float)orderQty;
                            batch.StockQuantity = orderQty;
                            batch.AvailableQuantity = orderQty;
                            batch.Remark = "入库单回传";
                            UpdateInboundOrderDetailStatus(detail.batchNo, detail.productCode);
                            break;
                        case "2": // å‡ºåº“
                            entity.OutboundQuantity += (float)orderQty;
                            entity.StockQuantity -= (float)orderQty;
                        case "2": // å‡ºåº“  æ€»100  å‡º20
                            decimal actualOutQty = entity.StockQuantity - orderQty;// è®¡ç®—本次实际出库数量 20
                            entity.StockQuantity=orderQty; //实际库存数 100
                            entity.OutboundQuantity =Math.Max(0,entity.OutboundQuantity-actualOutQty); //待出库数量
                            entity.AvailableQuantity = entity.StockQuantity - entity.OutboundQuantity;//可用库存
                            if (entity.StockQuantity < 0) entity.StockQuantity = 0;
                            entity.Remark = "出库单回传";
                            batch.OutboundQuantity += (float)orderQty;
                            batch.StockQuantity -= (float)orderQty;
                            batch.StockQuantity = orderQty;
                            batch.OutboundQuantity =Math.Max(0,batch.OutboundQuantity-actualOutQty);//待出库数量
                            batch.AvailableQuantity = batch.StockQuantity - batch.OutboundQuantity; //可用库存
                            if (batch.StockQuantity < 0) batch.StockQuantity = 0;
                            batch.Remark = "出库单回传";
                            UpdateOutboundOrderDetailStatus(detail.batchNo, detail.productCode);
                            //调拨任务
                            _deliveryOrderServices.CreateAllocatInOut(goods);
                            break;
                        case "3": //盘点
                            if (detail.stocktakingDetails != null && detail.stocktakingDetails.Any())
                        case "3": // ç›˜ç‚¹
                            decimal diff = detail.ea ?? 0;             // å·®å¼‚æ•°
                            int flag = detail.isLossOrProfit ?? 3;     // 1=盘亏, 2=盘盈, 3=盘中
                            if (flag == 1) // ç›˜äº
                            {
                                foreach (var stock in detail.stocktakingDetails)
                                {
                                    decimal diff = Convert.ToDecimal(stock.differenceQuantity);
                                    if (stock.IsProfit == "1") // ç›˜ç›ˆ
                                    {
                                        entity.SupplyQuantity += (float)Math.Abs(diff);
                                        batch.SupplyQuantity += (float)Math.Abs(diff);
                                    }
                                    else // ç›˜äº
                                    {
                                        entity.SupplyQuantity -= (float)Math.Abs(diff);
                                        batch.SupplyQuantity -= (float)Math.Abs(diff);
                                        if (entity.SupplyQuantity < 0) entity.SupplyQuantity = 0;
                                        if (batch.SupplyQuantity < 0) batch.SupplyQuantity = 0;
                                    }
                                    entity.PalletCode = stock.palletCode;
                                    entity.Remark = "盘点单回传";
                                    batch.Remark = "盘点单回传";
                                }
                                //库存数-差异数=盘亏
                                batch.SupplyQuantity +=( batch.StockQuantity - diff);
                                batch.Remark = "盘点单回传 - ç›˜äº";
                            }
                            else if (flag == 2) // ç›˜ç›ˆ
                            {
                                //库存数+差异数=盘盈
                                batch.SupplyQuantity +=(batch.StockQuantity + diff);
                                batch.Remark = "盘点单回传 - ç›˜ç›ˆ";
                            }
                            else // ç›˜ä¸­
                            {
                                batch.Remark = "盘点单回传 - ç›˜ä¸­";
                            }
                            break;
                    }
                    //保存到数据库
                    // 2️⃣ å¼€å¯äº‹åŠ¡
                    BaseDal.Db.Ado.BeginTran();
                    // 8️⃣ ä¿å­˜æ•°æ®
                    if (entity.Id == 0)
                        BaseDal.Db.Insertable(entity).ExecuteCommand();
                    else
@@ -308,17 +233,77 @@
                        BaseDal.Db.Updateable(batch).ExecuteCommand();
                }
                // 9️⃣ æäº¤äº‹åŠ¡
                BaseDal.Db.Ado.CommitTran();
                return new ApiResponse<Dt_InventoryInfo> { code = "0", msg = "成功" };
                return new ApiResponse<Dt_InventoryInfo>
                {
                    code = "0",
                    msg = "成功"
                };
            }
            catch (Exception ex)
            {
                // ðŸ”Ÿ å›žæ»šäº‹åŠ¡
                BaseDal.Db.Ado.RollbackTran();
                return new ApiResponse<Dt_InventoryInfo> { code = "500", msg = ex.Message };
                return new ApiResponse<Dt_InventoryInfo>
                {
                    code = "500",
                    msg = $"处理失败: {ex.Message}"
                };
            }
        }
        /// <summary>
        /// æ›´æ–°å…¥åº“单详细
        /// </summary>
        /// <param name="batchNo">批次号</param>
        /// <param name="productCode">物料名编码/param>
        public void UpdateInboundOrderDetailStatus(string batchNo,string productCode)
        {
            try
            {
                //查询详情
                var detail = BaseDal.Db.Queryable<Dt_CabinOrderDetail>()
                .First(x => x.Goods_no == productCode && x.Batch_num == batchNo && x.OrderDetailStatus == "开始" && x.Status == 1);
                //查找到后根据物料状态(OrderDetailStatus==开始) è¯¥çŠ¶æ€Status=1修改该条详情的OrderDetailStatus==已完成
                detail.OrderDetailStatus = "已完成";
                BaseDal.Db.Updateable(detail).ExecuteCommand();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        ///  //查找到后根据物料状态(OrderDetailStatus==开始) è¯¥çŠ¶æ€Status=1修改该条详情的OrderDetailStatus==已完成
        /// </summary>
        /// <param name="batchNo"></param>
        /// <param name="productCode"></param>
        public void UpdateOutboundOrderDetailStatus(string batchNo, string productCode)
        {
            try
            {
                //查询详情
                var detail = BaseDal.Db.Queryable<Dt_DeliveryOrderDetail>()
                .First(x => x.Goods_no == productCode && x.Batch_num == batchNo && x.OotDetailStatus == "开始" && x.Status == 1);
                detail.OotDetailStatus = "已完成";
                BaseDal.Db.Updateable(detail).ExecuteCommand();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        /// <summary>
        /// æŽ¨é€å¼‚常信息给上游系统1.入库单接口;2.入库单报完成接口;3.出库单接口;4.出库报完成接口;5.药品基础信息同步接口;6.供应商信息接口;7.客户信息接口;8.库存