using ICSSoft.Entity; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using Newtonsoft.Json; using System.Linq; using System.Text; using System.Threading.Tasks; using ICSSoft.Common; namespace ICSSoft.DataProject { public class CreatePOArrive { private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"]; private static string ConnStr = System.Configuration.ConfigurationManager.AppSettings["ConnStr"]; private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"]; private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"]; //参数示例 //[{ // "ASNNO": "DN510852000001", // "WHCode": "11", // "User": "CC001", // "MTime": "2021-08-26 17:20:13", // "details": [ // { // "LOTNO": "PO200219004100005", // "ReceiveQty": "2" // },{ // "LOTNO": "PO200219004100001", // "ReceiveQty": "1" // } // ] //}] //返回参数 //{ //"Success": true, //"Message": "接口调用成功!", //"Data": null //} public string Get(List infos) { List szJson = new List(); DataTable dt = null; DataTable dtNew = null; string json = ""; string connS = ""; if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string res = string.Empty; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; List result = infos.Select(t => t.WorkPoint).Distinct().ToList(); foreach (string WorkPoint in result) { try { connS = string.Format(connString, WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; foreach (ICSPOArrive info in infos) { if (WorkPoint != info.WorkPoint) { continue; } ICSUserInfo userInfo = new ICSUserInfo(); userInfo = DBHelper.GetPersonInfo(info.User, cmd); if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); sql = @" SELECT A.ID,A.cCode,A.cVenCode,D.cVenName,C.CDEPNAME,A.cDepCode,C.cDepName,A.cpocode,A.cMaker,A.cMakeTime,A.cverifier,A.caudittime, B.Autoid,B.irowno ,B.cInvCode ,B.INUM,B.iQuantity,B.fValidInQuan,B.iPOsID FROM PU_ArrivalVouch A INNER JOIN PU_ArrivalVouchs B ON A.ID=B.ID INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and A.iBillType=0"; if (!string.IsNullOrWhiteSpace(info.DNCode)) { sql += " and a.cCode='{0}'"; } if (!string.IsNullOrWhiteSpace(info.MTime.ToString())) { sql += " and ISNULL(a.cModifyTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime)))>='{1}'"; } if (!string.IsNullOrWhiteSpace(info.User)) { sql += "and a.CMAKER='{2}'"; } sql = string.Format(sql, info.DNCode, info.MTime, userInfo.UserName); dt = DBHelper.SQlReturnData(sql, cmd); if (dtNew == null) dtNew = dt; else dtNew.Merge(dt); } cmd.Transaction.Commit(); } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } json = JsonConvert.SerializeObject(dtNew); return json; } /// /// 生成到货单 /// /// /// public string Create(List infos) { string connS = ""; string sql = string.Empty; if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string res = string.Empty; VouchKey key = new VouchKey(); SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); List result = infos.Select(t => t.WorkPoint).Distinct().ToList(); foreach (string WorkPoint in result) { try { connS = string.Format(connString, WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; foreach (ICSPOArrive info in infos) { if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); string Lotnos = ""; foreach (var detail in info.details) { sql = @"IF EXISTS(SELECT LOTNO FROM ICSASNDETAIL WHERE LOTNO='{1}' AND STNO='{2}' AND ISNULL(RECEIVEQTY,0)>0) and WorkPoint='{3}' RAISERROR('条码:{1},已到货不能重复到货!',16,1) UPDATE ICSASNDETAIL SET RECEIVEQTY=ISNULL(RECEIVEQTY,0)+{0} WHERE LOTNO='{1}' AND STNO='{2}' and WorkPoint='{3}' --IF EXISTS(SELECT LOTNO FROM ICSASNDETAIL WHERE LOTNO='{1}' AND STNO='{2}' AND RECEIVEQTY>PLANQTY) -- RAISERROR('条码:{1},到货数量不能大于送货数量!',16,1)"; sql = string.Format(sql, detail.Quantity, detail.LOTNO, info.ASNNO, info.WorkPoint); DBHelper.CmdExecuteNonQuery(sql, cmd, "送货单号:" + info.ASNNO + ",条码:" + detail.LOTNO + "未查询到对应数据!"); Lotnos += "'" + detail.LOTNO + "',"; } if (string.IsNullOrWhiteSpace(Lotnos)) throw new Exception("送货单号:" + info.ASNNO + ",无条码信息!"); CreatePUArrive(infos); } cmd.Transaction.Commit(); } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } return res; } /// /// 回写U8到货单, /// /// /// /// public string CreatePUArrive(List Bills) { string res = string.Empty; string connS = ""; string str = ""; string iFatherIdTwo = ""; DataSet ds = null; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); int num = 0; //int iBaseCodeLen = Convert.ToInt32(dic["iBaseCodeLen"].ToString()); //int cVouchCodeBase = Convert.ToInt32(dic["cVouchCodeBase"].ToString()); List datas = new List(); string sql = ""; List result = Bills.Select(t => t.WorkPoint).Distinct().ToList(); foreach (string WorkPoint in result) { try { connS = string.Format(connString, WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; foreach (ICSPOArrive head in Bills) { iFatherIdTwo = ""; if (WorkPoint != head.WorkPoint) { continue; } ICSUserInfo userInfo = new ICSUserInfo(); userInfo = DBHelper.GetPersonInfo(head.User, cmd); if (!DBHelper.IsInventoryConsolidation(cmd, head.WorkPoint)) throw new Exception("U8正在整理现存量,请稍后再试"); num = head.details.Count(); string[] ss = head.WorkPoint.Split('_'); ERPDB = ss[1]; DateTime time = DateTime.Now; Dictionary dic = DBHelper.GetAllCode("" + ERPDB + "", "PuArrival", "" + num + "", head.WorkPoint, cmd); int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString()); int iChildId = Convert.ToInt32(dic["iChildId"].ToString()); DateTime date = DateTime.Now; string iBaseCodeLen = DBHelper.GetAllRDCode("26", "" + time + "", "admin", "", head.WorkPoint, cmd); string DEF_ID = DBHelper.GetDefaultTemplate(Type, cmd); #region 主表 sql = @"INSERT INTO dbo.PU_ArrivalVouch (iVTid, ID, cCode, cPTCode, dDate, cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, iExchRate, iTaxRate, cMemo, cBusType, cMaker, bNegative, iDiscountTaxType, iBillType, cMakeTime, cAuditDate, caudittime, cverifier, iverifystateex, IsWfControlled, iflowid, iPrintCount, cpocode) SELECT top 1 @iVTid, @ID, @cCode, cPTCode, CONVERT(NVARCHAR(10), GETDATE(), 23), cVenCode, cDepCode, cPersonCode, cPayCode, cexch_name, nflat, iTaxRate, cMemo, '普通采购', @User, 0, iDiscountTaxType, 0, GETDATE(), CONVERT(NVARCHAR(10), GETDATE(), 23), GETDATE(), @User, 2, 0, 0, iPrintCount, cPOID FROM PO_Pomain WHERE 1=1 AND cPOID = @POID "; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqlParameter("@iVTid", DEF_ID)); cmd.Parameters.Add(new SqlParameter("@ID", iFatherId)); cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen)); cmd.Parameters.Add(new SqlParameter("@User", userInfo.UserName)); cmd.Parameters.Add(new SqlParameter("@POID", head.POCode)); //cmd.Parameters.Add(new SqlParameter("@dDate", data.dMate)); cmd.CommandText = sql; try { int count = cmd.ExecuteNonQuery(); if (count <= 0) { log.Error("生成采购到货单表头失败,受影响行数<=0;"); throw new Exception("生成采购到货单表头失败,受影响行数<=0;"); } } catch (Exception ex) { log.Error("生成采购到货单表头失败!采购订单号:" + head.POCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex); throw new Exception("生成采购到货单表头失败!采购订单号:" + head.POCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex); } #endregion #region 子表 foreach (ICSPODetail body in head.details) { int iMassDate = 0; int cMassUnit = 0; sql = @"SELECT cInvCode, ISNULL(iMassDate, 0) iMassDate, ISNULL(cMassUnit, 0) cMassUnit FROM Inventory WHERE cInvCode = '{0}' "; sql = string.Format(sql, body.InvCode); DataTable dts = DBHelper.SQlReturnData(sql, cmd); if (dts.Rows.Count == 0) { log.Error("存货档案不存在"); throw new Exception("存货档案不存在"); } else { iMassDate = Convert.ToInt16(dts.Rows[0]["iMassDate"].ToString()); cMassUnit = Convert.ToInt16(dts.Rows[0]["cMassUnit"].ToString()); } sql = @" INSERT INTO dbo.PU_ArrivalVouchs (Autoid, ID, cInvCode, iQuantity, iOriCost, iOriTaxCost, iOriMoney, iOriTaxPrice, iOriSum, iCost, iMoney, iTaxPrice, iSum, iTaxRate, iPOsID, fValidInQuan, fRealQuantity, fValidQuantity, fRetQuantity, fInValidInQuan, bGsp, fValidNum, fValidInNum, fRealNum, bTaxCost, SoType, fInvalidInNum, iinvexchrate, cordercode, RejectSource, iExpiratDateCalcu, iordertype, ivouchrowno, bgift, dPDate, dVDate, imassdate, cmassunit, cExpirationdate, cFree1, cFree2, cFree3, cFree4, cFree5, cFree6, cFree7, cFree8,cItemCode, cBatch, cDefine37, fKPQuantity, finValidQuantity, fRefuseQuantity, iProductType,bexigency,cFree9,cFree10,iNum) SELECT @Autoid, @ID1, @cInvCode, @iQuantity,pd.iUnitPrice,pd.iTaxPrice,round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2), round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2),round(pd.iTaxPrice*@iQuantity,2),round((pd.iTaxPrice/(1+pd.iPerTaxRate/100)*b.nflat),2), round(round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2)*b.nflat,2), round((round(pd.iTaxPrice*@iQuantity,2)-round((pd.iTaxPrice*@iQuantity)/(1+pd.iPerTaxRate/100),2))*b.nflat,2),round(round(pd.iTaxPrice*@iQuantity,2)*b.nflat,2),pd.iPerTaxRate, pd.ID, 0, @iQuantity, @iQuantity, 0, 0, 0, null, null, null, 1, 0, null, 0, @cordercode, 0, 0, 0, @ivouchrowno, 0, @dPDate, @dVDate, @imassdate, @cmassunit, null, @cFree1, @cFree2, @cFree3, @cFree4, @cFree5, @cFree6, @cFree7, @cFree8,@cItemCode, @Batch, @cDefine37, null, null, null, null, null,@cFree9,@cFree10,@iNum FROM PO_Podetails pd left join po_pomain b on pd.poid=b.poid WHERE pd.ID = @iPOsID EXEC ICSProcedureUpdatePricePOToPUArrivalVouchs @ID= @ID1 "; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqlParameter("@iPOsID", body.PODetailID)); cmd.Parameters.Add(new SqlParameter("@Autoid", iChildId)); cmd.Parameters.Add(new SqlParameter("@ID1", iFatherId)); cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode)); cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity)); cmd.Parameters.Add(new SqlParameter("@iNum", body.Amount.ToString("0.00"))); cmd.Parameters.Add(new SqlParameter("@cordercode", head.POCode)); cmd.Parameters.Add(new SqlParameter("@ivouchrowno", body.Sequence)); cmd.Parameters.Add(new SqlParameter("@dPDate", head.MTime)); if (cMassUnit == 1) { cmd.Parameters.Add(new SqlParameter("@dVDate", head.MTime.AddYears(iMassDate).Date)); } else if (cMassUnit == 2) { cmd.Parameters.Add(new SqlParameter("@dVDate", head.MTime.AddMonths(iMassDate).Date)); } else if (cMassUnit == 3) { cmd.Parameters.Add(new SqlParameter("@dVDate", head.MTime.AddDays(iMassDate).Date)); } else cmd.Parameters.Add(new SqlParameter("@dVDate", "")); cmd.Parameters.Add(new SqlParameter("@imassdate", iMassDate)); cmd.Parameters.Add(new SqlParameter("@cmassunit", cMassUnit)); cmd.Parameters.Add(new SqlParameter("@Batch", body.BatchCode)); cmd.Parameters.Add(new SqlParameter("@cItemCode", body.ProjectCode)); cmd.Parameters.Add(new SqlParameter("@cDefine37", head.MTime.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddSeconds(-1))); cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1)); cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2)); cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3)); cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4)); cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5)); cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6)); cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7)); cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8)); cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9)); cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10)); cmd.CommandText = sql; try { int count = cmd.ExecuteNonQuery(); if (count <= 0) { log.Error("生成采购到货单表体失败,受影响行数<=0;"); throw new Exception("生成采购到货单表体失败,受影响行数<=0;"); } } catch (Exception ex) { log.Error("生成采购到货单表体失败!采购订单号:" + head.POCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex); throw new Exception("生成采购到货单表体失败!采购订单号:" + head.POCode + ";异常:" + ex.Message + ";SQL:\r\n" + sql, ex); } sql = string.Format(@"UPDATE B SET B.iArrMoney = ISNULL(B.iArrMoney, 0) + A.iOriSum, B.iNatArrMoney = ISNULL(B.iNatArrMoney, 0) + A.iSum, B.fPoArrQuantity=ISNULL(fPoArrQuantity,0)+A.iQuantity FROM dbo.PU_ArrivalVouchs A LEFT JOIN dbo.PO_Podetails B ON A.iPOsID = B.ID WHERE A.Autoid = '{0}'", iChildId); cmd.CommandText = sql; cmd.ExecuteNonQuery(); sql = @"select isnull(fPoArrQuantity,0)fOutQuantity,isnull(iQuantity,0)iQuantity,ISNULL(iNum, 0)iNum,ISNULL(NiNum, 0)NiNum,ISNULL(iNum, 0)-ISNULL(NiNum, 0) SiNum from PO_Podetails a LEFT JOIN (select sum(iNum) NiNum,iPOsID from PU_ArrivalVouchs GROUP BY iPOsID) b on a.ID=b.iPOsID where a.ID='" + body.PODetailID + "'"; DataTable dtDisCheck = DBHelper.SQlReturnData(sql, cmd); if (dtDisCheck != null && dtDisCheck.Rows.Count > 0) { foreach (DataRow item in dtDisCheck.Rows) { if (Convert.ToDecimal(item["fOutQuantity"].ToString()) == Convert.ToDecimal(item["iQuantity"].ToString())) { if (Convert.ToDecimal(item["iNum"].ToString()) != 0) { if (Convert.ToDecimal(item["SiNum"].ToString()) != 0) { sql = @"Update PU_ArrivalVouchs set iNum=isnull(iNum,0)+(" + item["SiNum"].ToString() + ") where autoid='" + iChildId + "' "; DBHelper.CmdExecuteNonQuery(sql, cmd, "辅计量余数处理失败!"); } } } } } iFatherIdTwo = "'" + iFatherId + "',"; iChildId--; } #endregion sql = @"SELECT top 1 A.ID as ID,A.ID as IDs,A.cCode as DNCode ,A.cVenCode,D.cVenName,A.cDepCode,C.cDepName, A.cpocode as POCode,A.cMaker as CreateUser,A.cMakeTime as CreateDateTime, A.cverifier as Checker,A.caudittime as CheckDateTime FROM PU_ArrivalVouch A left JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE left JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and A.iBillType=0 and A.ID in({0}) SELECT DISTINCT A.ID as IDs,B.Autoid as DetailID,B.ivouchrowno as Sequence,B.cInvCode as InvCode, B.INUM as Amount,B.iQuantity as Quantity,B.fValidInQuan as RCVQuantity,B.iPOsID as PODetailID ,isnull(b.cItemCode,'') ProjectCode, isnull(b.cbatch,'') cBatch, '' version ,'' brand, isnull(b.cFree1,'') as cFree1, isnull(b.cFree2,'') as cFree2, isnull(b.cFree3,'') as cFree3, isnull(b.cFree4,'') as cFree4, isnull(b.cFree5,'') as cFree5, isnull(b.cFree6,'') as cFree6, isnull(b.cFree7,'') as cFree7, isnull(b.cFree8,'') as cFree8, isnull(b.cFree9,'') as cFree9, isnull(b.cFree10,'') as cFree10 FROM PU_ArrivalVouch A INNER JOIN PU_ArrivalVouchs B ON A.ID=B.ID left JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE left JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and A.iBillType=0 and A.ID in({0})"; sql = string.Format(sql, iFatherIdTwo.TrimEnd(',')); if (ds != null) ds.Merge(DBHelper.SQlReturnDataSet(sql, cmd)); else ds = DBHelper.SQlReturnDataSet(sql, cmd); cmd.CommandType = CommandType.Text; cmd.Parameters.Clear(); } cmd.Transaction.Commit(); } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } str = JSON.DataSetToJson(ds, "details", "IDs"); return str; } public string Approve(List infos) { List szJson = new List(); DataTable dt = null; string json = ""; string connS = ""; if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string res = string.Empty; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; List result = infos.Select(t => t.WorkPoint).Distinct().ToList(); foreach (string WorkPoint in result) { try { connS = string.Format(connString, WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; foreach (ICSPOArrive info in infos) { if (WorkPoint != info.WorkPoint) { continue; } ICSUserInfo userInfo = new ICSUserInfo(); userInfo = DBHelper.GetPersonInfo(info.User, cmd); if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); sql = @"UPDATE dbo.PU_ArrivalVouch SET cVerifier ='" + userInfo.UserName + @"' , cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='{0}'"; sql = string.Format(sql, info.ID); DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!"); } cmd.Transaction.Commit(); } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } return json; } /// /// 删除请购单 /// /// /// public string Delete(List infos) { List szJson = new List(); if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string res = string.Empty; string connS = ""; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; List result = infos.Select(t => t.WorkPoint).Distinct().ToList(); foreach (string WorkPoint in result) { try { connS = string.Format(connString, WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; foreach (ICSPOArrive info in infos) { if (WorkPoint != info.WorkPoint) { continue; } if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); sql = @" DELETE dbo.PU_ArrivalVouch WHERE ID='{0}'"; sql = string.Format(sql, info.ID); DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!"); } cmd.Transaction.Commit(); } catch (Exception ex) { if (cmd.Transaction != null) cmd.Transaction.Rollback(); log.Error(ex.Message); throw new Exception(ex.Message); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } conn.Dispose(); } } return res; } } }