yanjinhui
2025-10-20 614945e153d38d1dadf5beb1e1d4dbc6db07c226
н¨Îļþ¼Ð/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,100 +80,170 @@
        }
        /// <summary>
        /// wcs回传给我调用我的方法
        /// wcs回传给我调用我的方法 ä¸ç®¡æ˜¯å…¥åº“ å‡ºåº“ ç›˜ç‚¹éƒ½ä¼šè°ƒç”¨è¿™ä¸ªæŽ¥å£
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ApiResponse<Dt_Inventory> OrderFeedback(EdiOrderCallbackRequest request)
        public ApiResponse<Dt_InventoryInfo> OrderFeedback(EdiOrderCallbackRequest request)
        {
            try
            {
                // 1️⃣ æ ¡éªŒè¯·æ±‚
                if (request == null || request.details == null || !request.details.Any())
                {
                    return new ApiResponse<Dt_Inventory> { code = "500", msg = "请求参数无效" };
                    return new ApiResponse<Dt_InventoryInfo> { 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);
                    //将集合中的数量进行累加
                    // å®‰å…¨è½¬æ¢
                     var goods = Db.Queryable<Dt_MaterielInfo>().Where(x => x.MaterielCode == detail.productCode).First();
                    //正常出入库
                    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;
                    // 3️⃣ è®¡ç®—入库数量(取正)
                    decimal orderQty = detail.orderDetails?
                        .Sum(x => decimal.TryParse(x.quantity, out var q) ? Math.Abs(q) : 0)
                        ?? 0;
                    // 5️⃣ æŸ¥è¯¢åº“存详情
                    var entity = BaseDal.Db.Queryable<Dt_InventoryInfo>()
                        .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_Inventory
                        entity = new Dt_InventoryInfo
                        {
                            Goods_no = detail.productCode ?? detail.productName,
                            Reservoirarea = "默认库区",
                            Batch_num = detail.batchNo,
                            //业务库存
                            Business_qty = 0,
                            //实际库存
                            Actual_qty = 0
                            PalletCode = detail.orderDetails?.FirstOrDefault()?.palletCode ?? "",
                            WarehouseCode = "001",
                            LocationCode = "立库",
                            StockStatus = 1,
                            MaterielCode = detail.productCode ?? detail.productName,
                            MaterielName = detail.productName ?? "",
                            MaterielSpec = detail.productSpecifications ?? "",
                            BatchNo = detail.batchNo,
                            StockQuantity = 0,
                            OutboundQuantity = 0,
                            SupplyQuantity = 0,
                            InDate = DateTime.Now,
                            ProductionDate = detail.finishDate.ToString("yyyy-MM-dd"),
                            ShelfLife = 0,
                            ValidityPeriod = "",
                            Remark = "WCS回传创建"
                        };
                    }
                    // 6️⃣ æŸ¥è¯¢åº“存批次信息
                    var batch = BaseDal.Db.Queryable<Dt_Inventory_Batch>()
                        .First(x => x.MaterielCode == detail.productCode && x.BatchNo == detail.batchNo);
                    if (batch == null)
                    {
                        batch = new Dt_Inventory_Batch
                        {
                            MaterielCode = detail.productCode ?? detail.productName,
                            MaterielName = detail.productName ?? "",
                            MaterielSpec = detail.productSpecifications ?? "",
                            BatchNo = detail.batchNo,
                            StockQuantity = 0,
                            OutboundQuantity = 0,
                            SupplyQuantity = 0,
                            ERPStockQuantity = 0,
                            Status = false,
                            ProductionDate = detail.finishDate.ToString("yyyy-MM-dd"),
                            ValidityPeriod = DateTime.Now.AddYears(1).ToString("yyyy-MM-dd"),
                            Remark = "自动创建"
                        };
                    }
                    // 7️⃣ æŒ‰è®¢å•类型执行不同逻辑
                    switch (request.orderType)
                    {
                        case "1": // å…¥åº“
                            entity.Business_qty += orderQty;
                            entity.Actual_qty += orderQty;
                        case "1": //入库
                            entity.StockQuantity += orderQty;
                            entity.InDate = DateTime.Now;
                            entity.Remark = "入库单回传";
                            //Goods.Business_qty=
                            batch.StockQuantity += orderQty;
                            batch.Remark = "入库单回传";
                            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;
                            entity.OutboundQuantity += orderQty; //出库数量
                            entity.StockQuantity -= orderQty;
                            if (entity.StockQuantity < 0) entity.StockQuantity = 0;
                            entity.Remark = "出库单回传";
                            //CreateAllocatInOut()
                            batch.OutboundQuantity += orderQty;
                            batch.StockQuantity -= orderQty;
                            if (batch.StockQuantity < 0) batch.StockQuantity = 0;
                            batch.Remark = "出库单回传";
                            //调拨任务
                            _deliveryOrderServices.CreateAllocatInOut(goods);
                            break;
                        case "3": // ç›˜ç‚¹
                            if (detail.stocktakingDetails != null && detail.stocktakingDetails.Any())
                            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.Business_qty += diff;//如果盘盈了多了,就将业务数量+,盘亏则相反
                                        entity.PalletCode = stock.palletCode;
                                    }
                                    else // ç›˜äº
                                    {
                                        entity.Business_qty -= diff;
                                        entity.PalletCode = stock.palletCode;
                                    }
                                }
                                batch.SupplyQuantity = batch.StockQuantity - diff;
                                batch.Remark = "盘点单回传 - ç›˜äº";
                            }
                            else if (flag == 2) // ç›˜ç›ˆ
                            {
                                batch.SupplyQuantity = batch.StockQuantity + diff;
                                batch.Remark = "盘点单回传 - ç›˜ç›ˆ";
                            }
                            else // ç›˜ä¸­
                            {
                                batch.Remark = "盘点单回传 - ç›˜ä¸­";
                            }
                            break;
                    }
                    // ä¿å­˜æ•°æ®
                    if (entity.Id == 0) // æ–°å»º
                    // 2️⃣ å¼€å¯äº‹åŠ¡
                    BaseDal.Db.Ado.BeginTran();
                    // 8️⃣ ä¿å­˜æ•°æ®
                    if (entity.Id == 0)
                        BaseDal.Db.Insertable(entity).ExecuteCommand();
                    else // æ›´æ–°
                    else
                        BaseDal.Db.Updateable(entity).ExecuteCommand();
                    if (batch.Id == 0)
                        BaseDal.Db.Insertable(batch).ExecuteCommand();
                    else
                        BaseDal.Db.Updateable(batch).ExecuteCommand();
                }
                BaseDal.Db.Ado.CommitTran(); // æäº¤äº‹åŠ¡
                return new ApiResponse<Dt_Inventory> { code = "0", msg = "成功" };
                // 9️⃣ æäº¤äº‹åŠ¡
                BaseDal.Db.Ado.CommitTran();
                return new ApiResponse<Dt_InventoryInfo>
                {
                    code = "0",
                    msg = "成功"
                };
            }
            catch (Exception ex)
            {
                BaseDal.Db.Ado.RollbackTran();//回滚事务
                return new ApiResponse<Dt_Inventory> { code = "500", msg = ex.Message };
                // ðŸ”Ÿ å›žæ»šäº‹åŠ¡
                BaseDal.Db.Ado.RollbackTran();
                return new ApiResponse<Dt_InventoryInfo>
                {
                    code = "500",
                    msg = $"处理失败: {ex.Message}"
                };
            }
        }