纽威
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.

733 lines
40 KiB

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