纽威
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
47 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. using ICSSoft.Common;
  2. using ICSSoft.Entity;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace ICSSoft.DataProject
  12. {
  13. /// <summary>
  14. /// 采购入库红字
  15. /// </summary>
  16. public class PurchaseReceiveDoctNegative
  17. {
  18. private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  19. private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
  20. private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
  21. private static string Type = System.Configuration.ConfigurationManager.AppSettings["Type"];
  22. /// <summary>
  23. /// 获取采购入库单(红字)
  24. /// </summary>
  25. /// <param name="infos">传入参数</param>
  26. /// <returns></returns>
  27. public string Get(List<ICSPurchaseReceiveDoc> infos)
  28. {
  29. List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
  30. DataTable dt = null;
  31. DataTable dtNew = null;
  32. string json = "";
  33. string connS = "";
  34. if (infos.Count <= 0)
  35. {
  36. throw new Exception("传送数据为空!");
  37. }
  38. string res = string.Empty;
  39. SqlConnection conn = new SqlConnection();
  40. SqlCommand cmd = new SqlCommand();
  41. string sql = string.Empty;
  42. foreach (ICSPurchaseReceiveDoc info in infos)
  43. {
  44. try
  45. {
  46. connS = string.Format(connString, info.WorkPoint);
  47. conn = new System.Data.SqlClient.SqlConnection(connS);
  48. conn.Open();
  49. SqlTransaction sqlTran = conn.BeginTransaction();
  50. cmd = new SqlCommand();
  51. cmd.Transaction = sqlTran;
  52. cmd.Connection = conn;
  53. if (info.MTime < new DateTime(2000, 01, 01))
  54. throw new Exception("请输入正确的操作时间:" + info.MTime);
  55. sql = @"select a.ID,a.cCode,a.cVenCode,''as cVenName,cWhCode,''as cWhName,cARVCode,cMaker,dnmaketime,cHandler,dVeriDate,
  56. AutoID,irowno,cInvCode,iQuantity,iNum,iUnitCost,iArrsId
  57. FROM RdRecord01 a
  58. LEFT JOIN rdrecords01 b on a.ID=b.ID
  59. INNER JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
  60. INNER JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and iQuantity<0";
  61. if (!string.IsNullOrWhiteSpace(info.RCVTCode))
  62. {
  63. sql += " and a.cCode='{0}'";
  64. }
  65. if (!string.IsNullOrWhiteSpace(info.MTime.ToString()))
  66. {
  67. sql += " and ISNULL(b.cbCloseTime,ISNULL(a.cChangAuditTime,ISNULL(a.cAuditTime, ISNULL(a.cModifyTime, a.cmaketime))))>='{2}'";
  68. }
  69. if (!string.IsNullOrWhiteSpace(info.User))
  70. {
  71. sql += "and a.CMAKER='{3}'";
  72. }
  73. sql = string.Format(sql, info.RCVTCode, ERPDB, info.MTime, info.User);
  74. dt = DBHelper.SQlReturnData(sql, cmd);
  75. dtNew.Merge(dt);
  76. cmd.Transaction.Commit();
  77. }
  78. catch (Exception ex)
  79. {
  80. cmd.Transaction.Rollback();
  81. log.Error(ex.Message);
  82. throw new Exception(ex.Message);
  83. }
  84. finally
  85. {
  86. if (conn.State == ConnectionState.Open)
  87. {
  88. conn.Close();
  89. }
  90. conn.Dispose();
  91. }
  92. }
  93. json = JsonConvert.SerializeObject(dtNew);
  94. return json;
  95. }
  96. ///<summary>
  97. //创建采购入库单(红字)
  98. ///</summary>
  99. ///<param name="Bills"></param>
  100. ///<returns></returns>
  101. public string CreatePurchaseReceiveDoctNegative(List<ICSPurchaseReceiveDoc> Bills)
  102. {
  103. string szJson = "";
  104. string sql = "";
  105. string connS = "";
  106. int iFatherId = 0;
  107. int iChildId = 0;
  108. DateTime time = DateTime.Now;
  109. int num = 0;
  110. DataTable dtNew1 = null;
  111. DataTable dtNew2 = null;
  112. decimal iTaxRate = 0;
  113. VouchKey key = new VouchKey();
  114. if (Bills.Count <= 0)
  115. {
  116. throw new Exception("传送数据为空!");
  117. }
  118. string res = string.Empty;
  119. SqlConnection conn = new SqlConnection();
  120. SqlCommand cmd = new SqlCommand();
  121. foreach (ICSPurchaseReceiveDoc head in Bills)
  122. {
  123. try
  124. {
  125. string iFatherIdTwo = "";
  126. connS = string.Format(connString, head.WorkPoint);
  127. conn = new System.Data.SqlClient.SqlConnection(connS);
  128. conn.Open();
  129. SqlTransaction sqlTran = conn.BeginTransaction();
  130. cmd = new SqlCommand();
  131. cmd.Transaction = sqlTran;
  132. cmd.Connection = conn;
  133. string[] ss = head.WorkPoint.Split('_');
  134. ERPDB = ss[1];
  135. num = head.details.Count();
  136. Dictionary<string, int> dic = DBHelper.GetAllCode("" + ERPDB + "", "rd", "" + num + "");
  137. iFatherId = Convert.ToInt32(dic["iFatherId"].ToString());
  138. iChildId = Convert.ToInt32(dic["iChildId"].ToString());
  139. DateTime dates = DateTime.Now;
  140. string iBaseCodeLen = DBHelper.GetAllRDCode("24", "" + time + "", "admin");
  141. string cRDcode = DBHelper.GetRDCode("采购入库", cmd);
  142. string DEF_ID08 = DBHelper.GetDefaultTemplate("24", cmd);
  143. if (head.MTime < new DateTime(2000, 01, 01))
  144. throw new Exception("请输入正确的操作时间:" + head.MTime);
  145. #region 验证入库数量不能大于采购订单数量
  146. // foreach (ICSPurchaseReceiveDocs body in head.details)
  147. // {
  148. // sql = @"SELECT a.iQuantity,a.ID,isnull(a.iReceivedQTY,0) as iReceivedQTY,isnull(a.freceivedqty,0) as freceivedqty,ISNULL(c.fInExcess,0) AS fInExcess
  149. // FROM dbo.PO_Podetails a
  150. // INNER JOIN dbo.PO_Pomain b ON a.POID=b.POID
  151. // LEFT JOIN dbo.Inventory c ON a.cInvCode=c.cInvCode
  152. // where a.ID='" + head.ID + "'";
  153. // cmd.CommandText = sql;
  154. // DataTable dtQty = DBHelper.SQlReturnData(sql, cmd);
  155. // if (dtQty != null && dtQty.Rows.Count > 0)
  156. // {
  157. // decimal fInExcess = decimal.Parse(dtQty.Rows[0]["fInExcess"].ToString());//入库超额上限
  158. // decimal PoQty = decimal.Parse(dtQty.Rows[0]["iQuantity"].ToString());
  159. // decimal iReceicedQty = decimal.Parse(dtQty.Rows[0]["iReceivedQTY"].ToString());//累计到货数量
  160. // decimal freceivedqty = decimal.Parse(dtQty.Rows[0]["freceivedqty"].ToString());//合格品入库数量
  161. // PoQty = PoQty * (1 + fInExcess);
  162. // log.Info("PO数量:" + PoQty.ToString() + "入库超额上限:" + fInExcess.ToString() + ",累计到货数量:" + iReceicedQty.ToString() + ",合格品入库数量:" + freceivedqty.ToString());
  163. // //2021-11-05 回写字段变更,见行408
  164. // //decimal to = PoQty - iReceicedQty - freceivedqty;
  165. // decimal to = PoQty - freceivedqty;
  166. // if (body.Quantity > to)
  167. // {
  168. // throw new Exception("入库数量" + body.Quantity.ToString("f3") + "大于采购订单可入库数量" + to.ToString("f3")
  169. // );
  170. // }
  171. // }
  172. //}
  173. #endregion
  174. #region 采购入库单表头
  175. string BusType = "";//业务类型
  176. sql = @"select b.POID,b.cPOID,a.cVenCode,a.cDepCode,a.cexch_name,a.iTaxRate,a.cMaker,a.cpocode,
  177. b.nflat,a.cPersonCode,a.cptcode ,a.ID,a.cCode,a.cBusType
  178. FROM PU_ArrivalVouch a
  179. LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
  180. WHERE a.cCode ='" + head.DNRTCode + "'";
  181. cmd.CommandText = sql;
  182. DataTable dtPOMain = DBHelper.SQlReturnData(sql, cmd);
  183. if (dtPOMain != null && dtPOMain.Rows.Count > 0)
  184. {
  185. string cSource = "";
  186. string cCode = "";
  187. int bredvouch = 0;
  188. string WHCode = "";
  189. BusType = dtPOMain.Rows[0]["cBusType"].ToString();
  190. //校验采购订单类型是固定资产仓库
  191. if (BusType.Equals("固定资产"))
  192. {
  193. string sqlwh = @"SELECT bWhAsset FROM Warehouse WHERE cWhCode='" + head.WHCode + "'";
  194. cmd.CommandText = sqlwh;
  195. DataTable dtwhcode = DBHelper.SQlReturnData(sqlwh, cmd);
  196. log.Info(dtwhcode.Rows[0]["bWhAsset"].ToString());
  197. if (!dtwhcode.Rows[0]["bWhAsset"].ToString().Equals("True"))
  198. {
  199. throw new Exception("采购订单:" + dtPOMain.Rows[0]["cPOID"].ToString() + ",业务类型:固定资产,只能入固定资产仓库!");
  200. }
  201. else
  202. {
  203. WHCode = head.WHCode;
  204. }
  205. }
  206. else
  207. {
  208. WHCode = head.WHCode;
  209. }
  210. cSource = "采购退货单";
  211. cCode = dtPOMain.Rows[0]["cCode"].ToString();
  212. bredvouch = 1;
  213. sql = @"
  214. INSERT INTO dbo.RdRecord01
  215. (ID ,bRdFlag ,cVouchType ,cBusType ,cSource ,
  216. cWhCode ,dDate ,cCode ,cRdCode ,cDepCode ,
  217. cPersonCode ,cVenCode ,cOrderCode ,cARVCode,
  218. cHandler ,bTransFlag ,cMaker,cDefine1,cDefine2,
  219. dVeriDate ,bpufirst ,biafirst , dARVDate ,VT_ID ,
  220. bIsSTQc ,ipurorderid ,iTaxRate ,iExchRate ,cExch_Name ,
  221. bOMFirst ,bFromPreYear ,bIsComplement ,iDiscountTaxType ,ireturncount ,
  222. iverifystate ,iswfcontrolled ,cModifyPerson ,dnmaketime ,dnverifytime ,
  223. bredvouch ,bCredit ,iPrintCount,ipurarriveid,cPTCode,cVenPUOMProtocol)
  224. SELECT
  225. @ID,1,'01',b.cBusType,@cSource,
  226. @cWhCode,@dDate,@cCode,@cRdCode,@cDepCode,
  227. @cPersonCode,b.cVenCode,b.cPOID,@cARVCode,
  228. @cHandler,0,@cMaker,b.cDefine1,b.cDefine2,
  229. @cVeriDate,0,0,@dARVDate,@VT_ID,
  230. 0,@ipurorderid,b.iTaxRate,b.nflat,b.cexch_name,
  231. 0,0,0,0,0,
  232. 0,0,'',@dnmakertime,@dnverifytime,
  233. @bredvouch,0,0,@ipurarriveid,b.cPTCode,b.cPayCode
  234. FROM PU_ArrivalVouch a
  235. LEFT JOIN PO_Pomain b ON b.cPOID=a.cpocode
  236. WHERE a.cCode ='" + head.DNRTCode + "'";
  237. cmd.Parameters.Clear();
  238. cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
  239. cmd.Parameters.Add(new SqlParameter("@cSource", cSource));
  240. cmd.Parameters.Add(new SqlParameter("@cWhCode", head.WHCode));
  241. cmd.Parameters.Add(new SqlParameter("@dDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy -MM-dd")));
  242. cmd.Parameters.Add(new SqlParameter("@cCode", iBaseCodeLen));
  243. cmd.Parameters.Add(new SqlParameter("@cDepCode", dtPOMain.Rows[0]["cDepCode"].ToString()));
  244. cmd.Parameters.Add(new SqlParameter("@cPersonCode", dtPOMain.Rows[0]["cPersonCode"].ToString()));
  245. cmd.Parameters.Add(new SqlParameter("@cARVCode", cCode));
  246. cmd.Parameters.Add(new SqlParameter("@cMaker", head.User));
  247. cmd.Parameters.Add(new SqlParameter("@cVeriDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd")));
  248. cmd.Parameters.Add(new SqlParameter("@dARVDate", Convert.ToDateTime(head.MTime)));
  249. cmd.Parameters.Add(new SqlParameter("@VT_ID", DEF_ID08));
  250. cmd.Parameters.Add(new SqlParameter("@ipurorderid", dtPOMain.Rows[0]["POID"].ToString()));
  251. cmd.Parameters.Add(new SqlParameter("@dnmakertime", Convert.ToDateTime(DateTime.Now).ToString()));
  252. cmd.Parameters.Add(new SqlParameter("@dnverifytime", Convert.ToDateTime(DateTime.Now).ToString()));
  253. cmd.Parameters.Add(new SqlParameter("@bredvouch", bredvouch));
  254. cmd.Parameters.Add(new SqlParameter("@ipurarriveid", dtPOMain.Rows[0]["ID"].ToString()));
  255. cmd.Parameters.Add(new SqlParameter("@cHandler", head.User));
  256. cmd.Parameters.Add(new SqlParameter("@cRdCode", cRDcode));
  257. ;
  258. cmd.CommandText = sql;
  259. try
  260. {
  261. int count = cmd.ExecuteNonQuery();
  262. if (count <= 0)
  263. {
  264. log.Error("生成红字采购入库单表头失败,受影响行数<=0;");
  265. throw new Exception("生成红字采购入库单表头失败,受影响行数<=0;");
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. log.Error("生成红字采购入库单表头失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
  271. throw new Exception("生成红字采购入库单表头失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
  272. }
  273. }
  274. else
  275. {
  276. throw new Exception("对应采购订单不存在!采购订单号:" + dtPOMain.Rows[0]["cPOID"].ToString());
  277. }
  278. #endregion
  279. #region 采购入库单表体
  280. foreach (ICSPurchaseReceiveDocs body in head.details)
  281. {
  282. sql = @"SELECT c.id,c.cInvCode,c.iUnitPrice ,c.iMoney AS 原币无税金额 ,c.ivouchrowno,
  283. c.iTax AS ,c.iSum AS ,c.iNatUnitPrice ,
  284. c.iNatMoney AS ,c.iNatTax AS ,c.iNatSum AS ,
  285. c.iTaxPrice ,c.freceivedqty AS ,c.iPerTaxRate,b.Autoid,a.cCode,a.dDate
  286. FROM dbo.PU_ArrivalVouch a
  287. LEFT JOIN dbo.PU_ArrivalVouchs b ON a.ID=b.ID
  288. LEFT JOIN dbo.PO_Podetails c ON b.iPOsID=c.ID
  289. left JOIN dbo.PO_Pomain d ON c.POID=d.POID
  290. where b.AutoID='" + body.DNRTDetailID + "'";
  291. cmd.CommandText = sql;
  292. DataTable dtPODetails = DBHelper.SQlReturnData(sql, cmd);
  293. decimal iUnitPrice = 0;
  294. decimal iNatUnitPrice = 0;
  295. decimal iTaxPrice = 0;
  296. string id = "";
  297. string code = "";
  298. string date = "";
  299. if (dtPODetails != null && dtPODetails.Rows.Count > 0)
  300. {
  301. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iUnitPrice"].ToString()))
  302. iUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iUnitPrice"].ToString());//原币无税单价
  303. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iNatUnitPrice"].ToString()))
  304. iNatUnitPrice = decimal.Parse(dtPODetails.Rows[0]["iNatUnitPrice"].ToString());//本币无税单价
  305. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iTaxPrice"].ToString()))
  306. iTaxPrice = decimal.Parse(dtPODetails.Rows[0]["iTaxPrice"].ToString());//原币含税单价
  307. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["iPerTaxRate"].ToString()))
  308. iTaxRate = Convert.ToDecimal(dtPODetails.Rows[0]["iPerTaxRate"]);
  309. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["Autoid"].ToString()))//采购退货单字体标识
  310. id = dtPODetails.Rows[0]["Autoid"].ToString();
  311. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["cCode"].ToString()))//采购退货单号
  312. code = dtPODetails.Rows[0]["cCode"].ToString();
  313. if (!string.IsNullOrEmpty(dtPODetails.Rows[0]["dDate"].ToString()))//采购退货单日期
  314. date = dtPODetails.Rows[0]["dDate"].ToString();
  315. sql = @"INSERT INTO dbo.rdrecords01
  316. (
  317. AutoID ,ID ,cInvCode ,iNum ,iQuantity ,
  318. iUnitCost ,iPrice ,iAPrice ,cBatch ,iFlag ,
  319. dSDate ,iSQuantity ,iSNum ,iMoney ,iPOsID ,
  320. fACost ,iNQuantity ,chVencode ,iOriTaxCost ,iOriCost ,
  321. iOriMoney ,iOriTaxPrice ,ioriSum ,iTaxRate ,iTaxPrice ,
  322. iSum ,bTaxCost ,cPOID ,iMatSettleState ,iBillSettleCount ,
  323. bLPUseFree ,iOriTrackID ,cbaccounter ,dbKeepDate ,bCosting ,
  324. iSumBillQuantity ,bVMIUsed ,iExpiratDateCalcu ,isotype ,irowno,
  325. iArrsId,cbarvcode,dbarvdate,cFree1,cFree2,cFree3,cFree4,cFree5,cFree6,cFree7,cFree8,cFree9,cFree10
  326. )
  327. select
  328. @AutoID,@ID,@cInvCode,0,@iQuantity,
  329. @iUnitCost,@iPrice,@iAPrice,@cBatch,0,
  330. null,0,0,0,b.ID,
  331. @fACost,@iNQuantity,c.cVenCode,@iOriTaxCost,@iOriCost,
  332. @iOriMoney,@iOriTaxPrice,@ioriSum,@iTaxRate,@iTaxPrice,
  333. @iSum,1,c.cPOID,0,0,
  334. 0,0,null,null,d.bInCost,
  335. null,0,0,0,@irowno,
  336. @iArrsId,@cbarvcode,@dbarvdate,@cFree1,@cFree2,@cFree3,@cFree4,@cFree5,@cFree6,@cFree7,@cFree8,@cFree9,@cFree10
  337. FROM dbo.PU_ArrivalVouchs a
  338. left JOIN dbo.PO_Podetails b ON a.iPOsID = b.ID
  339. left JOIN dbo.PO_Pomain c ON b.POID = c.POID
  340. left JOIN dbo.Warehouse d ON d.cWhCode ='{0}'
  341. WHERE a.Autoid = '{1}'";
  342. sql = string.Format(sql, head.WHCode, body.DNRTDetailID);
  343. cmd.Parameters.Clear();
  344. cmd.Parameters.Add(new SqlParameter("@AutoID", iChildId));
  345. cmd.Parameters.Add(new SqlParameter("@ID", iFatherId));
  346. cmd.Parameters.Add(new SqlParameter("@cInvCode", body.InvCode));
  347. cmd.Parameters.Add(new SqlParameter("@iQuantity", -body.Quantity));
  348. cmd.Parameters.Add(new SqlParameter("@iUnitCost", iUnitPrice));
  349. cmd.Parameters.Add(new SqlParameter("@iPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
  350. cmd.Parameters.Add(new SqlParameter("@iAPrice", Math.Round(body.Quantity * iUnitPrice, 2)));
  351. cmd.Parameters.Add(new SqlParameter("@cBatch", body.BatchCode));
  352. //cmd.Parameters.Add(new SqlParameter("@iSQuantity", 0));
  353. //cmd.Parameters.Add(new SqlParameter("@iMoney", 0));
  354. cmd.Parameters.Add(new SqlParameter("@fACost", iNatUnitPrice));
  355. cmd.Parameters.Add(new SqlParameter("@iNQuantity", body.Quantity));
  356. cmd.Parameters.Add(new SqlParameter("@iOriTaxCost", iUnitPrice));
  357. cmd.Parameters.Add(new SqlParameter("@iOriCost", iTaxPrice));
  358. cmd.Parameters.Add(new SqlParameter("@iOriMoney", Math.Round(body.Quantity * iUnitPrice, 2)));
  359. cmd.Parameters.Add(new SqlParameter("@iOriTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
  360. cmd.Parameters.Add(new SqlParameter("@ioriSum", Math.Round(iTaxPrice * body.Quantity, 2)));
  361. cmd.Parameters.Add(new SqlParameter("@iTaxRate", iTaxRate));
  362. cmd.Parameters.Add(new SqlParameter("@iTaxPrice", Math.Round(Math.Round(iTaxPrice * body.Quantity, 2) - Math.Round(body.Quantity * iUnitPrice, 2), 2)));
  363. cmd.Parameters.Add(new SqlParameter("@iSum", Math.Round(iTaxPrice * body.Quantity, 2)));
  364. cmd.Parameters.Add(new SqlParameter("@irowno", body.Sequence));
  365. //cmd.Parameters.Add(new SqlParameter("@cPOID", head.POCode));
  366. cmd.Parameters.Add(new SqlParameter("@iArrsId", id));
  367. cmd.Parameters.Add(new SqlParameter("@cbarvcode", code));
  368. cmd.Parameters.Add(new SqlParameter("@dbarvdate", Convert.ToDateTime(date)));
  369. cmd.Parameters.Add(new SqlParameter("@cFree1", body.cFree1));
  370. cmd.Parameters.Add(new SqlParameter("@cFree2", body.cFree2));
  371. cmd.Parameters.Add(new SqlParameter("@cFree3", body.cFree3));
  372. cmd.Parameters.Add(new SqlParameter("@cFree4", body.cFree4));
  373. cmd.Parameters.Add(new SqlParameter("@cFree5", body.cFree5));
  374. cmd.Parameters.Add(new SqlParameter("@cFree6", body.cFree6));
  375. cmd.Parameters.Add(new SqlParameter("@cFree7", body.cFree7));
  376. cmd.Parameters.Add(new SqlParameter("@cFree8", body.cFree8));
  377. cmd.Parameters.Add(new SqlParameter("@cFree9", body.cFree9));
  378. cmd.Parameters.Add(new SqlParameter("@cFree10", body.cFree10));
  379. cmd.CommandText = sql;
  380. try
  381. {
  382. int count = cmd.ExecuteNonQuery();
  383. if (count <= 0)
  384. {
  385. log.Error("生成采购入库单表体失败,受影响行数<=0;");
  386. throw new Exception("生成采购入库单表体失败,受影响行数<=0;");
  387. }
  388. }
  389. catch (Exception ex)
  390. {
  391. log.Error("生成采购入库单表体失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
  392. throw new Exception("生成采购入库单表体失败!异常:" + ex.Message + ";SQL:\r\n" + sql, ex);
  393. }
  394. #region 更新[采购到货单子表]PU_ArrivalVouchs 合格品入库数量20211019
  395. sql = @"UPDATE PU_ArrivalVouchs SET fValidInQuan=ISNULL(fValidInQuan,0)+@iQty WHERE Autoid=@Autoid";
  396. cmd.CommandText = sql;
  397. cmd.Parameters.Clear();
  398. cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
  399. cmd.Parameters.Add(new SqlParameter("@Autoid", body.DNRTDetailID));
  400. try
  401. {
  402. log.Info("PU_Autoid:" + body.DNRTDetailID);
  403. cmd.ExecuteNonQuery();
  404. }
  405. catch (Exception ex)
  406. {
  407. log.Error("回写采购到货单子表合格品入库数量失败:Autoid:" + body.DNRTDetailID + ";异常:" + ex.Message);
  408. throw new Exception("程序异常,请联系开发人员!");
  409. }
  410. #endregion
  411. #region 更新[采购订单子表]PO_PODetails累计到货数量和累计到货金额
  412. //sql = @"Update a set iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty,iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney FROM dbo.PO_Podetails a where a.ID='" + body.iPOsID + "'";
  413. sql = @"
  414. Update a set
  415. iReceivedMoney=isnull(iReceivedMoney,0)+@iMoney
  416. ,freceivedqty=isnull(freceivedqty ,0)+ @iQty
  417. FROM dbo.PO_Podetails a where a.ID=@ID"
  418. ;
  419. //2021-11-05
  420. //1.移除 iReceivedQTY =isnull(iReceivedQTY ,0)+ @iQty 由采购到货,创建到货单CreatePU时写入iReceivedQTY,此处不再回写,累计到货数量
  421. //2.加入 freceivedqty =isnull(freceivedqty ,0) + @iQty 合格品入库数量
  422. cmd.CommandText = sql;
  423. cmd.Parameters.Clear();
  424. cmd.Parameters.Add(new SqlParameter("@iQty", body.Quantity));
  425. cmd.Parameters.Add(new SqlParameter("@iMoney", body.Quantity * iUnitPrice));
  426. cmd.Parameters.Add(new SqlParameter("@ID", body.DNRTDetailID));
  427. try
  428. {
  429. log.Info("iPOsID:" + body.DNRTDetailID);
  430. cmd.ExecuteNonQuery();
  431. }
  432. catch (Exception ex)
  433. {
  434. log.Error("回写采购订单累计到货数量和累计到货金额失败:采购订单表体行号:" + body.DNDetailID + ";异常:" + ex.Message);
  435. throw new Exception("程序异常,请联系开发人员!");
  436. }
  437. #endregion
  438. #region 判断现存量是否超入库
  439. sql = @"IF EXISTS(SELECT ID FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0})
  440. BEGIN
  441. DECLARE @MSG NVARCHAR(100)
  442. SELECT @MSG='ERP入库数量不能大于订单数量ID'+CAST(ID AS NVARCHAR(100)) FROM dbo.PO_Podetails WHERE isnull(freceivedqty,0)>iQuantity AND ID={0}
  443. RAISERROR(@MSG,16,1)
  444. END";
  445. sql = string.Format(sql, body.DNRTDetailID);
  446. cmd.CommandText = sql;
  447. cmd.ExecuteNonQuery();
  448. #endregion
  449. if (head.UpdateStock)
  450. {
  451. //更新现存量
  452. key.cBustypeUN = "普通采购";
  453. key.cVouchTypeUN = "01";
  454. key.TableName = "IA_ST_UnAccountVouch01";
  455. DBHelper.UpdateCurrentStockNEW(cmd, body.InvCode, head.WHCode, body.InvCode, -body.Quantity, body.cFree1, body.cFree2, body.cFree3, body.cFree4, body.cFree5, body.cFree6, body.cFree7, body.cFree8, body.cFree9, body.cFree10, key);
  456. //DBHelper.UpdateCurrentStock(cmd, body.InvCode, head.WHCode, body.InvCode, -body.Quantity, key);
  457. }
  458. }
  459. iFatherIdTwo += "'" + iFatherId + "',";
  460. iChildId--;
  461. ////更新主键ID,DID
  462. //DBHelper.UpdateIDandDID("rd", head.list.Count(), cmd);
  463. }
  464. #endregion
  465. #region 查询
  466. sql = @" select a.ID as ID,a.ID as IDs,a.cCode as RCVNEGCode,a.cVenCode,D.cVenName,
  467. a.cWhCode,c.cWhName,cARVCode as DNRTCode,cMaker as CreateUser,
  468. dnmaketime as CreateDateTime,cHandler as Checker,dVeriDate as CheckDateTime
  469. FROM RdRecord01 a
  470. LEFT JOIN Warehouse C ON A.cWhCode=C.cWhCode
  471. LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and a.ID in ({0})
  472. select a.ID as IDs, AutoID as DetailID,irowno as Sequence,
  473. cInvCode as InvCode,iQuantity as Quantity,iNum as Amount,iArrsId as DNRTDetailID
  474. FROM RdRecord01 a
  475. LEFT JOIN rdrecords01 b on a.ID=b.ID
  476. LEFT JOIN DEPARTMENT C ON A.CDEPCODE=C.CDEPCODE
  477. LEFT JOIN VENDOR D ON A.CVENCODE=D.CVENCODE WHERE 1=1 and a.ID in ({0}) ";
  478. sql = string.Format(sql, iFatherIdTwo.TrimEnd(','));
  479. DataSet ds = DBHelper.SQlReturnDataSet(sql, cmd);
  480. dtNew1.Merge(ds.Tables[0]);
  481. dtNew2.Merge(ds.Tables[1]);
  482. #endregion
  483. cmd.Transaction.Commit();
  484. }
  485. catch (Exception ex)
  486. {
  487. cmd.Transaction.Rollback();
  488. log.Error(ex.Message);
  489. throw new Exception(ex.Message);
  490. }
  491. finally
  492. {
  493. if (conn.State == ConnectionState.Open)
  494. {
  495. conn.Close();
  496. }
  497. conn.Dispose();
  498. }
  499. }
  500. string RelationName = "details";
  501. DataRelation dh = new DataRelation(RelationName, dtNew1.Columns["IDs"], dtNew2.Columns["IDs"]);
  502. DataSet dz = new DataSet();
  503. dz.Relations.Add(dh);
  504. szJson = DBHelper.DataSetToJson(dz, RelationName);
  505. return szJson;
  506. }
  507. /// <summary>
  508. /// 审核采购入库单(红字)
  509. /// </summary>
  510. /// <param name="infos"></param>
  511. /// <returns></returns>
  512. public bool Approve(List<ICSPurchaseReceiveDoc> infos)
  513. {
  514. bool ResultFlag = false;
  515. string connS = "";
  516. SqlConnection conn = new SqlConnection();
  517. SqlCommand cmd = new SqlCommand();
  518. if (infos.Count <= 0)
  519. {
  520. throw new Exception("传送数据为空!");
  521. }
  522. LogInfo(infos);
  523. foreach (ICSPurchaseReceiveDoc head in infos)
  524. {
  525. try
  526. {
  527. connS = string.Format(connString, head.WorkPoint);
  528. conn = new System.Data.SqlClient.SqlConnection(connS);
  529. conn.Open();
  530. SqlTransaction sqlTran = conn.BeginTransaction();
  531. cmd = new SqlCommand();
  532. cmd.Transaction = sqlTran;
  533. cmd.Connection = conn;
  534. string[] ss = head.WorkPoint.Split('_');
  535. ERPDB = ss[1];
  536. string sql = "";
  537. ICSUserInfo userInfo = new ICSUserInfo();
  538. userInfo = DBHelper.GetPersonInfo(head.User, cmd);
  539. #region 检验单号是否存在
  540. sql = "select * from RdRecord01 where ID='" + head.ID + "'";
  541. DataTable dt = DBHelper.SQlReturnData(sql, cmd);
  542. if (dt != null && dt.Rows.Count > 0)
  543. {
  544. string cHandler = dt.Rows[0]["cHandler"].ToString();
  545. if (!string.IsNullOrEmpty(cHandler))
  546. {
  547. throw new Exception("单据ID:" + head.ID + "不是开立状态!");
  548. }
  549. }
  550. else
  551. {
  552. throw new Exception("单据ID:" + head.ID + "在U8中不存在!");
  553. }
  554. #endregion
  555. #region 审核其他出库单
  556. sql = @"UPDATE dbo.RdRecord01 SET cHandler='" + userInfo.UserName + @"' ,
  557. dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE() WHERE ID='" + head.ID + "'";
  558. DBHelper.CmdExecuteNonQuery(sql, cmd, "审核其他出库单失败!");
  559. #endregion
  560. sql = "select * from dbo.RdRecords01 a inner join RdRecord01 b on a.ID=b.ID where b.ID='" + head.ID + "';";
  561. DataTable dtChecks = DBHelper.SQlReturnData(sql, cmd);
  562. if (head.UpdateStock)
  563. {
  564. #region 更新现存量
  565. for (int i = 0; i < dtChecks.Rows.Count; i++)
  566. {
  567. //判断物料批号与现存量表批号是否一致、数量不能超过现存量物料数量
  568. //sql = @"SELECT cBatch,iQuantity from CurrentStock WHERE cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "'AND cBatch=''and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "'";
  569. 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() + "'";
  570. DataTable dtItem = DBHelper.SQlReturnData(sql, cmd);
  571. if (dtItem != null && dtItem.Rows.Count > 0)
  572. {
  573. //if (!dtItem.Rows[0]["cBatch"].ToString().Equals(body.cBatch))
  574. //{
  575. // throw new Exception("物料条码的批号与U8现存量物料批号不一致,物料:" + body.cInvCode);
  576. //}
  577. if (Convert.ToDecimal(dtItem.Rows[0]["iQuantity"].ToString()) < Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()))
  578. {
  579. throw new Exception("物料条码的数量大于U8现存量物料数量,物料:" + dtChecks.Rows[i]["cInvCode"].ToString());
  580. }
  581. }
  582. else
  583. {
  584. throw new Exception("物料:" + dtChecks.Rows[i]["cInvCode"].ToString() + "在现存量表中不存在!");
  585. }
  586. VouchKey key = new VouchKey();
  587. key.cBustypeUN = "普通采购";
  588. key.cVouchTypeUN = "01";
  589. key.TableName = "IA_ST_UnAccountVouch01";
  590. //DBHelper.UpdateCurrentStock(cmd, dtChecks.Rows[i]["cInvCode"].ToString(), dtChecks.Rows[i]["cWhCode"].ToString(), "", Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()), key);
  591. 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);
  592. //回写fOutQuantityy
  593. // sql = @"Update CurrentStock set fOutQuantity=isnull(fOutQuantity,0)-" + Convert.ToDecimal(dtChecks.Rows[i]["iQuantity"].ToString()) + @"
  594. // where cInvCode='" + dtChecks.Rows[i]["cInvCode"].ToString() + "' and cWhCode='" + dtChecks.Rows[i]["cWhCode"].ToString() + "' ";
  595. //if (body.cBatch != null)
  596. //{
  597. // sql += "and cBatch='" + body.cBatch + "'";
  598. //}
  599. //else
  600. //{
  601. // sql += "and cBatch=''";
  602. //}
  603. //DBHelper.CmdExecuteNonQuery(sql, cmd, "回写fOutQuantity失败!");
  604. //if (head.UpdateTodoQuantity == true)
  605. //{
  606. #region 判断现存量是否足够
  607. sql = @"IF EXISTS(SELECT AutoID FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0)
  608. BEGIN
  609. DECLARE @MSG NVARCHAR(100)
  610. SELECT @MSG='ERP待出库数量不足AutoID'+CAST(AutoID AS NVARCHAR(100)) FROM dbo.CurrentStock WHERE iQuantity<0 OR iNum<0 OR fOutQuantity<0
  611. RAISERROR(@MSG,16,1)
  612. END";
  613. cmd.CommandText = sql;
  614. cmd.ExecuteNonQuery();
  615. #endregion
  616. }
  617. #endregion
  618. }
  619. cmd.Transaction.Commit();
  620. }
  621. catch (Exception ex)
  622. {
  623. cmd.Transaction.Rollback();
  624. log.Error(ex.Message);
  625. throw new Exception(ex.Message);
  626. }
  627. finally
  628. {
  629. if (conn.State == ConnectionState.Open)
  630. {
  631. conn.Close();
  632. }
  633. conn.Dispose();
  634. }
  635. }
  636. ResultFlag = true;
  637. return ResultFlag;
  638. // List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
  639. // DataTable dt = null;
  640. // string json = "";
  641. // if (infos.Count <= 0)
  642. // {
  643. // throw new Exception("传送数据为空!");
  644. // }
  645. // string res = string.Empty;
  646. // SqlConnection conn = new System.Data.SqlClient.SqlConnection(connString);
  647. // conn.Open();
  648. // SqlTransaction sqlTran = conn.BeginTransaction();
  649. // SqlCommand cmd = new SqlCommand();
  650. // cmd.Transaction = sqlTran;
  651. // cmd.Connection = conn;
  652. // try
  653. // {
  654. // string sql = string.Empty;
  655. // foreach (ICSPurchaseReceiveDoc info in infos)
  656. // {
  657. // if (info.MTime < new DateTime(2000, 01, 01))
  658. // throw new Exception("请输入正确的操作时间:" + info.MTime);
  659. // sql = @"UPDATE [{0}].dbo.RdRecord01 SET cVerifier ='" + info.User + @"' ,
  660. // cAuditTime=CONVERT(VARCHAR(50),GETDATE(),112),cAuditDate=GETDATE() WHERE ID='" + info.ID + "'";
  661. // sql = string.Format(sql, ERPDB);
  662. // DBHelper.CmdExecuteNonQuery(sql, cmd, "审核采购红字入库单失败!");
  663. // }
  664. // cmd.Transaction.Commit();
  665. // return json;
  666. // }
  667. // catch (Exception ex)
  668. // {
  669. // cmd.Transaction.Rollback();
  670. // log.Error(ex.Message);
  671. // throw new Exception(ex.Message);
  672. // }
  673. // finally
  674. // {
  675. // if (conn.State == ConnectionState.Open)
  676. // {
  677. // conn.Close();
  678. // }
  679. // conn.Dispose();
  680. // }
  681. }
  682. /// <summary>
  683. /// 删除采购入库单(红字)
  684. /// </summary>
  685. /// <param name="infos"></param>
  686. /// <returns></returns>
  687. public string Delete(List<ICSPurchaseReceiveDoc> infos)
  688. {
  689. List<ICSPurchaseReceiveDoc> szJson = new List<ICSPurchaseReceiveDoc>();
  690. if (infos.Count <= 0)
  691. {
  692. throw new Exception("传送数据为空!");
  693. }
  694. string res = string.Empty;
  695. string connS = "";
  696. SqlConnection conn = new SqlConnection();
  697. SqlCommand cmd = new SqlCommand();
  698. string sql = string.Empty;
  699. foreach (ICSPurchaseReceiveDoc info in infos)
  700. {
  701. try
  702. {
  703. connS = string.Format(connString, info.WorkPoint);
  704. conn = new System.Data.SqlClient.SqlConnection(connS);
  705. conn.Open();
  706. SqlTransaction sqlTran = conn.BeginTransaction();
  707. cmd = new SqlCommand();
  708. cmd.Transaction = sqlTran;
  709. cmd.Connection = conn;
  710. if (info.MTime < new DateTime(2000, 01, 01))
  711. throw new Exception("请输入正确的操作时间:" + info.MTime);
  712. sql = @"delete rdrecord11 where rdrecord11.ID='" + info.ID + "'";
  713. sql += @"delete rdrecords11 where rdrecords11.ID='" + info.ID + "'";
  714. //UPDATE dbo.rdrecord11 a SET cHandler='" + info.User + @"' ,
  715. // dVeriDate=CONVERT(VARCHAR(50),GETDATE(),112),dnverifytime=GETDATE()
  716. // WHERE a.ID='" + info.ID + "'";
  717. DBHelper.CmdExecuteNonQuery(sql, cmd, "删除采购红字入库单失败!");
  718. cmd.Transaction.Commit();
  719. }
  720. catch (Exception ex)
  721. {
  722. cmd.Transaction.Rollback();
  723. log.Error(ex.Message);
  724. throw new Exception(ex.Message);
  725. }
  726. finally
  727. {
  728. if (conn.State == ConnectionState.Open)
  729. {
  730. conn.Close();
  731. }
  732. conn.Dispose();
  733. }
  734. }
  735. return res;
  736. }
  737. public string GetSerialCode(string ID)
  738. {
  739. string sql = "EXEC Addins_GetSerialCode '{0}'";
  740. sql = string.Format(sql, new object[] { ID });
  741. return DBHelper.ExecuteScalar(CommandType.Text, sql, connString).ToString();
  742. }
  743. /// <summary>
  744. /// 记录日志
  745. /// </summary>
  746. /// <param name="Bills"></param>
  747. private void LogInfo(List<ICSPurchaseReceiveDoc> Bills)
  748. {
  749. string HeadList = string.Empty;
  750. string BodyList = string.Empty;
  751. foreach (ICSPurchaseReceiveDoc head in Bills)
  752. {
  753. HeadList += "\r\n 表头主键ID:" + head.ID + ",用户:" + head.User + ",站点:" + head.WorkPoint;
  754. }
  755. log.Info(HeadList);
  756. log.Info(BodyList);
  757. }
  758. }
  759. }