using ICSSoft.Common; using ICSSoft.Entity; using ICSSoft.Entity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ICSSoft.DataProject { public class OutsourcingSevice { private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static string connString = System.Configuration.ConfigurationManager.AppSettings["ConnStr"]; private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"]; DataTable table = null; DataTable tableInfo = null; SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString); string sql = string.Empty; string sqlInfo = string.Empty; /// /// 委外送货单 /// /// /// public OutsourcingModelInfo Get(OutsourcingModel model) { conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; try { sql = @" select a.ID, a.OASNCode, b.VenCode , b.VenName, a.MUSER, a.MTIME from ICSOASN a left join ICSVendor b on a.VenCode=b.VenCode where 1=1 "; if (!string.IsNullOrEmpty(model.OASNCode)) { sql += " and a.OASNCode={0}"; } if (!string.IsNullOrEmpty(model.User)) { sql += " and a.MUSER={1}"; } if (model.MTime > new DateTime(2000, 01, 01)) { //throw new Exception("请输入正确的操作时间:" + model.MTime); sql += " and a.MTIME={2}"; } sql = string.Format(sql, model.OASNCode, model.User, model.MTime); table = DBHelper.SQlReturnData(sql, cmd); sqlInfo = @"select a.Sequence, a.LotNo, a.Quantity, a.Amount, b.InvCode from ICSOASNDetail a left join ICSInventoryLot b on a.LotNo=b.LotNo where 1=1"; if (!string.IsNullOrEmpty(model.OASNCode)) { sqlInfo += " and a.OASNCode=(select OASNCode from ICSOASN where OASNCode={0} )"; } sqlInfo = string.Format(sqlInfo, model.OASNCode); tableInfo = DBHelper.SQlReturnData(sqlInfo, cmd); string json = JsonConvert.SerializeObject(table); string jsonInfo = JsonConvert.SerializeObject(tableInfo); string jsonList = null; if (table.Rows.Count > 0) { foreach (DataRow item in table.Rows) { OutsourcingModelInfo main = new OutsourcingModelInfo(); main.ID = item["ID"].ToString(); main.User = item["MUSER"].ToString(); main.VenName = item["VenName"].ToString(); main.VenCode = item["VenCode"].ToString(); main.MTime = Convert.ToDateTime(item["MTime"]); List list = new List(); foreach (DataRow dt in tableInfo.Rows) { OutsourcingModelInfos detail = new OutsourcingModelInfos(); detail.LotNO = dt["LotNO"].ToString(); detail.InvCode = dt["InvCode"].ToString(); detail.Quantity = dt["Quantity"].ToString(); detail.Sequence = dt["Sequence"].ToString(); list.Add(detail); } main.detail = list; jsonList = JsonConvert.SerializeObject(main); } var deliveryNotrModelInfo = JsonConvert.DeserializeObject(jsonList); cmd.Transaction.Commit(); return deliveryNotrModelInfo; } return null; } catch (Exception ex) { cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } /// /// 添加 /// /// /// public int Create(List model) { string sqlERP = string.Empty;//ERP的表头 string sqlERPDetil = string.Empty;//ERP的表体 string jsonERP = string.Empty;///erpjson string IstrErp = string.Empty; string iresult = string.Empty;//接口调用 string WorkPoint = string.Empty; string res = string.Empty; conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; int num = 0; Random Rdm = new Random(); int iRdm = Rdm.Next(0, 100); try { foreach (var item in model) { string ISsqlInfos = @"select * from ICSODeliveryNotice where OASNCode='{0}' "; ISsqlInfos = string.Format(ISsqlInfos, item.TransCode); DataTable dataInfos = DBHelper.SQlReturnData(ISsqlInfos, cmd); if (dataInfos.Rows.Count > 0) { throw new Exception("请勿重复到货!"); } foreach (var itemInfo in item.Detail) { WorkPoint = itemInfo.WorkPoint; string ISsql = @"select * from ICSOASN a left join ICSOASNDetail b on a.OASNCode=b.OASNCode where b.LotNo='{0}' and B.WorkPoint='{1}' "; ISsql = string.Format(ISsql, itemInfo.LotNO, itemInfo.WorkPoint); DataTable data = DBHelper.SQlReturnData(ISsql, cmd); if (data.Rows.Count <= 0) { throw new Exception("送货单不存在!"); } else { string ISsqlInfo = @"select * from ICSOASN a left join ICSOASNDetail b on a.OASNCode=b.OASNCode where b.LotNo='{0}' and B.WorkPoint='{1}' and a.Status='2'"; ISsqlInfo = string.Format(ISsqlInfo, itemInfo.LotNO, itemInfo.WorkPoint); DataTable dataInfo = DBHelper.SQlReturnData(ISsqlInfo, cmd); if (dataInfo.Rows.Count <= 0) { throw new Exception("送货单未审核!"); } else { //修改子表 string sql = @"UPDATE ICSOASNDetail set ODNQuantity=(select sum(ODNQuantity) from ICSOASNDetail where LotNo='{0}' and WorkPoint='{1}') +'{2}' where LotNo='{0}' and WorkPoint='{1}' "; sql = string.Format(sql, itemInfo.LotNO, itemInfo.WorkPoint, itemInfo.Quantity); cmd.CommandText = sql; num = cmd.ExecuteNonQuery(); } } } string Date = DateTime.Now.ToString("yy"); string Pre = "ODN" + iRdm + Date; ///添加到到货单表 string sqlInfo = @" INSERT INTO [dbo].[ICSODeliveryNotice]([ID],[ODNCode],[Sequence],[VenCode],[DepCode],[ODNType],[InvCode],[Quantity],[Amount] ,[RCVQuantity],[UnitPrice] ,[Currency],[Status] ,[CreatePerson] ,[CreateDateTime],[POID] ,[PODetailID] ,[ODNID] ,[ODNDetailID] ,[ExtensionID] ,[MUSER] ,[MUSERName] ,[MTIME] ,[WorkPoint] ,[EATTRIBUTE1] ,[OASNCode]) (SELECT NEWID(),'{0}',row_number() OVER (ORDER BY b.InvCode),d.VenCode,d.DepCode,'1',b.InvCode,SUM(a.ODNQuantity),'0','0',d.UnitPrice,d.Currency,'2' ,'{1}',GETDATE(),d.OOID,d.OODetailID,'0','0',b.ExtensionID,'{1}',e.F_RealName,GETDATE(),'{2}','',a.OASNCode FROM ICSOASNDetail a INNER JOIN ICSInventoryLot b ON a.LotNo=b.LotNo AND a.WorkPoint=b.WorkPoint INNER JOIN ICSInventoryLotDetail c ON b.LotNo=c.LotNo AND b.WorkPoint=c.WorkPoint INNER JOIN ICSOutsourcingOrder d ON c.TransCode=d.OOCode AND c.TransSequence=d.Sequence AND c.WorkPoint=d.WorkPoint INNER JOIN Sys_SRM_User e ON e.F_Account='{1}' AND e.F_Location='{2}' WHERE a.OASNCode='{3}' GROUP BY d.OOID,d.OODetailID,d.VenCode,d.UnitPrice,d.Currency,d.DepCode,b.ExtensionID,b.InvCode,a.OASNCode,e.F_RealName) "; sqlInfo = string.Format(sqlInfo, Pre, item.User, WorkPoint, item.TransCode); //sqlInfo = string.Format(sqlInfo, Pre, item.VenCode, itemInfo.DepCode, itemInfo.Amount, itemInfo.Quantity, itemInfo.UnitPrice, itemInfo.Currency, item.User, DateTime.Now, itemInfo.WorkPoint, item.TransCode, itemInfo.Sequence, itemInfo.InvCode); cmd.CommandText = sqlInfo; num = cmd.ExecuteNonQuery(); #region ERP sqlERP = @"select a.VenCode,a.DepCode,b.OOCode,a.MUSER,(getdate())as Mtime from ICSODeliveryNotice a left join ICSOutsourcingOrder b on a.poid = b.OOID and a.PODetailID = b.OODetailID left join ICSOASNDetail c on c.OASNCode = a.OASNCode where a.OASNCode = '{0}'and A.WorkPoint = '{1}' group by a.VenCode,a.DepCode,b.OOCode,a.MUSER"; sqlERP = string.Format(sqlERP, item.TransCode, WorkPoint); table = DBHelper.SQlReturnData(sqlERP, cmd); sqlERPDetil = @"select a.Sequence,a.InvCode,sum(a.RCVQuantity) as Quantity ,a.Amount,isnull((a.UnitPrice),0) as UnitPrice,a.Currency,PODetailID , cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 from ICSODeliveryNotice A left join ICSOutsourcingOrder b on a.poid=b.OOID and a.PODetailID=b.OODetailID left join ICSOASNDetail c on c.OASNCode=a.OASNCode LEFT JOIN ICSExtension d ON A.ExtensionID=B.ID where a.OASNCode='{0}'and A.WorkPoint='{1}' group by a.Sequence,a.InvCode,a.Amount,a.UnitPrice,a.Currency,PODetailID, cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10 "; sqlERPDetil = string.Format(sqlERPDetil, item.TransCode, WorkPoint); DataTable ERPtable = DBHelper.SQlReturnData(sqlERPDetil, cmd); List docmodel = new List(); foreach (DataRow dtIn in table.Rows) { ERPDeliveryNotice doc = new ERPDeliveryNotice(); doc.VenCode = dtIn["VenCode"].ToString(); doc.DepCode = dtIn["DepCode"].ToString(); doc.OOCode = dtIn["OOCode"].ToString(); doc.User = dtIn["MUSER"].ToString(); doc.MTime = dtIn["Mtime"].ToString(); List list = new List(); foreach (DataRow dtList in ERPtable.Rows) { ERPDeliveryNoticeList docc = new ERPDeliveryNoticeList(); docc.Sequence = dtList["Sequence"].ToString(); docc.InvCode = dtList["InvCode"].ToString(); docc.Quantity = dtList["Quantity"].ToString(); docc.Amount = dtList["Amount"].ToString(); docc.Currency = dtList["Currency"].ToString(); docc.UnitPrice = dtList["UnitPrice"].ToString(); docc.OODetailID = dtList["PODetailID"].ToString(); docc.cFree1 = dtList["cFree1"].ToString(); docc.cFree2 = dtList["cFree2"].ToString(); docc.cFree3 = dtList["cFree3"].ToString(); docc.cFree4 = dtList["cFree4"].ToString(); docc.cFree5 = dtList["cFree5"].ToString(); docc.cFree6 = dtList["cFree6"].ToString(); docc.cFree7 = dtList["cFree7"].ToString(); docc.cFree8 = dtList["cFree8"].ToString(); docc.cFree9 = dtList["cFree9"].ToString(); docc.cFree10 = dtList["cFree10"].ToString(); list.Add(docc); } doc.details = list; docmodel.Add(doc); } IstrErp = JsonConvert.SerializeObject(docmodel); log.Info("委外到货ERPJSON" + IstrErp); iresult = HttpPost("委外到货", ERPUrl.ODeliveryNoticeURL, IstrErp); Result OtherOutResult = new Result(); OtherOutResult = JsonConvert.DeserializeObject(iresult); if (OtherOutResult.Success == false) { throw new Exception(OtherOutResult.Message); } else { List list = new List(); //string nn = OtherOutResult.Data.ToString();//LOTStockModel list = JsonConvert.DeserializeObject>(OtherOutResult.Data.ToString()); foreach (var items in list) { string ERPupdate = @"update ICSODeliveryNotice set ODNCode='{0}',Sequence='{1}',ODNID='{2}',ODNDetailID='{3}',ODNType='1' where OASNCode='{4}' "; ERPupdate = string.Format(ERPupdate, items.ODNCode, items.Sequence, items.ID, items.DetailID, item.TransCode, DateTime.Now); cmd.CommandText = ERPupdate; num = cmd.ExecuteNonQuery(); } } #endregion } num = cmd.ExecuteNonQuery(); if (num > 0) { cmd.Transaction.Commit(); } else { cmd.Transaction.Rollback(); } return num; } catch (Exception ex) { // cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } /// /// 删除委外数据(物理删除) /// /// /// public string Delete(NoticeDelete model) { string res = string.Empty; conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; try { //委外送货详情表删除 sql = @" DELETE FROM ICSOASNDetail WHERE OASNCode=(select OASNCode from ICSOASN where id='{0}') "; sqlInfo = @" DELETE FROM ICSOASN where 1=1 "; if (model.ID != null) { sqlInfo += " and id='{0}'"; } if (model.MTime != null) { sqlInfo += " and MTIME='{1}'"; } if (model.User != null) { sqlInfo += " and MUSER='{2}'"; } sql = string.Format(sql, model.ID); sqlInfo = string.Format(sqlInfo, model.ID, model.MTime, model.User); DBHelper.CmdExecuteNonQuery(sql, cmd, "送货单:" + model.ID + "未查询到对应数据!"); DBHelper.CmdExecuteNonQuery(sqlInfo, cmd, "送货单:" + model.ID + "未查询到对应数据!"); cmd.Transaction.Commit(); return res; } catch (Exception ex) { cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } #region 接口调用 public static string HttpPost(string apiName, string url, string body) { try { Encoding encoding = Encoding.UTF8; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*"; request.ContentType = "application/json; charset=utf-8"; byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (System.Net.WebException ex) { throw new Exception(apiName + "调用失败," + ex.Message); } } #endregion } }