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

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