f_tools.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Windows.Forms;
  11. using Newtonsoft.Json;
  12. namespace Fuel01
  13. {
  14. public partial class F_tools : Form
  15. {
  16. private int err = 0;
  17. private bool ok = false;
  18. private DataSet1.tb_venteDataTable tb_vente = new DataSet1.tb_venteDataTable();
  19. private readonly DataSet1.tb_prestaDataTable tb_presta = new DataSet1.tb_prestaDataTable();
  20. private readonly List<string> files2move = new List<string>();
  21. private bool hasChanged = false;
  22. private readonly List<Produit> lproduit = new List<Produit>();
  23. private List<Vente> Ventes = new List<Vente>();
  24. public F_tools()
  25. {
  26. InitializeComponent();
  27. Program.subfolder = Program.folder + @"\" + Program.key_ope;
  28. if (!Directory.Exists(Program.subfolder))
  29. Directory.CreateDirectory(Program.subfolder);
  30. if (File.Exists(Program.folder + @"\param\produit.xml"))
  31. {
  32. lproduit = DbUtil.GetProduits();
  33. }
  34. if (File.Exists(Program.subfolder + @"\presta.json"))
  35. {
  36. tb_presta = DbUtil.LoadPrestaFromJson(Program.subfolder + @"\presta.json", lproduit);
  37. }
  38. }
  39. /// <summary>
  40. /// Appelle le serveur pour récupérer les fichiers
  41. /// </summary>
  42. /// <param name="sender"></param>
  43. /// <param name="e"></param>
  44. private void bt_getdatas_Click(object sender, EventArgs e)
  45. {
  46. textResult.Text = "";
  47. line_res("Connexion au serveur");
  48. string url = Properties.Settings.Default.server_adress_datas;
  49. List<string> lines = readHttp_Dir(url);
  50. copyHttp(lines);
  51. line_res("F I N");
  52. }
  53. private void bt_trait_Click(object sender, EventArgs e)
  54. {
  55. this.Cursor = Cursors.WaitCursor;
  56. files2move.Clear();
  57. err = 0;
  58. textResult.Text = "";
  59. line_res("Début");
  60. string[] files = Directory.GetFiles(Program.folder + @"\in", "*.json ");
  61. List<Achats3> allAchats = new List<Achats3>();
  62. foreach (string file in files)
  63. {
  64. var content = File.ReadAllText(file);
  65. var str = "\"qtty\":\"\"";
  66. var str2 = "\"qtty\":\"1\"";
  67. if (content.Contains(str))
  68. {
  69. content = content.Replace(str, str2);
  70. }
  71. var achats = JsonConvert.DeserializeObject<List<Achats3>>(content);
  72. allAchats.AddRange(achats);
  73. files2move.Add(file);
  74. }
  75. Ventes = ConvertAchatsToVentes(Ventes, allAchats);
  76. line_res("F I N");
  77. if (err == 0 && !ok)
  78. {
  79. if (MessageBox.Show("Voulez-vous enregister les achats", "Aucune erreur", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
  80. {
  81. ok = true;
  82. load_vente();
  83. bt_trait_Click(sender, e);
  84. tb_vente.WriteXml(Program.subfolder + @"\vente.xml", XmlWriteMode.WriteSchema);
  85. //File.WriteAllText(Program.subfolder + @"\vente.json", JsonConvert.SerializeObject(allAchats));
  86. hasChanged = false;
  87. foreach (string file in files2move)
  88. File.Move(file, file.Replace(Program.folder + @"\in", Program.folder + @"\in\done"));
  89. foreach (var vente in Ventes)
  90. {
  91. Traite(vente);
  92. }
  93. DbUtil.SaveToJson<DataSet1.tb_venteDataTable>(Program.subfolder + @"\vente.json", tb_vente);
  94. load_vente();
  95. }
  96. }
  97. else
  98. ok = false;
  99. this.Cursor = Cursors.Default;
  100. }
  101. private void load_vente()
  102. {
  103. tb_vente.Clear();
  104. if (File.Exists(Program.subfolder + @"\vente.json"))
  105. {
  106. tb_vente = DbUtil.LoadFromJson<DataSet1.tb_venteDataTable>(Program.subfolder + @"\vente.json", tb_vente);
  107. Ventes = JsonConvert.DeserializeObject<List<Vente>>(File.ReadAllText(Program.subfolder + @"\vente.json"));
  108. if (Ventes != null && Ventes.Count > 0)
  109. {
  110. tb_vente.AcceptChanges();
  111. tbventeBindingSource.DataSource = tb_vente;
  112. }
  113. }
  114. }
  115. private void save_vente()
  116. {
  117. File.WriteAllText(Program.subfolder + @"\vente.json", JsonConvert.SerializeObject(Ventes));
  118. }
  119. private List<Vente> ConvertAchatsToVentes(List<Vente> ventes, List<Achats3> achats)
  120. {
  121. foreach (var achat in achats)
  122. {
  123. var vente = new Vente
  124. {
  125. date_vt = DateTime.ParseExact(achat.moment, "yyyy-MM-ddTHH:mm:ss.ffffff", CultureInfo.InvariantCulture),
  126. epreuve_vt = Program.key_ope,
  127. ht_vt = 0,
  128. prod_vt = achat.libel,
  129. pu_vt = achat.pu,
  130. qtt_vt = achat.qtty,
  131. station_vt = achat.stationKey.ToString(),
  132. ttc_vt = achat.montantTTC,
  133. tva_vt = 0,
  134. vehi_vt = achat.bandeau
  135. };
  136. ventes.Add(vente);
  137. }
  138. return ventes;
  139. }
  140. /// <summary>
  141. /// Récupère les noms des fichiers à partir d'un repertoire listé en HTML
  142. /// </summary>
  143. /// <param name="url_txt">URL à lister</param>
  144. /// <returns>liste Urls des fichiers distants</returns>
  145. private List<string> readHttp_Dir(string url_txt)
  146. {
  147. Uri url = new Uri(url_txt);
  148. List<string> lines = new List<string>();
  149. try
  150. {
  151. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  152. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  153. Stream receiveStream = response.GetResponseStream();
  154. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  155. var block = readStream.ReadToEnd();
  156. response.Close();
  157. readStream.Close();
  158. var files = JsonConvert.DeserializeObject<List<string>>(block);
  159. var str = "";
  160. var str2 = "";
  161. int inb=-1;
  162. foreach (var file in files.Where(x => x.EndsWith(".json", StringComparison.OrdinalIgnoreCase)))
  163. {
  164. try
  165. {
  166. var fileUrl = Path.Combine(url_txt, file);
  167. request = (HttpWebRequest)WebRequest.Create(fileUrl);
  168. response = (HttpWebResponse)request.GetResponse();
  169. receiveStream = response.GetResponseStream();
  170. readStream = new StreamReader(receiveStream, Encoding.UTF8);
  171. block = readStream.ReadToEnd();
  172. response.Close();
  173. readStream.Close();
  174. Console.WriteLine(block);
  175. str = "\"qtty\\\":\\\"\\\"";
  176. str2 = "\"qtty\\\":\\\"1\\\"";
  177. if (block.Contains(str))
  178. {
  179. block = block.Replace(str, str2);
  180. }
  181. var json = JsonConvert.DeserializeObject<string>(block);
  182. _ = JsonConvert.DeserializeObject<List<Achats3>>(json);
  183. lines.Add("http://" + response.ResponseUri.Host + "/Achats/" + file);
  184. }
  185. catch (Exception ex)
  186. {
  187. MessageBox.Show(ex.Message, "Err. Net");
  188. }
  189. }
  190. }
  191. catch (System.Net.WebException ex)
  192. {
  193. MessageBox.Show(ex.Message, "Err. Net");
  194. }
  195. catch (Exception ex)
  196. {
  197. MessageBox.Show(ex.Message, "Err. Autre");
  198. }
  199. line_res(lines.Count.ToString() + " Fichiers trouvés");
  200. return lines;
  201. }
  202. /// <summary>
  203. /// Copy localement (sous programmData/xxxx/xxxx) une liste de fichiers issue d"un répertoire HTML
  204. /// </summary>
  205. /// <param name="lines">liste des URL des fichiers distants</param>
  206. private void copyHttp(List<string> lines)
  207. {
  208. foreach (string line in lines)
  209. {
  210. Uri url = new Uri(line);
  211. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  212. // Set some reasonable limits on resources used by this request
  213. request.MaximumAutomaticRedirections = 4;
  214. request.MaximumResponseHeadersLength = 4;
  215. // Set credentials to use for this request.
  216. request.Credentials = CredentialCache.DefaultCredentials;
  217. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  218. if (!File.Exists(Program.folder + @"\in\" + response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1]) && !File.Exists(Program.folder + @"\in\done\" + response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1]))
  219. {
  220. text_res("Copie de " + response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1]);
  221. Stream receiveStream = response.GetResponseStream();
  222. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  223. StreamWriter writeStream = new StreamWriter(Program.folder + @"\in\" + response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1], false, Encoding.UTF8);
  224. writeStream.Write(readStream.ReadToEnd());
  225. writeStream.Close();
  226. readStream.Close();
  227. line_res(" . OK");
  228. }
  229. response.Close();
  230. }
  231. }
  232. //private void streamtolist_globXMLS(StreamReader readStream, string file)
  233. //{
  234. // XmlSerializer xs = new XmlSerializer(typeof(List<Achats>));
  235. // List<Achats> ListAchats = new List<Achats>();
  236. // try
  237. // {
  238. // using (readStream)
  239. // ListAchats = xs.Deserialize(readStream) as List<Achats>;
  240. // }
  241. // catch (Exception ex)
  242. // {
  243. // err++;
  244. // line_res("ERREUR Fichier : " + file);
  245. // MessageBox.Show(file + "\r\n" + ex.Message, "streamtolist_glob");
  246. // }
  247. // foreach (Achats ac in ListAchats)
  248. // {
  249. // line_res(string.Format("GLOBAL Date {0} Produit {1} PTTC {2}", ac.Date, ac.KindCarbu, ac.MontantCarbu));
  250. // if (ok)
  251. // {
  252. // traite(ac);
  253. // }
  254. // }
  255. // if (ok && err == 0) files2move.Add(file); // Normalement err toujours à zero pour autoriser le traitement cad ok=true;
  256. //}
  257. //private void streamtolist(StreamReader readStream, string file)
  258. //{
  259. //}
  260. //private void streamtolist_uniq(StreamReader readStream, string file)
  261. //{
  262. // XmlSerializer xs = new XmlSerializer(typeof(Achats));
  263. // Achats ac = null;
  264. // try
  265. // {
  266. // using (readStream)
  267. // ac = xs.Deserialize(readStream) as Achats;
  268. // line_res(string.Format("UNIQ Date {0} Produit {1} PTTC {2}", ac.Date, ac.KindCarbu, ac.MontantCarbu));
  269. // if (ok)
  270. // {
  271. // traite(ac);
  272. // files2move.Add(file);
  273. // }
  274. // }
  275. // catch (Exception ex)
  276. // {
  277. // err++;
  278. // line_res("ERREUR Fichier : " + file);
  279. // MessageBox.Show(file + "\r\n" + ex.Message, "streamtolist_uniq");
  280. // }
  281. //}
  282. //private void traite(Achats ac)
  283. //{
  284. // if (ac.Volume > 0)
  285. // {
  286. // tsLbl1.Text = string.Format("Date {0} Bandeau {1} Type {2} Volume {3} Total {4}", ac.Date, ac.Bandeau, ac.KindCarbu, ac.Volume, ac.MontantTotal);
  287. // Application.DoEvents();
  288. // if (tb_vente.FindByepreuve_vtstation_vtvehi_vtprod_vtdate_vt(Program.key_ope, ac.StationId.ToString(), ac.Bandeau, ac.KindCarbu, ac.Date) == null)
  289. // {
  290. // DataSet1.tb_venteRow myrow = tb_vente.NewRow() as DataSet1.tb_venteRow;
  291. // DataSet1.tb_prestaRow mydata = null;
  292. // mydata = tb_presta.FindBysta_prprod_pr(ac.StationId.ToString(), ac.KindCarbu);
  293. // if (mydata != null)
  294. // ac.TxTva = (float)mydata.tva_pr;
  295. // else
  296. // ac.TxTva = 0;
  297. // myrow["epreuve_vt"] = Program.key_ope;
  298. // myrow["station_vt"] = ac.StationId.ToString();
  299. // myrow["vehi_vt"] = ac.Bandeau;
  300. // myrow["prod_vt"] = ac.KindCarbu;
  301. // myrow["date_vt"] = ac.Date;
  302. // myrow["qtt_vt"] = Math.Round(ac.Volume, 2);
  303. // myrow["pu_vt"] = Math.Round(ac.PrixCarbu, 3);
  304. // myrow["tva_vt"] = ac.TxTva;
  305. // myrow["ttc_vt"] = Math.Round(ac.MontantCarbu, 2);
  306. // myrow["ht_vt"] = Math.Round(ac.MontantCarbu / (1 + (ac.TxTva / 100)), 2);
  307. // tb_vente.Addtb_venteRow(myrow);
  308. // hasChanged = true;
  309. // }
  310. // }
  311. // foreach (PrestasFournies pf in ac.Prestas)
  312. // {
  313. // if (pf.Name != null)
  314. // {
  315. // pf.TxTva = 0;
  316. // string newName = pf.Name.ToUpper().Contains("FREE") ? (pf.Libel == null ? "Produit inconnu" : pf.Libel) : pf.Name;
  317. // if (tb_vente.FindByepreuve_vtstation_vtvehi_vtprod_vtdate_vt(Program.key_ope, ac.StationId.ToString(), ac.Bandeau, newName, ac.Date) == null)
  318. // {
  319. // DataSet1.tb_venteRow myrow = tb_vente.NewRow() as DataSet1.tb_venteRow;
  320. // myrow["epreuve_vt"] = Program.key_ope;
  321. // myrow["station_vt"] = ac.StationId.ToString();
  322. // myrow["vehi_vt"] = ac.Bandeau;
  323. // myrow["prod_vt"] = newName;
  324. // myrow["date_vt"] = ac.Date;
  325. // myrow["qtt_vt"] = Math.Round(pf.Quantity, 2);
  326. // myrow["pu_vt"] = Math.Round(pf.PrixUnitaire, 2);
  327. // myrow["tva_vt"] = pf.TxTva; // pf.TxTva == 0 ? 20 : pf.TxTva; ;
  328. // myrow["ttc_vt"] = Math.Round(pf.Total, 2);
  329. // myrow["ht_vt"] = Math.Round(pf.Total, 2); // Math.Round(pf.Total / (1 + ( pf.TxTva / 100)), 2);
  330. // tb_vente.Addtb_venteRow(myrow);
  331. // hasChanged = true;
  332. // }
  333. // }
  334. // }
  335. // tsLbl1.Text = "";
  336. //}
  337. private void Traite(Vente ac)
  338. {
  339. if (ac.qtt_vt > 0)
  340. {
  341. tsLbl1.Text = string.Format("Date {0} Bandeau {1} Type {2} Volume {3} Total {4}", ac.date_vt, ac.vehi_vt, ac.prod_vt, ac.qtt_vt, ac.ttc_vt);
  342. Application.DoEvents();
  343. if (tb_vente.FindByepreuve_vtstation_vtvehi_vtprod_vtdate_vt(Program.key_ope, ac.station_vt, ac.vehi_vt, ac.prod_vt, ac.date_vt) == null)
  344. {
  345. DataSet1.tb_venteRow myrow = tb_vente.NewRow() as DataSet1.tb_venteRow;
  346. DataSet1.tb_prestaRow mydata = null;
  347. mydata = tb_presta.FindBysta_prprod_pr(ac.station_vt, ac.prod_vt);
  348. if (mydata != null)
  349. ac.txtva_vt = (float)mydata.tva_pr;
  350. else
  351. ac.txtva_vt = 0;
  352. myrow["epreuve_vt"] = Program.key_ope;
  353. myrow["station_vt"] = ac.station_vt;
  354. myrow["vehi_vt"] = ac.vehi_vt;
  355. myrow["prod_vt"] = ac.prod_vt;
  356. myrow["date_vt"] = ac.date_vt;
  357. myrow["qtt_vt"] = Math.Round(ac.qtt_vt, 2);
  358. myrow["pu_vt"] = Math.Round(ac.pu_vt, 3);
  359. myrow["tva_vt"] = ac.txtva_vt;
  360. myrow["ttc_vt"] = Math.Round(ac.ttc_vt, 2);
  361. myrow["ht_vt"] = Math.Round(ac.ttc_vt / (1 + (ac.txtva_vt / 100)), 2);
  362. tb_vente.Addtb_venteRow(myrow);
  363. hasChanged = true;
  364. }
  365. }
  366. //foreach (PrestasFournies pf in ac.Prestas)
  367. //{
  368. // if (pf.Name != null)
  369. // {
  370. // pf.TxTva = 0;
  371. // string newName = pf.Name.ToUpper().Contains("FREE") ? (pf.Libel == null ? "Produit inconnu" : pf.Libel) : pf.Name;
  372. // if (tb_vente.FindByepreuve_vtstation_vtvehi_vtprod_vtdate_vt(Program.key_ope, ac.StationId.ToString(), ac.Bandeau, newName, ac.Date) == null)
  373. // {
  374. // DataSet1.tb_venteRow myrow = tb_vente.NewRow() as DataSet1.tb_venteRow;
  375. // myrow["epreuve_vt"] = Program.key_ope;
  376. // myrow["station_vt"] = ac.StationId.ToString();
  377. // myrow["vehi_vt"] = ac.Bandeau;
  378. // myrow["prod_vt"] = newName;
  379. // myrow["date_vt"] = ac.Date;
  380. // myrow["qtt_vt"] = Math.Round(pf.Quantity, 2);
  381. // myrow["pu_vt"] = Math.Round(pf.PrixUnitaire, 2);
  382. // myrow["tva_vt"] = pf.TxTva; // pf.TxTva == 0 ? 20 : pf.TxTva; ;
  383. // myrow["ttc_vt"] = Math.Round(pf.Total, 2);
  384. // myrow["ht_vt"] = Math.Round(pf.Total, 2); // Math.Round(pf.Total / (1 + ( pf.TxTva / 100)), 2);
  385. // tb_vente.Addtb_venteRow(myrow);
  386. // hasChanged = true;
  387. // }
  388. // }
  389. //}
  390. tsLbl1.Text = "";
  391. }
  392. private void text_res(string text)
  393. {
  394. textResult.Text += text;
  395. textResult.ScrollToCaret();
  396. Application.DoEvents();
  397. }
  398. private void line_res(string text)
  399. {
  400. textResult.Text += (text + "\r\n");
  401. textResult.SelectionStart = textResult.TextLength;
  402. textResult.ScrollToCaret();
  403. Application.DoEvents();
  404. }
  405. private void bt_loadVT_Click(object sender, EventArgs e)
  406. {
  407. load_vente();
  408. }
  409. private void check_modif_CheckedChanged(object sender, EventArgs e)
  410. {
  411. dg_vente.AllowUserToDeleteRows = check_modif.Checked;
  412. dg_vente.ReadOnly = !check_modif.Checked;
  413. }
  414. private void dg_vente_CellEndEdit(object sender, DataGridViewCellEventArgs e)
  415. {
  416. hasChanged = true;
  417. }
  418. private void f_tools_FormClosing(object sender, FormClosingEventArgs e)
  419. {
  420. if (hasChanged)
  421. if (MessageBox.Show("Voulez-vous sauvegarder les modifications ?", "Modifications non sauvegardées", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
  422. DbUtil.SaveToJson<DataSet1.tb_venteDataTable>(Program.subfolder + @"\vente.json", tb_vente);
  423. e.Cancel = false;
  424. }
  425. private void f_tools_Load(object sender, EventArgs e)
  426. {
  427. }
  428. private void f_tools_MouseDoubleClick(object sender, MouseEventArgs e)
  429. {
  430. string input = "";
  431. if (Program.ShowInputDialog("Contrôle", "Entrez le mot de passe", ref input, true) == DialogResult.OK)
  432. splitContainer1.Enabled = (input == "fuel2016");
  433. }
  434. }
  435. }