f_tools.cs 20 KB

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