FormBatch.cs 19 KB

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