南骏 池
2025-05-19 07a9b9127da141cbc8afcb2932ed31208cf31af1
1.携客云送货单异常处理优化
已修改4个文件
391 ■■■■■ 文件已修改
Controllers/Warehouse/MesXkyController.cs 23 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
entity/DeliveryNoticeDetail.cs 14 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
entity/TblBarcodeInformation.cs 15 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
service/Warehouse/MesXkyService.cs 339 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
Controllers/Warehouse/MesXkyController.cs
@@ -20,7 +20,7 @@
        public string? erpCode { get; set; }
    }
    //到货单明细json
    //到货单明细json 和 到货单条码
    public class XKYGetDhdDeatilRequest
    {
        public string? deliveryNo { get; set; }
@@ -71,4 +71,25 @@
        }
    }
    [HttpPost("GetXkyDhdBar")]
    public ResponseResult GetXkyDhdBar(XKYGetDhdDeatilRequest request)
    {
        try
        {
            dynamic resultInfos = new ExpandoObject();
            resultInfos = m.GetXkyDhdBar(request);
            var tbBillList = resultInfos;
            return new ResponseResult
            {
                status = 0,
                message = "OK",
                data = tbBillList
            };
        }
        catch (Exception ex)
        {
            return ResponseResult.ResponseError(ex);
        }
    }
}
entity/DeliveryNoticeDetail.cs
@@ -12,7 +12,7 @@
    /// 主键Guid(SEQ_XKY)
    /// </summary>
    [SugarColumn(ColumnName = "id")]
    public string Id { get; set; }
    public Guid Id { get; set; }
    /// <summary>
    /// 项次号
@@ -433,4 +433,16 @@
    /// </summary>
    [SugarColumn(ColumnName = "plan_line_no")]
    public string PlanLineNo { get; set; }
    /// <summary>
    /// 送货单号
    /// </summary>
    [SugarColumn(ColumnName = "delivery_no")]
    public string DeliveryNo { get; set; }
    /// <summary>
    /// 同步时间
    /// </summary>
    [SugarColumn(ColumnName = "SYNCHRONOUS_DATE")]
    public DateTime? SynchronousDate { get; set; }
}
entity/TblBarcodeInformation.cs
@@ -13,7 +13,7 @@
    /// 主键Guid(SEQ_XKY)
    /// </summary>
    [SugarColumn(ColumnName = "id", IsPrimaryKey = true)]
    public string Id { get; set; }
    public Guid Id { get; set; }
    /// <summary>
    /// 产品编码
@@ -118,12 +118,6 @@
    public string OutPackageSn { get; set; }
    /// <summary>
    /// 条码规则中对应的动态字段的值
    /// </summary>
    [SugarColumn(ColumnName = "dynamic_data")]
    public string DynamicData { get; set; }
    /// <summary>
    /// 包装层级
    /// </summary>
    [SugarColumn(ColumnName = "pack_level")]
@@ -176,4 +170,11 @@
    /// </summary>
    [SugarColumn(ColumnName = "customize1")]
    public string Customize1 { get; set; }
    /// <summary>
    /// 同步时间
    /// </summary>
    [SugarColumn(ColumnName = "SYNCHRONOUS_DATE")]
    public DateTime? SynchronousDate { get; set; }
}
service/Warehouse/MesXkyService.cs
@@ -29,8 +29,9 @@
    /// <summary>
    /// 系统自动日志模板(用于携客云接口调用记录)
    /// </summary>
    private string _logMessageDhdBar = "【SysAuto】获取携客云送货单条码。";
    private string _logMessageDhdBar = "";
    //获取携客云到货单
    public dynamic GetXkyDhd(XKYGetDhdRequest entity)
    {
        _logMessageDHD = "【SysAuto】获取携客云送货单。";
@@ -93,53 +94,11 @@
                _responseData = JsonConvert.DeserializeObject(result2);
            }
            //// 新增日志记录(在返回响应前)
            //using (var conn = new SqlConnection(DbHelperSQL.strConn))
            //{
            //    using (var cmd = new SqlCommand("prc_log_create", conn))
            //    {
            //        try
            //        {
            //            conn.Open();
            //            cmd.CommandType = CommandType.StoredProcedure;
            //            SqlParameter[] logParams =
            //            {
            //                new("@edtUserGuid", SqlDbType.UniqueIdentifier) { Value = Guid.Parse("11111111-1111-1111-1111-111111111111") },
            //                new("@abtGuid", SqlDbType.UniqueIdentifier) { Value = DBNull.Value },
            //                new("@abtTable", SqlDbType.NVarChar, 40) { Value = "DELIVERY_NOTICE" },
            //                new("@detail", SqlDbType.NVarChar, 2500) { Value = "【SysAuto】获取携客云送货单。" },
            //                new("@hNo", SqlDbType.NVarChar, 100) { Value = "" },
            //                new("@SendJson", SqlDbType.NVarChar) { Value = json },
            //                new("@RtnJson", SqlDbType.NVarChar) { Value = JsonConvert.SerializeObject(responseJson) },
            //                new("@xkyBeginTime", SqlDbType.NVarChar) { Value = (entity.startDate/1000).ToString() },
            //                new("@xkyEndTime", SqlDbType.NVarChar) { Value = (entity.endDate/1000).ToString()},
            //                new("@sendStatus", SqlDbType.NVarChar) { Value = responseJson.result.ToString()},
            //                new("@executeTime", SqlDbType.NVarChar) { Value =  executeTime},
            //            };
            //            foreach (var param in logParams)
            //                cmd.Parameters.Add(param);
            //            cmd.ExecuteNonQuery();
            //        }
            //        catch (Exception logEx)
            //        {
            //            // 日志记录失败不中断主流程
            //            Console.WriteLine($"日志记录失败: {logEx.Message}");
            //        }
            //        finally
            //        {
            //            conn.Close();
            //        }
            //    }
            //}
            if (_responseData.result != 1)
                throw new ApplicationException(_responseData.errorMsg);
            sendStatus = _responseData.result;
            // 原120-131行替换为:
            //储存送货单号详细
            if (SaveDeliveryNotice(_responseData) > 0)
                sendStatus = 1;
            else
