锐腾搅拌上料功能
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.

739 lines
35 KiB

5 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using ICSSoft.Frame.Data.Entity;
  6. using System.Data;
  7. using ICSSoft.Base.Config.DBHelper;
  8. using ICSSoft.Base.Config.AppConfig;
  9. using ICSSoft.Frame.Data.Entity.NcApiEntity;
  10. using Newtonsoft.Json;
  11. using System.Net;
  12. namespace ICSSoft.Frame.Data.DAL
  13. {
  14. public class ICSForecastDAL
  15. {
  16. private static string APIURL = System.Configuration.ConfigurationSettings.AppSettings["APIURL"].ToString();
  17. private static string urlCreatForecast = APIURL + "planrelation";//生成预测单
  18. //private static string erp = AppConfig.GetDataBaseConnectStringByKey("[DB.ERP]");
  19. #region 新增和修改
  20. public static void Add(ICSForecast Info, DataTable dt, string Version, string dsconn)
  21. {
  22. FramDataContext db = new FramDataContext(dsconn);
  23. db.Connection.Open();
  24. db.Transaction = db.Connection.BeginTransaction();
  25. try
  26. {
  27. //var has = db.ICSForecast.Where(a => a.ForecastNO == Info.ForecastNO && a.Version == Info.Version && a.ID != Info.ID);
  28. //if (has != null && has.Count() > 0)
  29. // throw new Exception("单据号:" + Info.ForecastNO + " 已存在!");
  30. var line = db.ICSForecast.SingleOrDefault(a => a.ID == Info.ID);
  31. if (line == null)
  32. {
  33. ICSForecast dtCus = SearchInfo(Info.Customer, db);
  34. if (dtCus == null)
  35. throw new Exception("版本号获取失败!");
  36. Info.Version = dtCus.Version;
  37. string time = DateTime.Now.ToString("yyyyMMdd");
  38. string code = "PL" + time.Substring(2);
  39. var forecast = db.ICSForecast.Where(a => a.ForecastNO.Substring(0, code.Length) == code).OrderByDescending(a => a.ForecastNO).FirstOrDefault();
  40. if (forecast == null)
  41. Info.ForecastNO = code + "001";
  42. else
  43. Info.ForecastNO = code + (Convert.ToInt32(forecast.ForecastNO.Substring(code.Length)) + 1).ToString().PadLeft(3, '0');
  44. db.ICSForecast.InsertOnSubmit(Info);
  45. }
  46. else if (string.IsNullOrWhiteSpace(Version) && line.Checker != null)
  47. {
  48. throw new Exception("单据号:" + Info.ForecastNO + " 已审核,不能修改!");
  49. }
  50. else if (!string.IsNullOrWhiteSpace(Version))
  51. {
  52. if (line.Checker == null)
  53. throw new Exception("单据号:" + Info.ForecastNO + " 未审核,不能变更!");
  54. else
  55. {
  56. #region 版本号根据供应商直接升级
  57. var hasV = db.ICSForecast.Where(a => a.Customer == Info.Customer);
  58. if (hasV != null && hasV.Count() > 0)
  59. {
  60. ICSForecast dtCus = SearchInfo(Info.Customer, db);
  61. if (dtCus == null)
  62. throw new Exception("版本号获取失败!");
  63. Info.Version = dtCus.Version;
  64. }
  65. #endregion
  66. ICSForecast lineNew = new ICSForecast();
  67. Info.ID = AppConfig.GetGuid();
  68. lineNew.ID = Info.ID;
  69. lineNew.ForecastNO = Info.ForecastNO;
  70. lineNew.Version = Info.Version;// (Convert.ToInt32(line.Version) + 10).ToString();
  71. lineNew.Customer = Info.Customer;
  72. lineNew.Org = Info.Org;
  73. lineNew.Enable = true;
  74. lineNew.WorkPoint = AppConfig.WorkPointCode;
  75. lineNew.EATTRIBUTE1 = null;
  76. lineNew.MUSER = AppConfig.UserCode;
  77. lineNew.MUSERName = AppConfig.UserName;
  78. lineNew.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  79. lineNew.CreateUser = lineNew.MUSER;
  80. lineNew.CreateDateTime = lineNew.MTIME;
  81. db.ICSForecast.InsertOnSubmit(lineNew);
  82. line.Enable = false;
  83. }
  84. }
  85. else
  86. {
  87. line.MUSER = Info.MUSER;
  88. line.MUSERName = Info.MUSERName;
  89. line.MTIME = Info.MTIME;
  90. }
  91. db.SubmitChanges();
  92. var delete = db.ICSForecastDetail.Where(a => a.ForecastID == Info.ID);
  93. db.ICSForecastDetail.DeleteAllOnSubmit(delete);
  94. db.SubmitChanges();
  95. foreach (DataRow dr in dt.Rows)
  96. {
  97. if (string.IsNullOrWhiteSpace(dr["InvCode"].ToString()))
  98. throw new Exception("物料编码不能为空!");
  99. foreach (DataColumn dc in dt.Columns)
  100. {
  101. if (dc.Caption == "InvCode" || dc.Caption == "物料编码" || dc.Caption == "客户料号")
  102. continue;
  103. bool isNew = false;
  104. var detail = db.ICSForecastDetail.SingleOrDefault(a => a.ForecastID == Info.ID && a.InvCode == dr["InvCode"].ToString() && a.Period == dc.Caption);
  105. if (detail == null)
  106. {
  107. isNew = true;
  108. detail = new ICSForecastDetail();
  109. detail.ID = AppConfig.GetGuid();
  110. detail.ForecastID = Info.ID;
  111. detail.InvCode = dr["InvCode"].ToString();
  112. detail.Period = dc.Caption;
  113. detail.WorkPoint = Info.WorkPoint;
  114. }
  115. detail.Quantity = string.IsNullOrWhiteSpace(dr[dc.Caption].ToString()) ? 0 : Convert.ToDecimal(dr[dc.Caption]);
  116. detail.MUSER = Info.MUSER;
  117. detail.MUSERName = Info.MUSERName;
  118. detail.MTIME = Info.MTIME;
  119. if (isNew)
  120. db.ICSForecastDetail.InsertOnSubmit(detail);
  121. }
  122. db.SubmitChanges();
  123. }
  124. db.Transaction.Commit();
  125. }
  126. catch (Exception ex)
  127. {
  128. db.Transaction.Rollback();
  129. throw ex;
  130. }
  131. }
  132. #endregion
  133. #region 导入
  134. public static void AddList(DataTable dt, string dsconn)
  135. {
  136. FramDataContext db = new FramDataContext(dsconn);
  137. db.Connection.Open();
  138. db.Transaction = db.Connection.BeginTransaction();
  139. try
  140. {
  141. DateTime mtime = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  142. //string version = mtime.ToString("yyyyMM");
  143. var parent = dt.DefaultView.ToTable(true, "客户编码");
  144. foreach (DataRow drP in parent.Rows)
  145. {
  146. bool isNewP = false;
  147. string customer = drP["客户编码"].ToString();
  148. ICSForecast dtCus = SearchInfo(customer, db,true);
  149. if (dtCus == null)
  150. throw new Exception("版本号获取失败!");
  151. string ForecastNO = dtCus.ForecastNO;
  152. string version = dtCus.Version;
  153. var line = db.ICSForecast.SingleOrDefault(a => a.ForecastNO == ForecastNO && a.Enable == true);
  154. ICSForecast lineNew = new ICSForecast();
  155. if (line == null)
  156. {
  157. isNewP = true;
  158. lineNew.Version = version;
  159. lineNew.ID = AppConfig.GetGuid();
  160. lineNew.ForecastNO = ForecastNO;
  161. lineNew.Enable = true;
  162. lineNew.WorkPoint = AppConfig.WorkPointCode;
  163. lineNew.EATTRIBUTE1 = null;
  164. lineNew.CreateUser = AppConfig.UserCode;
  165. lineNew.CreateDateTime = mtime;
  166. }
  167. else if (line.Checker != null)
  168. {
  169. isNewP = true;
  170. lineNew.Version = version;// (Convert.ToInt32(line.Version) + 10).ToString();
  171. lineNew.ID = AppConfig.GetGuid();
  172. lineNew.ForecastNO = ForecastNO;
  173. lineNew.Enable = true;
  174. lineNew.WorkPoint = AppConfig.WorkPointCode;
  175. lineNew.EATTRIBUTE1 = null;
  176. lineNew.CreateUser = AppConfig.UserCode;
  177. lineNew.CreateDateTime = mtime;
  178. line.Enable = false;
  179. }
  180. else
  181. {
  182. lineNew = line;
  183. }
  184. lineNew.MUSER = AppConfig.UserCode;
  185. lineNew.MUSERName = AppConfig.UserName;
  186. lineNew.MTIME = mtime;
  187. if (isNewP)
  188. db.ICSForecast.InsertOnSubmit(lineNew);
  189. else
  190. {
  191. var delete = db.ICSForecastDetail.Where(a => a.ForecastID == lineNew.ID);
  192. db.ICSForecastDetail.DeleteAllOnSubmit(delete);
  193. db.SubmitChanges();
  194. }
  195. db.SubmitChanges();
  196. DataRow[] drs = dt.Select("客户编码='" + customer + "'");
  197. foreach (DataRow dr in drs)
  198. {
  199. if (string.IsNullOrWhiteSpace(customer))
  200. throw new Exception("单据号:" + ForecastNO + " 客户编码不能为空!");
  201. else if (string.IsNullOrWhiteSpace(dr["物料编码"].ToString()))
  202. throw new Exception("单据号:" + ForecastNO + " 物料编码不能为空!");
  203. lineNew.Customer = dr["客户编码"].ToString();
  204. lineNew.Org = dr["客户名称"].ToString();
  205. foreach (DataColumn dc in dt.Columns)
  206. {
  207. if (dc.Caption == "客户编码" || dc.Caption == "物料编码" || dc.Caption == "客户名称")
  208. continue;
  209. bool isNew = false;
  210. var detail = db.ICSForecastDetail.SingleOrDefault(a => a.ForecastID == lineNew.ID && a.InvCode == dr["物料编码"].ToString() && a.Period == dc.Caption);
  211. if (detail == null)
  212. {
  213. isNew = true;
  214. detail = new ICSForecastDetail();
  215. detail.ID = AppConfig.GetGuid();
  216. detail.ForecastID = lineNew.ID;//ICSINVENTORY.INVMODELGROUP
  217. detail.InvCode = dr["物料编码"].ToString();
  218. detail.Period = dc.Caption;
  219. detail.WorkPoint = lineNew.WorkPoint;
  220. }
  221. decimal t = 0m;
  222. if (decimal.TryParse(string.IsNullOrWhiteSpace(dr[dc.Caption].ToString()) ? "0" : dr[dc.Caption].ToString(), out t))
  223. {
  224. detail.Quantity = t;
  225. }
  226. else
  227. {
  228. throw new Exception("单据号:" + ForecastNO + dc.Caption + "格式不正确!");
  229. }
  230. detail.MUSER = lineNew.MUSER;
  231. detail.MUSERName = lineNew.MUSERName;
  232. detail.MTIME = lineNew.MTIME;
  233. if (isNew)
  234. db.ICSForecastDetail.InsertOnSubmit(detail);
  235. }
  236. db.SubmitChanges();
  237. }
  238. }
  239. db.Transaction.Commit();
  240. }
  241. catch (Exception ex)
  242. {
  243. db.Transaction.Rollback();
  244. throw ex;
  245. }
  246. }
  247. #endregion
  248. private static string GetVersion(string version)
  249. {
  250. string ver = version.Substring(6);
  251. List<string> str = new List<string> { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
  252. int index = str.IndexOf(ver) + 1;
  253. if (index >= str.Count())
  254. throw new Exception("超出变更次数!");
  255. return version.Substring(0, 6) + str[index];
  256. }
  257. public static ICSForecast SearchInfo(string Customer, FramDataContext db, bool ForecastNO=false)
  258. {
  259. string time=DateTime.Now.ToString("yyyyMMdd");
  260. string version = time.Substring(0, 6);
  261. ICSForecast info = new ICSForecast();
  262. var forecastVer = db.ICSForecast.Where(a => a.Customer == Customer && a.Version.Substring(0,6) == version).OrderByDescending(a => a.Version).FirstOrDefault();
  263. if (forecastVer == null)
  264. info.Version = version + "A";
  265. else
  266. //if (forecastVer != null)
  267. info.Version = GetVersion(forecastVer.Version);
  268. if (ForecastNO)
  269. {
  270. var num = db.ICSForecast.Where(a => a.Customer == Customer && a.Enable==true && !a.UploadErp);
  271. var check = num.Where(a => a.Checker == null);
  272. if (check == null || check.Count() <= 0)
  273. {
  274. string code = "PL" + time.Substring(2);
  275. var forecast = db.ICSForecast.Where(a => a.ForecastNO.Substring(0, code.Length) == code).OrderByDescending(a => a.ForecastNO).FirstOrDefault();
  276. if (forecast == null)
  277. info.ForecastNO = code + "001";
  278. else
  279. info.ForecastNO = code + (Convert.ToInt32(forecast.ForecastNO.Substring(code.Length)) + 1).ToString().PadLeft(3, '0');
  280. }
  281. else if (check.Count() > 1)
  282. {
  283. throw new Exception("客户编码:" + Customer + " 已存在多个未上传且未审核的预测单,不能导入!");
  284. }
  285. else
  286. {
  287. var numfirst = check.OrderByDescending(a => a.Version).FirstOrDefault();
  288. info.ForecastNO = numfirst.ForecastNO;
  289. }
  290. }
  291. // string sql = @"DECLARE @MaxNO INT,@date varchar(20)='PL'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 3, 6)
  292. // ,@Version VARCHAR(50)
  293. // SELECT @MaxNO=SUBSTRING(MAX(ForecastNO),LEN(@date)+1,LEN(MAX(ForecastNO))-LEN(@date))+1 FROM ICSForecast WHERE SUBSTRING(ForecastNO, 1, LEN(@date))=@date
  294. // SELECT @Version=MAX(Version) FROM ICSForecast WHERE Customer='{0}' AND SUBSTRING(Version, 1, LEN(Version)-1)=CONVERT(VARCHAR(6),GETDATE(),112)
  295. // IF @Version IS NULL
  296. // BEGIN
  297. // SET @Version=CONVERT(VARCHAR(6),GETDATE(),112)+'A'
  298. // END
  299. // IF @MaxNO IS NULL
  300. // BEGIN
  301. // SELECT '1' AS ID,@date+'001' AS ForecastNO,@Version AS Version
  302. // END
  303. // ELSE
  304. // BEGIN
  305. // SELECT '1' AS ID,@date+REPLICATE('0',3-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10)) AS ForecastNO,@Version AS Version
  306. // END ";
  307. // sql = string.Format(sql, Customer);
  308. // var info = db.ExecuteQuery<ICSForecast>(sql).FirstOrDefault();
  309. //DataSet ds = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql);
  310. //if (ds == null || ds.Tables.Count == 0)
  311. // return null;
  312. //else
  313. // return ds.Tables[0];
  314. return info;
  315. }
  316. #region 通过ID查询
  317. public static DataSet SearchInfoByID(string ID, string dsconn)
  318. {
  319. string sql = "";
  320. if (string.IsNullOrWhiteSpace(ID))
  321. {
  322. sql = @"DECLARE @MaxNO INT,@date varchar(20)='PL'+SUBSTRING(CONVERT(varchar(8), GETDATE(), 112), 3, 6)
  323. SELECT @MaxNO=SUBSTRING(MAX(ForecastNO),LEN(@date)+1,LEN(MAX(ForecastNO))-LEN(@date))+1 FROM ICSForecast WHERE SUBSTRING(ForecastNO, 1, LEN(@date))=@date
  324. IF @MaxNO IS NULL
  325. BEGIN
  326. SELECT @date+'001' AS ForecastNO,CONVERT(VARCHAR(6),GETDATE(),112)+'A' AS Version
  327. END
  328. ELSE
  329. BEGIN
  330. SELECT @date+REPLICATE('0',3-LEN(@MaxNO))+CAST(@MaxNO AS nvarchar(10)) AS ForecastNO,CONVERT(VARCHAR(6),GETDATE(),112)+'A' AS Version
  331. END ";
  332. }
  333. else
  334. {
  335. sql = @"SELECT ID,ForecastNO,Version,Org,Enable,Customer,CreateUser,CreateDateTime,Checker,CheckDateTime,Reviewer,ReviewDateTime,MUSER,MUSERName,MTIME,WorkPoint
  336. FROM ICSForecast WHERE ID='{0}' AND WorkPoint='{1}' ";
  337. }
  338. sql += @"SELECT a.Month,InvCode,Quantity
  339. INTO #TempForecast
  340. FROM ICSMonth a
  341. LEFT JOIN ICSForecastDetail b ON a.Month=b.Period AND ForecastID='{0}' AND WorkPoint='{1}'
  342. declare @sql varchar(8000)
  343. select @sql=isnull(@sql+',','')+'['+Month+']'
  344. from(select distinct Month from #TempForecast)as a
  345. set @sql='SELECT ISNULL(InvCode,'''') AS InvCode,'+@sql+' FROM #TempForecast PIVOT( MAX(Quantity) FOR Month IN ('+@sql+'))a '
  346. exec(@sql)
  347. DROP TABLE #TempForecast";
  348. sql = string.Format(sql, ID, AppConfig.WorkPointCode);
  349. DataSet ds = DBHelper.ExecuteDataset(dsconn, CommandType.Text, sql);
  350. return ds;
  351. }
  352. #endregion
  353. #region 删除
  354. public static void deleteInfo(List<string> IDList, string dsconn)
  355. {
  356. FramDataContext db = new FramDataContext(dsconn);
  357. db.Connection.Open();
  358. db.Transaction = db.Connection.BeginTransaction();
  359. try
  360. {
  361. var lines = db.ICSForecast.Where(a => IDList.Contains(a.ID));
  362. foreach (ICSForecast line in lines)
  363. {
  364. //上传ERP后删除标记
  365. if (line.UploadErp)
  366. {
  367. line.MUSER = AppConfig.UserCode;
  368. line.MUSERName = AppConfig.UserName;
  369. line.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  370. line.Enable = false;
  371. line.EATTRIBUTE1 = "delete";
  372. }
  373. else
  374. {
  375. var details = db.ICSForecastDetail.Where(a => a.ForecastID == line.ID);
  376. db.ICSForecastDetail.DeleteAllOnSubmit(details);
  377. db.ICSForecast.DeleteOnSubmit(line);
  378. }
  379. db.SubmitChanges();
  380. }
  381. db.Transaction.Commit();
  382. }
  383. catch (Exception ex)
  384. {
  385. db.Transaction.Rollback();
  386. throw ex;
  387. }
  388. }
  389. #endregion
  390. #region 审核
  391. public static void Check(List<string> IDList, string dsconn)
  392. {
  393. FramDataContext db = new FramDataContext(dsconn);
  394. db.Connection.Open();
  395. db.Transaction = db.Connection.BeginTransaction();
  396. try
  397. {
  398. var lines = db.ICSForecast.Where(a => IDList.Contains(a.ID));
  399. foreach (ICSForecast line in lines)
  400. {
  401. if (line.Checker != null)
  402. {
  403. throw new Exception("单据号:" + line.ForecastNO + " 已审核,不能再次审核!");
  404. }
  405. line.MUSER = AppConfig.UserCode;
  406. line.MUSERName = AppConfig.UserName;
  407. line.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  408. line.Checker = AppConfig.UserCode;
  409. line.CheckDateTime = line.MTIME;
  410. db.SubmitChanges();
  411. }
  412. db.Transaction.Commit();
  413. }
  414. catch (Exception ex)
  415. {
  416. db.Transaction.Rollback();
  417. throw ex;
  418. }
  419. }
  420. #endregion
  421. #region 弃审
  422. public static void RefuseCheck(List<string> IDList, string dsconn)
  423. {
  424. FramDataContext db = new FramDataContext(dsconn);
  425. db.Connection.Open();
  426. db.Transaction = db.Connection.BeginTransaction();
  427. try
  428. {
  429. var lines = db.ICSForecast.Where(a => IDList.Contains(a.ID));
  430. foreach (ICSForecast line in lines)
  431. {
  432. if (line.Checker == null)
  433. {
  434. throw new Exception("单据号:" + line.ForecastNO + " 不是审核状态,不能弃审!");
  435. }
  436. else if (line.Reviewer != null)
  437. {
  438. throw new Exception("单据号:" + line.ForecastNO + " 已复审,不能弃审!");
  439. }
  440. line.MUSER = AppConfig.UserCode;
  441. line.MUSERName = AppConfig.UserName;
  442. line.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  443. line.Checker = null;
  444. line.CheckDateTime = null;
  445. line.EATTRIBUTE1 = "check";
  446. db.SubmitChanges();
  447. }
  448. db.Transaction.Commit();
  449. }
  450. catch (Exception ex)
  451. {
  452. db.Transaction.Rollback();
  453. throw ex;
  454. }
  455. }
  456. #endregion
  457. #region 复审
  458. public static void Review(List<string> IDList, string dsconn)
  459. {
  460. FramDataContext db = new FramDataContext(dsconn);
  461. db.Connection.Open();
  462. db.Transaction = db.Connection.BeginTransaction();
  463. try
  464. {
  465. var lines = db.ICSForecast.Where(a => IDList.Contains(a.ID));
  466. foreach (ICSForecast line in lines)
  467. {
  468. if (line.Checker == null)
  469. {
  470. throw new Exception("单据号:" + line.ForecastNO + " 未审核,不能复审!");
  471. }
  472. else if (line.Reviewer != null)
  473. {
  474. throw new Exception("单据号:" + line.ForecastNO + " 已复审,不能再次复审!");
  475. }
  476. line.MUSER = AppConfig.UserCode;
  477. line.MUSERName = AppConfig.UserName;
  478. line.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  479. line.Reviewer = AppConfig.UserCode;
  480. line.ReviewDateTime = line.MTIME;
  481. db.SubmitChanges();
  482. }
  483. db.Transaction.Commit();
  484. }
  485. catch (Exception ex)
  486. {
  487. db.Transaction.Rollback();
  488. throw ex;
  489. }
  490. }
  491. #endregion
  492. #region 取消复审
  493. public static void ReviewBack(List<string> IDList, string dsconn)
  494. {
  495. FramDataContext db = new FramDataContext(dsconn);
  496. db.Connection.Open();
  497. db.Transaction = db.Connection.BeginTransaction();
  498. try
  499. {
  500. var lines = db.ICSForecast.Where(a => IDList.Contains(a.ID));
  501. foreach (ICSForecast line in lines)
  502. {
  503. if (line.Reviewer == null)
  504. {
  505. throw new Exception("单据号:" + line.ForecastNO + " 不是复审状态,不能取消复审!");
  506. }
  507. line.MUSER = AppConfig.UserCode;
  508. line.MUSERName = AppConfig.UserName;
  509. line.MTIME = AppConfig.GetSeverDateTime("yyyy-MM-dd HH:mm:ss");
  510. line.Reviewer = null;
  511. line.ReviewDateTime = null;
  512. line.EATTRIBUTE1 = "review";
  513. db.SubmitChanges();
  514. }
  515. db.Transaction.Commit();
  516. }
  517. catch (Exception ex)
  518. {
  519. db.Transaction.Rollback();
  520. throw ex;
  521. }
  522. }
  523. #endregion
  524. public static DataSet GetInvInfoAndCust(string pk_org)
  525. {
  526. string sqlDB = "SELECT '['+DBIpAddress+'].'+DBName FROM dbo.Sys_DataBase WHERE WorkCode = '{0}' AND DBSourceName = 'ERP'";
  527. sqlDB = string.Format(sqlDB, AppConfig.WorkPointCode);
  528. var DB = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sqlDB).Tables[0].Rows[0][0].ToString();
  529. string sql = @"SELECT '' AS [物料编码],'' as [客户料号],'' AS [物料名称] ,'' AS [规格型号]
  530. UNION ALL
  531. SELECT a.code AS [],a.materialmnecode as [],a.name AS [] ,a.materialspec AS []
  532. FROM {1}.dbo.bd_material a
  533. -- INNER JOIN {1}.dbo.org_orgs b ON a.pk_org =b.pk_org
  534. WHERE a.pk_org='{0}' --b.code='Ahwit'
  535. ORDER BY []
  536. SELECT cus.code AS [],cus.name AS [],cus.mnecode as [],cus.shortname as [] FROM {1}.dbo.bd_customer cus
  537. INNER JOIN {1}.dbo.org_orgs org ON cus.pk_org=org.pk_org
  538. ORDER BY cus.code";//--WHERE org.code='{1}'
  539. sql = string.Format(sql, pk_org, DB);
  540. return DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql);
  541. }
  542. public static void UploadErp(string ids, string dsconn)
  543. {
  544. string sql = "";
  545. FramDataContext db = new FramDataContext(dsconn);
  546. db.Connection.Open();
  547. db.Transaction = db.Connection.BeginTransaction();
  548. try
  549. {
  550. sql = "UPDATE ICSForecast SET UploadErp=1 WHERE ID IN ({0})";
  551. sql = string.Format(sql, ids);
  552. db.ExecuteCommand(sql);
  553. db.SubmitChanges();
  554. sql = @"SELECT ISNULL(d.code, '') AS Code,
  555. InvCode,
  556. Period,
  557. SUM(Quantity) AS Quantity,
  558. CONVERT(VARCHAR(7),MTIME,121) AS cDate
  559. FROM ICSForecastDetail a
  560. LEFT JOIN {1}.[dbo].bd_material b ON a.InvCode=b.code
  561. LEFT JOIN {1}.[dbo].bd_materialplan c ON b.pk_material=c.pk_material AND c.pk_org=(select pk_org from {1}.[dbo].org_orgs where code='01P1')
  562. LEFT JOIN {1}.[dbo].org_orgs d ON c.pk_prodfactory=d.pk_org
  563. WHERE (Quantity>0 OR Period=CONVERT(VARCHAR(7),MTIME,121)) AND ForecastID IN ({0})
  564. GROUP BY d.code,InvCode,Period,CONVERT(VARCHAR(7),MTIME,121)
  565. ORDER BY InvCode,Period
  566. ";
  567. var infoERP = db.Sys_DataBase.SingleOrDefault(a => a.DBSourceName == "ERP" && a.WorkCode == AppConfig.WorkPointCode);
  568. var infoMES = db.Sys_DataBase.SingleOrDefault(a => a.DBSourceName == "SYS" && a.WorkCode == AppConfig.WorkPointCode);
  569. string DB = (infoERP.DBIpAddress == infoMES.DBIpAddress ? "" : "[" + infoERP.DBIpAddress + "].") + infoERP.DBName;
  570. sql = string.Format(sql, ids, DB);
  571. var query = db.ExecuteQuery<TEMP_ForecastDetail>(sql).ToArray();
  572. var infoApiUser = db.Sys_DataBase.SingleOrDefault(a => a.DBSourceName == "UserNCAPI" && a.WorkCode == AppConfig.WorkPointCode);
  573. if (infoApiUser == null)
  574. throw new Exception("数据源中未维护调用NC接口的用户:UserNCAPI");
  575. string ApiUserCode = infoApiUser.DBUser;
  576. string ApiUserPassword = AppConfig.FromMd5(infoApiUser.DBPwd);
  577. NcApiInputArguments inputInfo = new NcApiInputArguments();
  578. inputInfo.datasource = "design";
  579. inputInfo.usercode = ApiUserCode;// AppConfig.UserCode;
  580. inputInfo.password = ApiUserPassword;// AppConfig.FromMd5(AppConfig.UserPwd);
  581. inputInfo.list = new List<object>();
  582. inputInfo.list.Clear();
  583. string msg = "";
  584. foreach (TEMP_ForecastDetail item in query)
  585. {
  586. string[] period = item.Period.Split('-');
  587. if (period == null || period.Length != 2)
  588. continue;
  589. if (string.IsNullOrWhiteSpace(item.Code))
  590. msg += "物料编码:" + item.InvCode + ",对应的工厂未维护!" + Environment.NewLine;
  591. CreateForecastEntity forecast = new CreateForecastEntity();
  592. forecast.pk_org = item.Code;//AppConfig.WorkPointCode;
  593. DateTime time = Convert.ToDateTime(item.Period + "-01");
  594. forecast.cbegindate = time.ToString("yyyy-MM-dd");
  595. forecast.cenddate = time.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
  596. forecast.periodyear = period[0];
  597. forecast.periodcode = Convert.ToInt32(period[1]).ToString();
  598. forecast.vchangerate = "1/1";
  599. forecast.cmaterialid = item.InvCode;
  600. //维护的月份等于当前上传月份
  601. if (item.Period == item.cDate)
  602. {
  603. var qty = query.Where(a => a.InvCode == item.InvCode && a.Period == "之前欠缺数量").ToList();
  604. if (qty == null || qty.Count() <= 0)
  605. {
  606. forecast.nnum = item.Quantity.ToString();
  607. }
  608. else
  609. {
  610. TEMP_ForecastDetail f = qty.First();
  611. forecast.nnum = (item.Quantity + (f == null ? 0 : f.Quantity)).ToString();
  612. }
  613. }
  614. else
  615. {
  616. forecast.nnum = item.Quantity.ToString();
  617. }
  618. inputInfo.list.Add(forecast);
  619. }
  620. if(!string.IsNullOrWhiteSpace(msg))
  621. throw new Exception(msg);
  622. //string sqlQuery = @"SELECT InvCode,Period,SUM(Quantity) AS Quantity
  623. // FROM ICSForecastDetail
  624. // WHERE Quantity>0 AND ForecastID IN ({0})
  625. // GROUP BY InvCode,Period";
  626. //sqlQuery = string.Format(sqlQuery, ids);
  627. //DataTable dt = DBHelper.ExecuteDataset(AppConfig.AppConnectString, CommandType.Text, sql).Tables[0];
  628. //foreach (DataRow dr in dt.Rows)
  629. //{
  630. // string[] period = dr["Period"].ToString().Split('-');
  631. // if (period == null || period.Length != 2)
  632. // continue;
  633. // CreateForecastEntity forecast = new CreateForecastEntity();
  634. // forecast.pk_org = "01P1";//AppConfig.WorkPointCode;
  635. // DateTime time = Convert.ToDateTime(dr["Period"].ToString() + "-01");
  636. // forecast.cbegindate = time.ToString("yyyy-MM-dd");
  637. // forecast.cenddate = time.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");
  638. // forecast.periodyear = period[0];
  639. // forecast.periodcode = Convert.ToInt32(period[1]).ToString();
  640. // forecast.vchangerate = "1/1";
  641. // forecast.cmaterialid = dr["InvCode"].ToString();
  642. // forecast.nnum = dr["Quantity"].ToString();
  643. // inputInfo.list.Add(forecast);
  644. //}
  645. string inputJson = JsonConvert.SerializeObject(inputInfo);
  646. string resStrCreatForecast = HttpPost(urlCreatForecast, inputJson);
  647. NcApiOutArguments res = new NcApiOutArguments();
  648. res = JsonConvert.DeserializeObject<NcApiOutArguments>(resStrCreatForecast);
  649. if (res.flat != "0")
  650. {
  651. throw new Exception("生成预测单失败:" + res.list_info);
  652. }
  653. db.Transaction.Commit();
  654. }
  655. catch (Exception ex)
  656. {
  657. db.Transaction.Rollback();
  658. throw ex;
  659. }
  660. finally
  661. {
  662. db.Connection.Close();
  663. }
  664. }
  665. public static string HttpPost(string url, string body)
  666. {
  667. try
  668. {
  669. Encoding encoding = Encoding.UTF8;
  670. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  671. request.Method = "POST";
  672. request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
  673. request.ContentType = "application/json; charset=utf-8";
  674. byte[] buffer = encoding.GetBytes(body);
  675. request.ContentLength = buffer.Length;
  676. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  677. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  678. using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
  679. {
  680. return reader.ReadToEnd();
  681. }
  682. }
  683. catch (WebException ex)
  684. {
  685. throw new Exception(ex.Message);
  686. }
  687. }
  688. }
  689. public class TEMP_ForecastDetail
  690. {
  691. public string Code { get; set; }
  692. public string InvCode { get; set; }
  693. public string Period { get; set; }
  694. public decimal Quantity { get; set; }
  695. public string cDate { get; set; }
  696. }
  697. }