FormBatch.cs 20 KB

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