FormBatch.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. using qdr.app.studiou.orders2printpack.Extensions;
  2. using qdr.app.studiou.orders2printpack.Properties;
  3. using Quadarax.Foundation.Core.Data;
  4. using Quadarax.Foundation.Core.IO;
  5. using Quadarax.Foundation.Core.Value;
  6. using Quadarax.Foundation.Core.Value.Extensions;
  7. using System.Data;
  8. using System.IO.Abstractions;
  9. namespace qdr.app.studiou.orders2printpack
  10. {
  11. public partial class FormBatch : Form
  12. {
  13. #region *** Constants ***
  14. private const string CS_COL_SOURCE_PATH = "LocalPath";
  15. private const string CS_COL_ID = "LocalID";
  16. private const string CS_COL_OUTPUT = "OutputFileName";
  17. private const string CS_COL_EXTERNALORDER = "ExternalOrder";
  18. private const string CS_COL_EXTERNALORDERDATE = "ExternalOrderDate";
  19. private const string CS_TAG_LB = "{";
  20. private const string CS_TAG_RB = "}";
  21. private const string CS_TAG_EXT = "ext";
  22. private const string CS_TAG_FILE = "file";
  23. private const string CS_TAG_ORDINAL = "ordinal";
  24. #endregion
  25. #region *** Private Fields ***
  26. private DataTable _source = new();
  27. private readonly Dictionary<string, int> _sourceColOrdinals = [];
  28. private readonly List<string> _sourcePathCache = [];
  29. private readonly IFileSystem _fs = new FileSystem();
  30. private string _outputPath;
  31. #endregion
  32. #region *** Constructor ***
  33. public FormBatch()
  34. {
  35. InitializeComponent();
  36. _outputPath = string.Empty;
  37. }
  38. #endregion
  39. #region *** Form Handlers ***
  40. private void FormMain_Load(object sender, EventArgs e)
  41. {
  42. Text = $"{Application.ProductName} v{Application.ProductVersion}";
  43. RefreshToolButtons();
  44. }
  45. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  46. private void butOpenOrdersFile_Click(object sender, EventArgs e)
  47. {
  48. if (dlgOpenFile.ShowDialog() == DialogResult.OK)
  49. OpenOrderBatchFile(dlgOpenFile.FileName);
  50. RefreshToolButtons();
  51. }
  52. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  53. private void butOpenSource_Click(object sender, EventArgs e)
  54. {
  55. dlgOpenDir.Description = "Otevřít složku se zdrojovými (RAW) soubory...";
  56. dlgOpenDir.UseDescriptionForTitle = true;
  57. dlgOpenDir.InitialDirectory = AppSettings.Default.LastSourceDir;
  58. if (dlgOpenDir.ShowDialog() == DialogResult.OK)
  59. {
  60. BlockErrorHandled(() =>
  61. {
  62. if (!string.IsNullOrEmpty(_outputPath) && dlgOpenDir.SelectedPath == _outputPath)
  63. throw new Exception($"Vstupní složka '{dlgOpenDir.SelectedPath}' je stejná jako výstupní.");
  64. AppSettings.Default.LastSourceDir = dlgOpenDir.SelectedPath;
  65. AppSettings.Default.Save();
  66. OpenSourceDir(dlgOpenDir.SelectedPath);
  67. });
  68. }
  69. RefreshToolButtons();
  70. }
  71. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  72. private void butOutputDir_Click(object sender, EventArgs e)
  73. {
  74. dlgOpenDir.Description = "Otevřít složku pro výstup...";
  75. dlgOpenDir.UseDescriptionForTitle = true;
  76. dlgOpenDir.InitialDirectory = AppSettings.Default.LastOutputDir;
  77. if (dlgOpenDir.ShowDialog() == DialogResult.OK)
  78. {
  79. BlockErrorHandled(() =>
  80. {
  81. if (!string.IsNullOrEmpty(AppSettings.Default.LastSourceDir) && dlgOpenDir.SelectedPath == AppSettings.Default.LastSourceDir)
  82. throw new Exception($"Výstupní složka '{dlgOpenDir.SelectedPath}' je stejná jako vstupní.");
  83. _outputPath = dlgOpenDir.SelectedPath;
  84. Log($"Otevřena složka výstupu '{_outputPath}'");
  85. AppSettings.Default.LastOutputDir = dlgOpenDir.SelectedPath;
  86. AppSettings.Default.Save();
  87. tbOutputDir.Text = _outputPath;
  88. });
  89. }
  90. RefreshToolButtons();
  91. }
  92. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  93. private void tsbCheck_Click(object sender, EventArgs e)
  94. {
  95. CheckSourceOrderFile();
  96. RefreshToolButtons();
  97. }
  98. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  99. private void tsbDo_Click(object sender, EventArgs e)
  100. {
  101. ProcessSourceFile();
  102. RefreshToolButtons();
  103. }
  104. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  105. private void tsbAddSourceDir_Click(object sender, EventArgs e)
  106. {
  107. dlgOpenDir.Description = "Otevřít další složku se zdrojovými (RAW) soubory...";
  108. dlgOpenDir.UseDescriptionForTitle = true;
  109. dlgOpenDir.InitialDirectory = AppSettings.Default.LastSourceDir;
  110. if (dlgOpenDir.ShowDialog() == DialogResult.OK)
  111. {
  112. Log("Přidávám další zdrojovou složku...");
  113. OpenSourceDir(dlgOpenDir.SelectedPath, true);
  114. }
  115. RefreshToolButtons();
  116. }
  117. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  118. private void tsbProtocol_Click(object sender, EventArgs e)
  119. {
  120. var dlg = new dlgProtocol();
  121. if (dlg.ShowDialog(this) == DialogResult.OK)
  122. GenerateProtocol(dlg.ExternalOrder, dlg.ExternalOrderDate, dlg.ProtocolFile);
  123. }
  124. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  125. private void lbNotMapped_MouseDoubleClick(object sender, MouseEventArgs e)
  126. {
  127. if (lbNotMapped.SelectedIndices.Count == 0)
  128. return;
  129. var id = (int?)lbNotMapped.SelectedValue;
  130. if (id == null)
  131. return;
  132. var row = _source.Rows[id.GetValueOrDefault()];
  133. var fileName = _fs.Path.GetFileName(row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColUri]));
  134. dlgOpenFile.Title = "Vyberte zdrojový soubor soubor pro záznam...";
  135. dlgOpenFile.InitialDirectory = AppSettings.Default.LastSourceDir;
  136. dlgOpenFile.FileName = fileName;
  137. dlgOpenFile.Filter = "Všechny soubory|*.*";
  138. if (dlgOpenFile.ShowDialog() == DialogResult.OK)
  139. {
  140. var sourcePath = dlgOpenFile.FileName;
  141. row.SetField(_sourceColOrdinals[CS_COL_SOURCE_PATH], sourcePath);
  142. RefreshToolButtons();
  143. }
  144. }
  145. [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  146. private void tsbSettings_Click(object sender, EventArgs e)
  147. {
  148. var dlg = new dlgSettings();
  149. dlg.ShowDialog();
  150. }
  151. #endregion
  152. #region *** Private Methods ***
  153. #region **** Common ****
  154. private void Log(string message)
  155. {
  156. lbLog.Items.Insert(0, message);
  157. }
  158. private int GetOrderCount()
  159. {
  160. return _source.AsEnumerable().Select(x => x.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo])).Distinct().Count();
  161. }
  162. private int GetLinesCount()
  163. {
  164. return _source.AsEnumerable().Count();
  165. }
  166. private string? GetSourceFullFileName(string? webUrl)
  167. {
  168. if (string.IsNullOrEmpty(webUrl))
  169. return null;
  170. var fileName = Path.GetFileName(webUrl);
  171. var sourcePath = _sourcePathCache.FirstOrDefault(x => string.Equals(Path.GetFileName(x), fileName));
  172. if (string.IsNullOrEmpty(sourcePath))
  173. Log($"Soubor '{fileName}' nebyl nalezen ve zdrojové složce.");
  174. return sourcePath;
  175. }
  176. private static string NormalizeColumnName(string name)
  177. {
  178. return name.ToLower().Replace(" ", "_");
  179. }
  180. private void ApplyRowToParametrizedString(DataRow row, ParameterizedString ps)
  181. {
  182. foreach (DataColumn col in row.Table.Columns)
  183. {
  184. var ord = _sourceColOrdinals[col.ColumnName];
  185. ps.AddOrSetParameter(NormalizeColumnName(col.ColumnName), row[ord]?.ToString()!);
  186. }
  187. }
  188. private void BlockErrorHandled(Action block)
  189. {
  190. try
  191. {
  192. block();
  193. }
  194. catch (Exception ex)
  195. {
  196. Log("Error: " + ex.Message);
  197. MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  198. RefreshToolButtons();
  199. }
  200. }
  201. #endregion
  202. #region **** Bussiness ****
  203. private void OpenOrderBatchFile(string fileName)
  204. {
  205. BlockErrorHandled(() =>
  206. {
  207. _source = CsvHelper.CsvToDataTable(_fs, fileName, AppSettings.Default.CSVDelimiter);
  208. _source.Columns.Add(new DataColumn(CS_COL_SOURCE_PATH, typeof(string)));
  209. _source.Columns.Add(new DataColumn(CS_COL_ID, typeof(int)));
  210. _source.Columns.Add(new DataColumn(CS_COL_OUTPUT, typeof(string)));
  211. _source.Columns.Add(new DataColumn(CS_COL_EXTERNALORDER, typeof(string)));
  212. _source.Columns.Add(new DataColumn(CS_COL_EXTERNALORDERDATE, typeof(string)));
  213. _sourceColOrdinals.Clear();
  214. for (int i = 0; i < _source.Columns.Count; i++)
  215. _sourceColOrdinals.Add(_source.Columns[i].ColumnName.Replace("\"", ""), i);
  216. var invalidRows = new List<DataRow>();
  217. foreach (DataRow row in _source.Rows)
  218. {
  219. if (string.Equals(row[_sourceColOrdinals[AppSettings.Default.MapColUri]]?.ToString(), "null", StringComparison.CurrentCultureIgnoreCase))
  220. invalidRows.Add(row);
  221. }
  222. foreach (var row in invalidRows)
  223. _source.Rows.Remove(row);
  224. Log($"{invalidRows.Count} položek ignorováno, nebylo vyplněno URL");
  225. var cntId = 0;
  226. foreach (DataRow row in _source.Rows)
  227. row.SetField(_sourceColOrdinals[CS_COL_ID], cntId++);
  228. var cntOrders = GetOrderCount();
  229. var cntLines = GetLinesCount();
  230. Log($"Soubor {fileName} načten. Počet objednávek: {cntOrders}, počet záznamů: {cntLines}");
  231. tbOrdersSourceFile.Text = fileName;
  232. tspOrdersCount.Text = $"Objednávek: {cntOrders}";
  233. });
  234. }
  235. private void OpenSourceDir(string pathToSourceFolder, bool appendCache = false)
  236. {
  237. BlockErrorHandled(() =>
  238. {
  239. var fsrch = new FileSearch(pathToSourceFolder, true);
  240. if (!appendCache)
  241. _sourcePathCache.Clear();
  242. tbSourceDir.Text = pathToSourceFolder;
  243. Log($"Procházím všechny soubory {AppSettings.Default.SourceSearchPattern} ve složce '{pathToSourceFolder}'...");
  244. Log("Tato operace může chvíli trvat!");
  245. var files = fsrch.Search(new[] { AppSettings.Default.SourceSearchPattern, "*" });
  246. if (files.Length == 0)
  247. throw new Exception($"Nenalezeny žádné soubory pro zpracování ve složce '{pathToSourceFolder}'.");
  248. foreach (var file in files)
  249. if (!_sourcePathCache.Any(x => x == file))
  250. _sourcePathCache.Add(file);
  251. tsbFiles.Text = "Souborů: " + _sourcePathCache.Count.ToString();
  252. Log($"Nalezeno {files.Length} souborů.");
  253. });
  254. }
  255. private void CheckSourceOrderFile()
  256. {
  257. ssProgress.Value = 0;
  258. int cntFailed = 0;
  259. BlockErrorHandled(() =>
  260. {
  261. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  262. ssProgress.Maximum = rows.Count();
  263. foreach (var row in rows)
  264. {
  265. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  266. var sourceUrl = row[_sourceColOrdinals[AppSettings.Default.MapColUri]]?.ToString();
  267. var sourcePath = GetSourceFullFileName(sourceUrl);
  268. if (sourcePath == null) cntFailed++;
  269. row.SetField(_sourceColOrdinals[CS_COL_SOURCE_PATH], sourcePath);
  270. ssProgress.Increment(1);
  271. }
  272. });
  273. tsbNotFound.Text = $"Nenalezeno: {cntFailed}";
  274. ssProgress.Value = 0;
  275. }
  276. private void ProcessSourceFile()
  277. {
  278. ssProgress.Value = 0;
  279. BlockErrorHandled(() =>
  280. {
  281. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  282. if (rows.Any())
  283. throw new Exception("Některé řádky nebyly zkontrolovány. Proveďte kontrolu zdrojových souborů (1. Kontrola).");
  284. rows = _source.AsEnumerable();
  285. //var colNames = _source.Columns.Cast<DataColumn>().Select(x => NormalizeColumnName(x.ColumnName)).ToArray();
  286. if (AppSettings.Default.CleanupOutputDir)
  287. {
  288. Log($"Čistím složku výstupu '{_outputPath}' ...");
  289. CleanupDirectory(_outputPath);
  290. }
  291. ssProgress.Maximum = rows.Count();
  292. var outputFileNameBuilder = new ParameterizedString(AppSettings.Default.OutputFileMask, CS_TAG_LB, CS_TAG_RB);
  293. foreach (var row in rows)
  294. {
  295. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  296. var sourceUrl = row[_sourceColOrdinals[AppSettings.Default.MapColUri]]?.ToString();
  297. var qty = int.Parse(row[_sourceColOrdinals[AppSettings.Default.MapColQuantity]]?.ToString()!);
  298. var sourcePath = row[_sourceColOrdinals[CS_COL_SOURCE_PATH]]?.ToString();
  299. var sourceExt = _fs.Path.GetExtension(sourcePath);
  300. var sourceFileName = _fs.Path.GetFileNameWithoutExtension(sourcePath);
  301. ApplyRowToParametrizedString(row, outputFileNameBuilder);
  302. outputFileNameBuilder.AddOrSetParameter(CS_TAG_EXT, sourceExt!);
  303. outputFileNameBuilder.AddOrSetParameter(CS_TAG_FILE, sourceFileName!);
  304. for (int i = 0; i < qty; i++)
  305. {
  306. outputFileNameBuilder.AddOrSetParameter(CS_TAG_ORDINAL, i.ToString().PadLeft(3, '0'));
  307. var outputFileName = _fs.Path.GetFileName(outputFileNameBuilder.ToString());
  308. var outputFilePath = _fs.Path.GetDirectoryName(outputFileNameBuilder.ToString())!;
  309. var outputFileNameSanitized = FileUtils.SanitizedFileName(_fs, outputFileName);
  310. var outputPath = _fs.Path.Combine(_outputPath, _fs.Path.Combine(outputFilePath, outputFileNameSanitized));
  311. _fs.Directory.CreateDirectory(_fs.Path.GetDirectoryName(outputPath)!);
  312. _fs.File.Copy(sourcePath!, outputPath, true);
  313. Log($"Soubor '{outputPath}' vytvořen.");
  314. row.SetField(_sourceColOrdinals[CS_COL_OUTPUT], outputPath);
  315. }
  316. ssProgress.Increment(1);
  317. }
  318. });
  319. ssProgress.Value = 0;
  320. }
  321. private void GenerateProtocol(string externalOrder, DateTime externalOrderDate, string protocolFile)
  322. {
  323. BlockErrorHandled(() =>
  324. {
  325. Log($"Nastavuji číslo externí objednávky: {externalOrder} a datum: {externalOrderDate.ToShortDateString()} ...");
  326. foreach (var row in _source.AsEnumerable())
  327. {
  328. row.SetField(_sourceColOrdinals[CS_COL_EXTERNALORDER], externalOrder);
  329. row.SetField(_sourceColOrdinals[CS_COL_EXTERNALORDERDATE], externalOrderDate.ToFileUtcString());
  330. }
  331. Log($"Generuji protokol ...");
  332. CsvUtils.DataTableToCsv(_fs, _source, protocolFile, AppSettings.Default.CSVDelimiter, (column) => { return NormalizeColumnName(column); });
  333. Log($"Protokol uložen do souboru '{protocolFile}'.");
  334. });
  335. }
  336. #endregion
  337. #region **** Refreshes ****
  338. private void RefreshToolButtons()
  339. {
  340. var canBeChecked = GetOrderCount() > 0 && _sourcePathCache.Count > 0;
  341. var canBeProcess = canBeChecked && !_source.AsEnumerable().Any(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH]))) && !string.IsNullOrEmpty(_outputPath);
  342. var canBeCreateProtocol = canBeProcess && _source.AsEnumerable().All(x => !string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_OUTPUT])));
  343. tsbCheck.Enabled = canBeChecked;
  344. tsbDo.Enabled = canBeProcess;
  345. tsbProtocol.Enabled = canBeCreateProtocol;
  346. RefreshNotMappedList();
  347. }
  348. private void RefreshNotMappedList()
  349. {
  350. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  351. var list = new List<Tuple<int, string>>();
  352. foreach (var row in rows)
  353. {
  354. var id = row.Field<int>(_sourceColOrdinals[CS_COL_ID]);
  355. var fileName = _fs.Path.GetFileName(row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColUri]));
  356. var productName = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColProductFormat]);
  357. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  358. list.Add(new Tuple<int, string>(id, $"{fileName} [Jméno: {productName} / Obj.:{orderNo}]"));
  359. }
  360. lbNotMapped.DisplayMember = "Item2";
  361. lbNotMapped.ValueMember = "Item1";
  362. lbNotMapped.DataSource = list;
  363. lbNotMapped.Update();
  364. }
  365. #endregion
  366. #region **** Support opperations ****
  367. public static void CleanupDirectory(string directoryPath)
  368. {
  369. return;
  370. /*
  371. if (string.IsNullOrWhiteSpace(directoryPath))
  372. throw new ArgumentException("Directory path cannot be null or empty.", nameof(directoryPath));
  373. if (!Directory.Exists(directoryPath))
  374. throw new DirectoryNotFoundException($"Directory not found: {directoryPath}");
  375. try
  376. {
  377. var di = new DirectoryInfo(directoryPath);
  378. foreach (var file in di.GetFiles())
  379. {
  380. try
  381. {
  382. file.Delete();
  383. }
  384. catch { }
  385. }
  386. foreach (var dir in di.GetDirectories())
  387. {
  388. try
  389. {
  390. dir.Delete(true);
  391. }
  392. catch { }
  393. }
  394. }
  395. catch (Exception)
  396. {
  397. throw;
  398. }
  399. */
  400. }
  401. #endregion
  402. #endregion
  403. }
  404. }