autocopy.aspx.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using BizCom;
  2. using ICSharpCode.SharpZipLib.Zip;
  3. using MSharp.Framework;
  4. using SQLData;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.IO;
  11. using System.Net.Http;
  12. using System.Net.Http.Headers;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Web;
  16. using System.Web.UI;
  17. using System.Web.UI.WebControls;
  18. public partial class autocopy : System.Web.UI.Page
  19. {
  20. public static string upPath = ConfigurationManager.AppSettings["upPath"];
  21. public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
  22. private void conErc(string msg)
  23. {
  24. Response.Write("{\"type\":\"error\",\"result\":\"" + msg + "\"}");
  25. //Response.End();
  26. }
  27. private void conSuc(string msg)
  28. {
  29. Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
  30. //Response.End();
  31. }
  32. protected void Page_Load(object sender, EventArgs e)
  33. {
  34. if (Request["hexdata"] != null)
  35. {
  36. string tids = Request["hexdata"];
  37. if (tids.Trim() == "")
  38. {
  39. conErc("无法下载");
  40. return;
  41. }
  42. int userId = 0;
  43. if (Request["userid"] != null)
  44. {
  45. userId = Convert.ToInt32(Request["userid"]);
  46. }
  47. try
  48. {
  49. string[] tArr = tids.Split(',');
  50. if (tArr.Length != 2)
  51. {
  52. conErc("订单ID不对,无法下载");
  53. return;
  54. }
  55. string oldctid = tArr[0].ToString();
  56. string newctid = tArr[1].ToString();
  57. StringBuilder sql = new StringBuilder();
  58. sql.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName from view_erptradecell where ctid='{0}'", oldctid);
  59. DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
  60. if (dt == null || dt.Rows.Count < 1)
  61. {
  62. conErc("没有找到相关订单" + oldctid);
  63. return;
  64. }
  65. StringBuilder sqlnew = new StringBuilder();
  66. sqlnew.AppendFormat("select ctid,tid,seller_memo,FinishDesignTime,OrderState,SupplierId,SupplierName,orderSn,payment,ProductId from view_erptradecell where (orderstate=3 or orderstate=4) and ctid='{0}'", newctid);
  67. DataTable dtnew = CeErpTradeCell.ExecuteDataset(sqlnew.ToString()).Tables[0];
  68. if (dtnew == null || dtnew.Rows.Count < 1)
  69. {
  70. conErc("没有找到相关new新订单" + newctid);
  71. return;
  72. }
  73. List<string> files = new List<string>();
  74. string oldDesignTime = "";
  75. string oldFilename = "";
  76. string df_name = "";
  77. string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
  78. string oldTag = ".cdr";
  79. List<string> noFileLst = new List<string>();
  80. List<string> errorFileLst = new List<string>();
  81. DataRow dr = dt.Rows[0];
  82. if (dr["FinishDesignTime"].ToString() == "")
  83. {
  84. conErc("没有找到相关old老订单附件,FinishDesignTime为空");
  85. return;
  86. }
  87. DateTime ftime = Convert.ToDateTime(dr["FinishDesignTime"]);
  88. DateTime splitTime = new DateTime(2023, 06, 27, 15, 30, 0);
  89. if (ftime.CompareTo(splitTime) > 0)
  90. {
  91. oldDesignTime = getDesignTimeWithDay(dr["FinishDesignTime"]);
  92. }
  93. else
  94. oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
  95. //oldDesignTime = getDesignTime(dr["FinishDesignTime"]);
  96. df_name = upPath + "\\" + oldDesignTime + "\\" + formatMemo(dr["seller_memo"]);
  97. foreach (string ext in extArr)
  98. {
  99. oldFilename = df_name + ext;
  100. oldTag = ext;
  101. if (File.Exists(oldFilename))
  102. {
  103. break;
  104. //if (!isUpdateError)
  105. //{
  106. // files.Add(fname);
  107. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  108. // fc++;
  109. //}
  110. }
  111. else
  112. oldFilename = "";
  113. }
  114. if (oldFilename == "")
  115. {
  116. conErc("没有找到相关old老订单附件");
  117. return;
  118. //noFileLst.Add("'" + dr["ctid"].ToString() + "'");
  119. }
  120. //if (hasFile)
  121. //{
  122. // fname = upPath + "\\" + dTime + "\\" + formatMemo(dr["seller_memo"]) + ".png";
  123. // if (File.Exists(fname))
  124. // {
  125. // files.Add(fname);
  126. // copyFile(getDesignDate(dr["FinishDesignTime"]), dr["SupplierName"].ToString(), fname);
  127. // }
  128. //}
  129. //sql = new StringBuilder();
  130. //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", tids, (int)OrderState.下单完成, userId, "下载设计文件");
  131. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo not like '%电子稿%' ;", (int)OrderState.下单完成, tids, (int)OrderState.设计完成);
  132. //sql.AppendFormat("update ce_erptradecell set FinishPlaceTime=getdate(),OrderState={0},IsReturn=0 where ctid in ({1}) and orderstate={2} and IsReturn<>2 and seller_memo like '%电子稿%' ;", (int)OrderState.已发货, tids, (int)OrderState.设计完成);
  133. //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
  134. DataRow newDr = dtnew.Rows[0];
  135. string newMemo = newDr["seller_memo"].ToString();
  136. newMemo = newMemo.Replace("(", "(");
  137. newMemo = newMemo.Replace(")", ")");
  138. string newmemoctid = MidStrEx(newMemo, "(", ")").Trim();
  139. string orderSn = newDr["orderSn"].ToString();
  140. if (newctid.IndexOf("C") != -1)
  141. {
  142. /*if (newMemo.IndexOf("[") != -1 && newMemo.IndexOf("C") != -1)
  143. {
  144. if (newmemoctid.IndexOf("S_") != -1) // (S_S_1962772776865084101)[C1] 对应ctid是 S_S_C1_1962772776865084101
  145. {
  146. int lastIndex = newmemoctid.LastIndexOf("S_"); //最后一个S_的位置
  147. string sPre = newmemoctid.Substring(0, lastIndex + 2); //S_S_
  148. string initTid = newmemoctid.Substring(lastIndex + 2, newmemoctid.Length - lastIndex - 2); //1962772776865084101
  149. string pre_ctid = MidStrEx(newMemo, "[", "]"); //C1
  150. if (pre_ctid.IndexOf("+") != -1)
  151. {
  152. pre_ctid = "C" + pre_ctid.Split('+')[1];
  153. }
  154. newmemoctid = sPre + pre_ctid + "_" + initTid; //S_S_ + C1 + _ +1962772776865084101
  155. }
  156. else
  157. {
  158. string pre_ctid = MidStrEx(newMemo, "[", "]");
  159. if (pre_ctid.IndexOf("+") != -1)
  160. {
  161. pre_ctid = "C" + pre_ctid.Split('+')[1];
  162. }
  163. if (newmemoctid.IndexOf('C') == -1)
  164. {
  165. newmemoctid = pre_ctid + "_" + newmemoctid;
  166. }
  167. }
  168. }*/
  169. }
  170. if (string.IsNullOrEmpty(newmemoctid))
  171. {
  172. conErc("上传的文件名格式不正确");
  173. return;
  174. }
  175. if (orderSn != newmemoctid)
  176. {
  177. conErc("新订单备注中的订单号不正确");
  178. return;
  179. }
  180. string newUpDesignTime = getDesignTimeWithDay(DateTime.Now);
  181. //string newDfName = upPath + "\\" + newUpDesignTime + "\\" + formatMemo(newDr["seller_memo"])+oldTag;
  182. string newPathFileName = "";
  183. copyUpFile(newUpDesignTime, oldFilename, formatMemo(newDr["seller_memo"]) + oldTag, ref newPathFileName);
  184. //copyFile(getDesignDate(DateTime.Now), dr["SupplierName"].ToString(), oldFilename, formatMemo(newDr["seller_memo"]) + oldTag);
  185. CeErpTradeCell.UpdateRelationOrder(newctid);
  186. StringBuilder up_sql = new StringBuilder();
  187. up_sql.AppendFormat("update ce_erptradecell with(rowlock) set orderstate=5,IsReturn=0,StartDesignTime=getdate(),SupplierId={1},FinishDesignTime=getdate() where ctid='{0}'", newctid, dr["SupplierId"]);
  188. CeErpTradeCell.ExecuteNonQuery(up_sql.ToString());
  189. if (oldTag == ".cdr")
  190. {
  191. //string sqlpng = string.Format("insert into s_cdrtopng(name,addtime)values('{0}',getdate()) ;", newPathFileName);
  192. //CeErpTradeLog.ExecuteNonQuery(sqlpng);
  193. }
  194. if (!Convert.IsDBNull(newDr["ProductId"]))
  195. {
  196. CeErpProduct product = CeErpProduct.GetById(Convert.ToInt32(newDr["ProductId"]));
  197. if (product != null)
  198. {
  199. string param = "[{ \"product_type\": \"" + product.PType + "\",\"remark\": \"" + newDr["seller_memo"] + "\",\"index\": \"" + orderSn + "\",\"orderid\": \"" + newDr["ctid"] + "\",\"price\": \"" + newDr["payment"] + "\"}]";
  200. sysHttpClient(param);
  201. }
  202. }
  203. CeErpTradeLog.AddLog(newctid, 5, userId, "自动上传老客户文件-" + newPathFileName);
  204. string fileSql = string.Format("INSERT INTO [dbo].[CE_ErpTradeCellFile]([tid], [ctid], [isDel], [url], [createtime], [type]) SELECT '{0}', '{1}', isDel ,url,getdate(),type FROM [dbo].[CE_ErpTradeCellFile] WHERE tid='{2}' and ctid='{3}' and isDel = 0 and type = 'AUTH_FILE'", dtnew.Rows[0]["tid"], dtnew.Rows[0]["tid"], dt.Rows[0]["tid"], dt.Rows[0]["tid"]);
  205. CeErpTradeCell.ExecuteNonQuery(fileSql);
  206. conSuc("文件已上传到共享目录");
  207. return;
  208. }
  209. catch (Exception ex)
  210. {
  211. conErc("错误的下载访问" + ex.Message);
  212. XLog.SaveLog(0, "autocopydown," + ex.Message);
  213. return;
  214. }
  215. }
  216. }
  217. public void sysHttpClient(string param)
  218. {
  219. Task.Run(async () =>
  220. {
  221. var client = new HttpClient();
  222. var request = new HttpRequestMessage
  223. {
  224. Method = HttpMethod.Post,
  225. RequestUri = new Uri("http://47.122.57.102:11004/quotations/batch"),
  226. Content = new StringContent(param)
  227. {
  228. Headers =
  229. {
  230. ContentType = new MediaTypeHeaderValue("application/json")
  231. }
  232. }
  233. };
  234. var task = Task.Run(() =>
  235. {
  236. try
  237. {
  238. var response = client.SendAsync(request).Result;
  239. response.EnsureSuccessStatusCode();
  240. writeLog(param + "-" + response.Content.ReadAsStringAsync().Result);
  241. return response.Content.ReadAsStringAsync().Result;
  242. }
  243. catch (Exception e)
  244. {
  245. return "";
  246. }
  247. });
  248. });
  249. }
  250. public static string MidStrEx(string sourse, string startstr, string endstr)
  251. {
  252. string result = string.Empty;
  253. int startindex, endindex;
  254. try
  255. {
  256. startindex = sourse.IndexOf(startstr);
  257. if (startindex == -1)
  258. return result;
  259. string tmpstr = sourse.Substring(startindex + startstr.Length);
  260. endindex = tmpstr.IndexOf(endstr);
  261. if (endindex == -1)
  262. return result;
  263. result = tmpstr.Remove(endindex);
  264. }
  265. catch (Exception ex)
  266. {
  267. Console.WriteLine("MidStrEx Err:" + ex.Message);
  268. }
  269. return result;
  270. }
  271. private string formatMemo(object memo)
  272. {
  273. string m = memo.ToString();
  274. m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
  275. return m;
  276. }
  277. private void copyUpFile(string date, string oldfile, string newfilename, ref string newPathFileName)
  278. {
  279. try
  280. {
  281. string path = upPath + "\\" + date;
  282. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  283. //string fname = Path.GetFileName(file);
  284. File.Copy(oldfile, path + "\\" + newfilename, true);
  285. newPathFileName = path + "\\" + newfilename;
  286. if (!File.Exists(path + "\\" + newfilename))
  287. {
  288. File.Copy(oldfile, path + "\\" + newfilename, true);
  289. }
  290. }
  291. catch (Exception ex)
  292. {
  293. XLog.SaveLog(0, "自动复制上传文件发生错误," + newfilename + "," + ex.Message);
  294. throw ex;
  295. }
  296. }
  297. private void copyFile(string date, string supplier, string oldfile, string newFileName)
  298. {
  299. try
  300. {
  301. string path = copyPath + "\\" + date + "\\" + supplier;
  302. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  303. //string fname = Path.GetFileName(file);
  304. File.Copy(oldfile, path + "\\" + newFileName, true);
  305. if (!File.Exists(path + "\\" + newFileName))
  306. {
  307. File.Copy(oldfile, path + "\\" + newFileName, true);
  308. }
  309. }
  310. catch (Exception ex)
  311. {
  312. XLog.SaveLog(0, "自动复制下载文件发生错误," + oldfile + "," + ex.Message);
  313. }
  314. }
  315. private string getDesignTime(object v)
  316. {
  317. if (v.ToString() == "") return "";
  318. return Convert.ToDateTime(v).ToString("yyyyMM");
  319. }
  320. private string getDesignTimeWithDay(object v)
  321. {
  322. if (v.ToString() == "") return "";
  323. return Convert.ToDateTime(v).ToString("yyyyMMdd");
  324. }
  325. private string getDesignDate(object v)
  326. {
  327. return DateTime.Now.ToString("yyyy-MM-dd");
  328. if (v.ToString() == "") return "";
  329. return Convert.ToDateTime(v).ToString("yyyy-MM-dd");
  330. }
  331. /// 批量进行多个文件压缩到一个文件
  332. /// </summary>
  333. /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
  334. /// <param name="zipFileName">生成的zip文件名称</param>
  335. private void ZipFileDownload(List<string> files, string zipFileName)
  336. {
  337. MemoryStream ms = new MemoryStream();
  338. byte[] buffer = null;
  339. using (ZipFile file = ZipFile.Create(ms))
  340. {
  341. file.BeginUpdate();
  342. //file.NameTransform = new ZipNameTransform();
  343. file.NameTransform = new MyNameTransfom();
  344. foreach (var item in files)
  345. {
  346. if (File.Exists(item)) file.Add(item);
  347. }
  348. file.CommitUpdate();
  349. buffer = new byte[ms.Length];
  350. ms.Position = 0;
  351. ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
  352. ms.Flush();
  353. ms.Close();
  354. }
  355. Response.Clear();
  356. Response.Buffer = true;
  357. Response.ContentType = "application/x-zip-compressed";
  358. Response.AddHeader("Set-Cookie", "fileDownload=true; path=/");
  359. Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(zipFileName));
  360. Response.BinaryWrite(buffer);
  361. Page.Response.Flush();
  362. Page.Response.SuppressContent = true;
  363. HttpContext.Current.ApplicationInstance.CompleteRequest();
  364. //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "alert('123');", true);
  365. //Response.Flush();
  366. //Response.End();
  367. }
  368. private void downLoadFile(string file)
  369. {
  370. string filePath = Server.MapPath("d/" + file);//路径
  371. //以字符流的形式下载文件
  372. FileStream fs = new FileStream(filePath, FileMode.Open);
  373. byte[] bytes = new byte[(int)fs.Length];
  374. fs.Read(bytes, 0, bytes.Length);
  375. fs.Close();
  376. Response.ContentType = "application/octet-stream";
  377. //通知浏览器下载文件而不是打开
  378. Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(file, System.Text.Encoding.UTF8));
  379. Response.BinaryWrite(bytes);
  380. Response.Flush();
  381. Response.End();
  382. }
  383. private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
  384. private static object logFlag = new object();
  385. public static void writeLog(string log)
  386. {
  387. lock (logFlag)
  388. {
  389. using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
  390. {
  391. using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
  392. {
  393. sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
  394. sw.Flush();
  395. }
  396. }
  397. }
  398. }
  399. }