using ICSSoft.Common; 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 ManufactureReceiveDoc { 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 ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"]; private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"]; /// /// 获取成品入库单 /// /// /// public string Get(List infos) { List szJson = new List(); DataTable dt = null; DataTable dtNew = null; string connS = ""; string json = ""; if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string res = string.Empty; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; foreach (ICSManufactureReceiveDoc info in infos) { try { connS = string.Format(connString, info.WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); sql = @" select a.ID,a.cCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName,a.cMPoCode ,a.cMaker ,a.dnmaketime ,a.cHandler ,a.dnverifytime , b.AutoID,b.iRSRowNO ,b.cInvCode ,b.iQuantity ,b.iNum ,b.iMPoIds from rdrecord10 a left join rdrecords10 b on a.ID=b.ID left join Department c on a.cDepCode=c.cDepCode left join Warehouse d on a.cWhCode=d.cWhCode WHERE 1=1"; if (!string.IsNullOrWhiteSpace(info.MRCVCode)) { sql += " and a.cCode='{0}'"; } if (!string.IsNullOrWhiteSpace(info.MTime.ToString())) { sql += " and ISNULL(a.dnmodifytime,ISNULL(a.dnverifytime, ISNULL(a.dnmodifytime, a.dnmaketime)))>='{1}'"; } if (!string.IsNullOrWhiteSpace(info.User)) { sql += "and a.CMAKER='{2}'"; } sql = string.Format(sql, info.MRCVCode, info.MTime, info.User); dt = DBHelper.SQlReturnData(sql, cmd); if (dt.Rows.Count <= 0 || dt == null) throw new Exception("成品入库单:" + info.MRCVCode + ",无信息!"); dtNew.Merge(dt); cmd.Transaction.Commit(); } 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(); } } json = JsonConvert.SerializeObject(dtNew); return json; } /// /// 创建成品入库单 /// /// /// public string CreateManufactureReceiveDoc(List Bills) { string msg = ""; DataTable dtNew1 = null; DataTable dtNew2 = null; string connS = ""; int num = 0; string sql = string.Empty; //取得out库单的默认显示模版 //取得采购入库单单据 表头ID,表体DID VouchKey key = new VouchKey(); SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); if (Bills.Count <= 0) { throw new Exception("传送数据为空!"); } LogInfo(Bills); //MergeObject(Bills, cmd); //string ERPName = U8Helper.GetERPName(); foreach (ICSManufactureReceiveDoc head in Bills) { try { string iFatherIdTwo = ""; connS = string.Format(connString, head.WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; string[] ss = head.WorkPoint.Split('_'); ERPDB = ss[1]; num = head.details.Count(); Dictionary dic = DBHelper.GetAllCode("" + ERPDB + "", "ReceiveDoc", "" + num + ""); int iFatherId = Convert.ToInt32(dic["iFatherId"].ToString()); int iChildId = Convert.ToInt32(dic["iChildId"].ToString()); DateTime date = DateTime.Now; string DEF_ID = DBHelper.GetDefaultTemplate("0411", cmd); string cRDcode = DBHelper.GetRDCode("生产入库", cmd); string iBaseCodeLen = DBHelper.GetAllRDCode("0411", "" + date + "", "admin"); //Person personEntity = new Person(); //personEntity = U8Helper.GetDepCodeByUserCode(head.UserCode, cmd); DateTime dvDate = DateTime.Now.Date; #region 产成品入库单表头 sql = @"INSERT INTO dbo.rdrecord10 ( ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,cWhCode ,dDate , cCode ,cRdCode ,cDepCode ,cHandler ,bTransFlag ,cMaker , cDefine1 ,cDefine2 ,cDefine3 ,cDefine4 ,cDefine5 ,cDefine6 , cDefine7 ,cDefine8 ,cDefine9 ,cDefine10 ,dVeriDate ,bpufirst , biafirst ,VT_ID ,bIsSTQc ,cDefine11 ,cDefine12 ,cDefine13 , cDefine14 ,cDefine15 ,cDefine16 ,cMPoCode ,iproorderid , bFromPreYear ,bIsComplement ,iDiscountTaxType ,ireturncount , iverifystate ,iswfcontrolled ,cModifyPerson ,dnmaketime , dnverifytime ,bredvouch ,iPrintCount ) SELECT @ID,1,'10','成品入库','生产订单',@cWhCode,convert(datetime,convert(varchar(10),getdate(),120)), @cCode,@RdCode,@DepCode,@cHandler,0,@cMaker, a.Define1,a.Define2,a.Define3,a.Define4,a.Define5,a.Define6, a.Define7,a.Define8,a.Define9,a.Define10,@dDate,0, 0,@VT_ID,0,a.Define11,a.Define12,a.Define13, a.Define14,a.Define15,a.Define16,a.MoCode,a.MoId, 0,0,0,0, 0,0,'',@dDate, @dDate,0,0 FROM dbo.mom_order a WHERE a.MoCode='" + head.MOCode + "'"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqlParameter("@ID", iFatherId)); cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode)); cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen)); cmd.Parameters.Add(new SqlParameter("@cDepCode", head.DepCode)); cmd.Parameters.Add(new SqlParameter("@cHandler", head.User)); cmd.Parameters.Add(new SqlParameter("@cMaker", head.User)); cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID)); cmd.Parameters.Add(new SqlParameter("@DepCode", head.DepCode)); cmd.Parameters.Add(new SqlParameter("@dDate", dvDate)); cmd.Parameters.Add(new SqlParameter("@RdCode", cRDcode)); cmd.CommandText = sql; try { int count = cmd.ExecuteNonQuery(); if (count <= 0) { log.Error("生成成品入库单表头失败,受影响行数<=0;"); throw new Exception("生成成品入库单表头失败,受影响行数<=0;"); } } catch (Exception ex) { log.Error("生成成品入库单表头失败!SQL:\r\n" + sql, ex); throw new Exception("生成成品入库单表头失败!SQL:\r\n" + sql, ex); } #endregion #region 产成品入库单表体 foreach (ICSManufactureReceiveDocs body in head.details) { #region 判断工单行是否关闭,关闭不能入库 sql = @"SELECT ISNULL(a.CloseUser,'') as CloseUser,b.MoCode,a.SortSeq FROM dbo.mom_orderdetail a INNER JOIN dbo.mom_order b ON b.MoId = a.MoId WHERE a.MoDId = '" + body.MODetailID + "'"; DataTable dtCheck = DBHelper.SQlReturnData(sql, cmd); if (dtCheck != null && dtCheck.Rows.Count > 0) { if (!string.IsNullOrEmpty(dtCheck.Rows[0]["CloseUser"].ToString())) { throw new Exception("工单号:" + dtCheck.Rows[0]["MoCode"].ToString() + ",行号:" + dtCheck.Rows[0]["SortSeq"].ToString() + ",已关闭,无法入库!"); } } #endregion #region 生成产成品入库单表体 //if (head.IsReturn == "1") //{ // body.iQuantity = -body.iQuantity; //} sql = @"INSERT INTO dbo.rdrecords10 ( AutoID ,ID ,cInvCode ,iQuantity ,cBatch ,iFlag , cDefine22 ,cDefine23 ,cDefine24 ,cDefine25 ,cDefine26 ,cDefine27 , cItemCode ,cName ,iNQuantity ,cDefine28 , cDefine29 ,cDefine30 ,cDefine31 ,cDefine32 ,cDefine33 ,cDefine34 , cDefine35 ,cDefine36 ,cDefine37 ,iMPoIds ,bRelated ,bLPUseFree , iRSRowNO ,iOriTrackID ,bCosting ,cmocode ,imoseq ,iExpiratDateCalcu , iorderdid ,iordertype,iordercode,iorderseq,isodid,isotype,csocode,isoseq,irowno ,iposflag ,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10) SELECT @AutoID,@ID,@cInvCode,@iQuantity,@cBatch,0, a.Define22,a.Define23,a.Define24,a.Define25,a.Define26,a.Define27, null,null,a.Qty,a.Define28, a.Define29,a.Define30,a.Define31,a.Define32,a.Define33,a.Define34, a.Define35,a.Define36,a.Define37,a.MoDId,0,0, 0,0,1,b.MoCode,a.SortSeq,0, a.OrderDid,a.OrderType,a.OrderCode,a.OrderSeq,a.SoDId,a.SoType,a.SoCode,a.SoSeq,@irowno,0,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10 FROM dbo.mom_orderdetail a INNER JOIN dbo.mom_order b ON a.MoId=b.MoId WHERE a.MoDId='" + body.MODetailID + "'"; cmd.Parameters.Clear(); cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId)); cmd.Parameters.Add(new SqlParameter("@ID", iFatherId)); cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode)); cmd.Parameters.Add(new SqlParameter("@iQuantity", body.Quantity)); cmd.Parameters.Add(new SqlParameter("@cBatch", body.BatchCode)); cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence)); 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("生成材料出库单表头失败!SQL:\r\n" + sql, ex); throw new Exception("生成材料出库单表头失败!SQL:\r\n" + sql, ex); } #endregion if (head.UpdateStock) { #region 更新现存量 key.cBustypeUN = "成品入库"; key.cVouchTypeUN = "10"; key.TableName = "IA_ST_UnAccountVouch10"; //DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, "", body.Quantity, key); DBHelper.UpdateCurrentStockNEW(cmd, body.InvCode, head.WHCode, body.BatchCode, body.Quantity, body.cFree1, body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10, key); #endregion } #region 回写生产订单入库数量 sql = @"UPDATE dbo.mom_orderdetail SET QualifiedInQty=ISNULL(QualifiedInQty,0)+" + body.Quantity + " where MoDId='" + body.MODetailID + "'"; DBHelper.CmdExecuteNonQuery(sql, cmd, "回写生产订单入库数量失败!"); #endregion #region 判断工单行是否全部入库 sql = "SELECT (QualifiedInQty - Qty) as qty,QualifiedInQty FROM dbo.mom_orderdetail WHERE MoDId='" + body.MODetailID + "'"; DataTable dtClose = DBHelper.SQlReturnData(sql, cmd); foreach (DataRow dr in dtClose.Rows) { if (Convert.ToDecimal(dr["qty"]) >= 0) { sql = "update mom_orderdetail set CloseTime = GETDATE(),CloseDate= CONVERT(NVARCHAR(15),GETDATE(),23), CloseUser ='" + head.User + "',Status=4 where MODId='" + body.MODetailID + "'"; DBHelper.CmdExecuteNonQuery(sql, cmd, "生产订单行关闭失败!"); } } #endregion iFatherIdTwo += "'" + iFatherId + "',"; iChildId--; } #endregion #region 查询 sql = @" select a.ID as ID,a.ID as IDs,a.cCode as MRCVCode,a.cDepCode,c.cDepName,a.cWhCode,d.cWhName ,a.cMPoCode as MOCode ,a.cMaker as CreateUser ,a.dnmaketime as CreateDateTime ,a.cHandler as Checker ,a.dnverifytime as CheckDateTime from rdrecord10 a left join Department c on a.cDepCode=c.cDepCode left join Warehouse d on a.cWhCode=d.cWhCode WHERE A.cHandler IS NOT NULL AND A.ID in({0}) select a.ID as IDs, b.AutoID as DetailID,b.irowno as Sequence ,b.cInvCode as InvCode , b.iQuantity as Quantity ,b.iNum as Amount,b.iMPoIds as MODetailID from rdrecord10 a left join rdrecords10 b on a.ID=b.ID left join Department c on a.cDepCode=c.cDepCode left join Warehouse d on a.cWhCode=d.cWhCode WHERE A.cHandler IS NOT NULL AND A.ID in({0}) "; sql = string.Format(sql, iFatherIdTwo.TrimEnd(',')); DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd); dtNew1.Merge(ds.Tables[0]); dtNew2.Merge(ds.Tables[1]); #endregion cmd.Transaction.Commit(); } 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(); } } string RelationName = "details"; DataRelation dh = new DataRelation(RelationName, dtNew1.Columns["IDs"], dtNew2.Columns["IDs"]); DataSet dz = new DataSet(); dz.Relations.Add(dh); msg = DBHelper.DataSetToJson(dz, RelationName); return msg; } /// /// 审核成品入库单 /// /// /// public bool Approve(List infos) { bool ResultFlag = false; List szJson = new List(); string connS = ""; if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } LogInfo(infos); string res = string.Empty; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; foreach (ICSManufactureReceiveDoc head in infos) { try { connS = string.Format(connString, head.WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; ICSUserInfo userInfo = new ICSUserInfo(); userInfo = DBHelper.GetPersonInfo(head.User, cmd); #region 检验单号是否存在 sql = "select * from rdrecord10 where ID='" + head.ID + "'"; DataTable dt = DBHelper.SQlReturnData(sql, cmd); if (dt != null && dt.Rows.Count > 0) { string cHandler = dt.Rows[0]["cHandler"].ToString(); if (!string.IsNullOrEmpty(cHandler)) { throw new Exception("单据ID:" + head.ID + "不是开立状态!"); } } else { throw new Exception("单据ID:" + head.ID + "在U8中不存在!"); } #endregion #region 审核其他出库单 sql = @"UPDATE dbo.rdrecord10 SET cHandler='" + userInfo.UserName + @"' , dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'"; DBHelper.CmdExecuteNonQuery(sql, cmd, "审核其他出库单失败!"); #endregion sql = "select * from dbo.rdrecords10 a inner join rdrecord10 b on a.ID=b.ID where b.ID='" + head.ID + "';"; DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd); if (head.UpdateStock) { #region 更新现存量 for (int i = 0; i < dtChecks.Rows.Count; i++) { //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量 sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch='" + dtChecks.Rows[i]["cBatch"].ToString() + @"'AND cFree1='" + dtChecks.Rows[i]["cFree1"].ToString() + @"' AND cFree2='" + dtChecks.Rows[i]["cFree2"].ToString() + @"' AND cFree3='" + dtChecks.Rows[i]["cFree3"].ToString() + @"' AND cFree4='" + dtChecks.Rows[i]["cFree4"].ToString() + @"' AND cFree5='" + dtChecks.Rows[i]["cFree5"].ToString() + @"' AND cFree6='" + dtChecks.Rows[i]["cFree6"].ToString() + @"' AND cFree7='" + dtChecks.Rows[i]["cFree7"].ToString() + @"' AND cFree8='" + dtChecks.Rows[i]["cFree8"].ToString() + @"' AND cFree9='" + dtChecks.Rows[i]["cFree9"].ToString() + @"' AND cFree10='" + dtChecks.Rows[i]["cFree10"].ToString() + @"' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'"; DataTable dtItem = DBHelper.SQlReturnData(sql, cmd); if (dtItem != null && dtItem.Rows.Count > 0) { //if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch)) //{ // throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode); //} if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString())) { throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString()); } } else { throw new Exception("物料:" + dtChecks.Rows[i]["cInvCode"].ToString() + "在现存量表中不存在!"); } VouchKey key = new VouchKey(); key.cBustypeUN = "成品入库"; key.cVouchTypeUN = "10"; key.TableName = "IA_ST_UnAccountVouch10"; //DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key); DBHelper.UpdateCurrentStockNEW(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), dtChecks.Rows[i]["cBatch"].ToString(), Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), dtChecks.Rows[i]["cFree1"].ToString(), dtChecks.Rows[i]["cFree2"].ToString(), dtChecks.Rows[i]["cFree3"].ToString(), dtChecks.Rows[i]["cFree4"].ToString(), dtChecks.Rows[i]["cFree5"].ToString(), dtChecks.Rows[i]["cFree6"].ToString(), dtChecks.Rows[i]["cFree7"].ToString(), dtChecks.Rows[i]["cFree8"].ToString(), dtChecks.Rows[i]["cFree9"].ToString(), dtChecks.Rows[i]["cFree10"].ToString(), key); //回写fOutQuantityy // sql = @"Update CurrentStock set fOutQuantity=isnull(fOutQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @" // where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' "; //if (body.cBatch != null) //{ // sql += "and cBatch='" + body.cBatch + "'"; //} //else //{ // sql += "and cBatch=''"; //} //DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fOutQuantity失败!"); //if (head.UpdateTodoQuantity == true) //{ } #endregion } cmd.Transaction.Commit(); } 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(); } ResultFlag = true; } return ResultFlag; } /// /// 删除成品入库单 /// /// /// public string Delete(List infos) { List szJson = new List(); if (infos.Count <= 0) { throw new Exception("传送数据为空!"); } string connS = ""; string res = string.Empty; SqlConnection conn = new SqlConnection(); SqlCommand cmd = new SqlCommand(); string sql = string.Empty; foreach (ICSManufactureReceiveDoc info in infos) { try { connS = string.Format(connString, info.WorkPoint); conn = new System.Data.SqlClient.SqlConnection(connS); conn.Open(); SqlTransaction sqlTran = conn.BeginTransaction(); cmd = new SqlCommand(); cmd.Transaction = sqlTran; cmd.Connection = conn; if (info.MTime < new DateTime(2000, 01, 01)) throw new Exception("请输入正确的操作时间:" + info.MTime); sql = @" DELETE rdrecord10 WHERE ID={0}"; sql = string.Format(sql, info.ID); DBHelper.CmdExecuteNonQuery(sql, cmd, "未查询到对应数据!"); cmd.Transaction.Commit(); } 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(); } } return res; } /// /// /// 记录日志 /// /// private void LogInfo(List Bills) { string HeadList = string.Empty; string BodyList = string.Empty; foreach (ICSManufactureReceiveDoc head in Bills) { HeadList += "\r\n 表头主键ID:" + head.ID + ",仓库:" + head.WHCode + ",用户:" + head.User + ",站点:" + head.WorkPoint; foreach (ICSManufactureReceiveDocs body in head.details) { BodyList += "\r\n 表体主键ID: " + body.MODetailID + ",数量:" + body.Quantity; } } log.Info(HeadList); log.Info(BodyList); } } }