@@ -171,7 +130,7 @@
                edtUserGuid: Guid.Parse("11111111-1111-1111-1111-111111111111"),
                abtGuid: null,
                abtTable: "DELIVERY_NOTICE",
                detail: _logMessageDHD,
                detail: _logMessageDHD+ $"系统异常错误:{e.Message}\n跟踪:{e.StackTrace}",
                orderNo: "",
                sendJson: _requestJson,
                rtnJson: JsonConvert.SerializeObject(_responseData),
@@ -185,34 +144,36 @@
    }
    //public dynamic GetXkyDHD(XKYGetDhdRequest entity)
    //{
    //   return XKY_GET_DHD(entity);
    //}
    //对获取到的携客云送货单做处理
    private int SaveDeliveryNotice(dynamic responseJson)
    {
        var result = 1;
        List<DeliveryNotice> noticeList = JsonConvert.DeserializeObject<List<DeliveryNotice>>(responseJson.dataList.ToString());
        // 新增列表空值检查
        if (noticeList == null || !noticeList.Any() || noticeList.Count < 1)
        {
            _logMessageDhdBar += $"本次获取收货单数据为空";
            return result;
        }
        noticeList.ForEach(n => n.Id = Guid.NewGuid());
    
        var deliveryNos = noticeList.Select(n => n.DeliveryNo).Distinct().ToList();
        var noticeIds = noticeList.Select(n => n.Id).ToList(); // 保持GUID类型
        //var noticeIds = noticeList.Select(n => n.Id).ToList(); // 保持GUID类型
        var result = 0;
        Db.Ado.UseTran(() =>
        {
            // 删除关联送货明细数据
            Db.Deleteable<DeliveryNoticeDetail>()
            .Where(d => noticeIds.Contains(Guid.Parse(d.Pid)))
              .ExecuteCommand();
            // 添加空值检查
            if (deliveryNos.Any())
            {
                // 删除关联送货明细数据
                Db.Deleteable<DeliveryNoticeDetail>()
                .Where(d => deliveryNos.Contains(d.DeliveryNo))
                  .ExecuteCommand();
                //删除关联送货条码明细
                Db.Deleteable<TblBarcodeInformation>()
                  .Where(b => deliveryNos.Contains(b.DeliveryNo))
@@ -229,8 +190,8 @@
        }, 
        ex => {
            // 增强异常信息
            _logMessageDHD = _logMessageDHD + $"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}";
            //throw new Exception($"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}");
            //_logMessageDHD = _logMessageDHD + $"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}";
            throw new Exception($"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}");
        });
        return result;
@@ -297,65 +258,23 @@
                _responseData = JsonConvert.DeserializeObject(result2);
            }
            //// 新增日志记录(在返回响应前)
            //using (var conn = new SqlConnection(DbHelperSQL.strConn))
            //{
            //    using (var cmd = new SqlCommand("prc_log_create", conn))
            //    {
            //        try
            //        {
            //            conn.Open();
            //            cmd.CommandType = CommandType.StoredProcedure;
            //            SqlParameter[] logParams =
            //            {
            //                new("@edtUserGuid", SqlDbType.UniqueIdentifier) { Value = Guid.Parse("11111111-1111-1111-1111-111111111111") },
            //                new("@abtGuid", SqlDbType.UniqueIdentifier) { Value = DBNull.Value },
            //                new("@abtTable", SqlDbType.NVarChar, 40) { Value = "DELIVERY_NOTICE" },
            //                new("@detail", SqlDbType.NVarChar, 2500) { Value = "【SysAuto】获取携客云送货单。" },
            //                new("@hNo", SqlDbType.NVarChar, 100) { Value = "" },
            //                new("@SendJson", SqlDbType.NVarChar) { Value = json },
            //                new("@RtnJson", SqlDbType.NVarChar) { Value = JsonConvert.SerializeObject(responseJson) },
            //                new("@xkyBeginTime", SqlDbType.NVarChar) { Value = (entity.startDate/1000).ToString() },
            //                new("@xkyEndTime", SqlDbType.NVarChar) { Value = (entity.endDate/1000).ToString()},
            //                new("@sendStatus", SqlDbType.NVarChar) { Value = responseJson.result.ToString()},
            //                new("@executeTime", SqlDbType.NVarChar) { Value =  executeTime},
            //            };
            //            foreach (var param in logParams)
            //                cmd.Parameters.Add(param);
            //            cmd.ExecuteNonQuery();
            //        }
            //        catch (Exception logEx)
            //        {
            //            // 日志记录失败不中断主流程
            //            Console.WriteLine($"日志记录失败: {logEx.Message}");
            //        }
            //        finally
            //        {
            //            conn.Close();
            //        }
            //    }
            //}
            if (_responseData.result != 1)
                throw new ApplicationException(_responseData.errorMsg);
            sendStatus = _responseData.result;
            // 原120-131行替换为:
            //if (SaveDeliveryNotice(_responseData) > 0)
            //    sendStatus = 1;
            //else
            //    sendStatus = 0;
            // 对数据做处理存入mes
            if (SaveDeliveryNoticeDetail(_responseData) > 0)
                sendStatus = 1;
            else
                sendStatus = 0;
            var logService = new LogService();
            logService.CreateLogI(
                db: Db,
                edtUserGuid: Guid.Parse("11111111-1111-1111-1111-111111111111"),
                abtGuid: null,
                abtTable: "DELIVERY_NOTICE",
                detail: _logMessageDHD,
                abtTable: "DELIVERY_NOTICE_DETAIL",
                detail: _logMessageDhdDetail,
                orderNo: "",
                sendJson: _requestJson,
                rtnJson: JsonConvert.SerializeObject(_responseData),
@@ -374,8 +293,8 @@
                db: Db,
                edtUserGuid: Guid.Parse("11111111-1111-1111-1111-111111111111"),
                abtGuid: null,
                abtTable: "DELIVERY_NOTICE",
                detail: _logMessageDHD,
                abtTable: "DELIVERY_NOTICE_DETAIL",
                detail: _logMessageDhdDetail,
                orderNo: "",
                sendJson: _requestJson,
                rtnJson: JsonConvert.SerializeObject(_responseData),
@@ -389,4 +308,198 @@
    }
    //对获取到的携客云送货单做处理
    private int SaveDeliveryNoticeDetail(dynamic responseJson)
    {
        var result = 0;
        List<DeliveryNoticeDetail> noticeList = JsonConvert.DeserializeObject<List<DeliveryNoticeDetail>>(responseJson.data.lineList.ToString());
        // 获取送货单号并校验
        var deliveryNoObj = responseJson.data.deliveryNo;
        if (deliveryNoObj == null || string.IsNullOrEmpty(deliveryNoObj.ToString()))
        {
            _logMessageDhdDetail += $"【异常】获取送货单失败:{responseJson}";
            return result;
        }
        string deliveryNo = deliveryNoObj.ToString();
        // 新增列表空值检查
        if (noticeList == null || !noticeList.Any())
        {
            _logMessageDhdBar += $"【异常】送货明细数据为空,送货单号:{deliveryNo}";
            return result;
        }
        //赋值guid和到货单号
        noticeList.ForEach(n => n.Id = Guid.NewGuid());
        noticeList.ForEach(n => n.DeliveryNo = deliveryNo);
        noticeList.ForEach(n => n.SynchronousDate = DateTime.Now);
        Db.Ado.UseTran(() =>
        {
            // 删除关联送货明细数据
            Db.Deleteable<DeliveryNoticeDetail>()
            .Where(d => d.DeliveryNo == deliveryNo)
              .ExecuteCommand();
            // 批量插入优化
            result = Db.Fastest<DeliveryNoticeDetail>().BulkCopy(noticeList);
        },
        ex => {
            // 增强异常信息
            _logMessageDhdDetail = _logMessageDhdDetail + $"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}";
            //throw new Exception($"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}");
        });
        return result;
    }
    //获取携客云到货单条码
    public dynamic GetXkyDhdBar(XKYGetDhdDeatilRequest entity)
    {
        _logMessageDhdBar = "【SysAuto】获取携客云送货单条码。";
        /// <summary>
        /// 请求报文缓存(存储序列化后的JSON请求内容)
        /// </summary>
        string _requestJson = string.Empty;
        /// <summary>
        /// 动态响应对象(存储反序列化的携客云接口响应)
        /// </summary>
        dynamic _responseData = new System.Dynamic.ExpandoObject();
        /// <summary>
        /// 接口执行时间(格式:yyyy-MM-dd HH:mm:ss)
        /// </summary>
        string _executeTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        /// <summary>
        /// 接口调用状态(0-失败 1-成功)
        /// </summary>
        int sendStatus = 0;
        try
        {
            string ErrorMsg = "";
            ApiCommonParam Apiparam = ApiCommonParam.NewApiCommon();
            _executeTimestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string sendJson = JsonConvert.SerializeObject(entity);
            ArrayList SQLStringList = new ArrayList();
            var url = "https://openapi.xiekeyun.com/barcode/byDeliveryNo.json";
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            _requestJson = "{\"commonParam\":" + JsonConvert.SerializeObject(Apiparam) + ",\"body\":" + sendJson + "}";
            byte[] postData = Encoding.UTF8.GetBytes(_requestJson);
            // 创建请求对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = postData.Length;
            // 发送请求数据
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(postData, 0, postData.Length);
            }
            // 发送请求并获取响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                string result2 = reader.ReadToEnd();
                _responseData = JsonConvert.DeserializeObject(result2);
            }
            if (_responseData.result != 1)
                throw new ApplicationException(_responseData.errorMsg);
            sendStatus = _responseData.result;
            // 对数据做处理存入mes
            if (SaveDeliveryNoticeBar(_responseData, entity.deliveryNo) > 0)
                sendStatus = 1;
            else
                sendStatus = 0;
            var logService = new LogService();
            logService.CreateLogI(
                db: Db,
                edtUserGuid: Guid.Parse("11111111-1111-1111-1111-111111111111"),
                abtGuid: null,
                abtTable: "TBL_BARCODE_INFORMATION",
                detail: _logMessageDhdBar,
                orderNo: "",
                sendJson: _requestJson,
                rtnJson: JsonConvert.SerializeObject(_responseData),
                xkyBeginTime: "",
                xkyEndTime: "",
                sendStatus: sendStatus,
                executeTime: _executeTimestamp
            );
            return _responseData;
        }
        catch (Exception e)
        {
            var logService = new LogService();
            logService.CreateLogI(
                db: Db,
                edtUserGuid: Guid.Parse("11111111-1111-1111-1111-111111111111"),
                abtGuid: null,
                abtTable: "TBL_BARCODE_INFORMATION",
                detail: _logMessageDhdBar,
                orderNo: "",
                sendJson: _requestJson,
                rtnJson: JsonConvert.SerializeObject(_responseData),
                xkyBeginTime: "",
                xkyEndTime: "",
                sendStatus: 0,
                executeTime: _executeTimestamp
            );
            throw new Exception(e.Message);
        }
    }
    //对获取到的携客云送货单条码做处理
    private int SaveDeliveryNoticeBar(dynamic responseJson,string deliveryNo)
    {
        var result = 0;
        List<TblBarcodeInformation> noticeList = JsonConvert.DeserializeObject<List<TblBarcodeInformation>>(responseJson.dataList.ToString());
        // 新增列表空值检查
        if (noticeList == null || !noticeList.Any())
        {
            _logMessageDhdBar += $"【异常】条码数据为空,送货单号:{deliveryNo}";
            return result;
        }
        // 赋值guid和到货单号
        noticeList.ForEach(n => n.Id = Guid.NewGuid());
        noticeList.ForEach(n => n.DeliveryNo = deliveryNo);
        noticeList.ForEach(n => n.SynchronousDate = DateTime.Now);
        Db.Ado.UseTran(() =>
        {
            // 删除关联送货明细数据
            Db.Deleteable<TblBarcodeInformation>()
            .Where(d => d.DeliveryNo == deliveryNo)
              .ExecuteCommand();
            // 批量插入优化
            result = Db.Fastest<TblBarcodeInformation>().BulkCopy(noticeList);
        },
        ex => {
            // 增强异常信息
            _logMessageDhdBar = _logMessageDhdBar + $"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}";
            //throw new Exception($"数据库操作失败:{ex.Message}\n跟踪:{ex.StackTrace}");
        });
        return result;
    }
}