FormBatch.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. Log ("Kontrola duplicit...");
  252. var checkDuplicities = _sourcePathCache.Select(x => _fs.Path.GetFileName(x)).GetDuplicates();
  253. if (checkDuplicities.Count() > 0)
  254. {
  255. Log ("Duplicity nalezeny pro následující soubory:");
  256. foreach (var dup in checkDuplicities)
  257. {
  258. Log(dup);
  259. }
  260. }
  261. else
  262. {
  263. Log("Žádné duplicity nenalezeny.");
  264. }
  265. tsbFiles.Text = "Souborů: " + _sourcePathCache.Count.ToString();
  266. Log($"Nalezeno {files.Length} souborů.");
  267. });
  268. }
  269. private void CheckSourceOrderFile()
  270. {
  271. ssProgress.Value = 0;
  272. int cntFailed = 0;
  273. BlockErrorHandled(() =>
  274. {
  275. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  276. ssProgress.Maximum = rows.Count();
  277. foreach (var row in rows)
  278. {
  279. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  280. var sourceUrl = row[_sourceColOrdinals[AppSettings.Default.MapColUri]]?.ToString();
  281. var sourcePath = GetSourceFullFileName(sourceUrl);
  282. if (sourcePath == null) cntFailed++;
  283. row.SetField(_sourceColOrdinals[CS_COL_SOURCE_PATH], sourcePath);
  284. ssProgress.Increment(1);
  285. }
  286. });
  287. tsbNotFound.Text = $"Nenalezeno: {cntFailed}";
  288. ssProgress.Value = 0;
  289. }
  290. private void ProcessSourceFile()
  291. {
  292. ssProgress.Value = 0;
  293. BlockErrorHandled(() =>
  294. {
  295. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  296. if (rows.Any())
  297. throw new Exception("Některé řádky nebyly zkontrolovány. Proveďte kontrolu zdrojových souborů (1. Kontrola).");
  298. rows = _source.AsEnumerable();
  299. //var colNames = _source.Columns.Cast<DataColumn>().Select(x => NormalizeColumnName(x.ColumnName)).ToArray();
  300. if (AppSettings.Default.CleanupOutputDir)
  301. {
  302. Log($"Čistím složku výstupu '{_outputPath}' ...");
  303. CleanupDirectory(_outputPath);
  304. }
  305. ssProgress.Maximum = rows.Count();
  306. var outputFileNameBuilder = new ParameterizedString(AppSettings.Default.OutputFileMask, CS_TAG_LB, CS_TAG_RB);
  307. foreach (var row in rows)
  308. {
  309. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  310. var sourceUrl = row[_sourceColOrdinals[AppSettings.Default.MapColUri]]?.ToString();
  311. var qty = int.Parse(row[_sourceColOrdinals[AppSettings.Default.MapColQuantity]]?.ToString()!);
  312. var sourcePath = row[_sourceColOrdinals[CS_COL_SOURCE_PATH]]?.ToString();
  313. var sourceExt = _fs.Path.GetExtension(sourcePath);
  314. var sourceFileName = _fs.Path.GetFileNameWithoutExtension(sourcePath);
  315. var sourceEmail = row[_sourceColOrdinals[AppSettings.Default.MapColEmail]]?.ToString();
  316. var sourceFormat = row[_sourceColOrdinals[AppSettings.Default.MapColProductFormat]]?.ToString();
  317. var isDigital = (string.IsNullOrEmpty(sourceFormat) ? false : sourceFormat.Contains(AppSettings.Default.FormatDigitalContains, StringComparison.CurrentCultureIgnoreCase)) && !string.IsNullOrEmpty(sourceEmail);
  318. ApplyRowToParametrizedString(row, outputFileNameBuilder);
  319. outputFileNameBuilder.AddOrSetParameter(CS_TAG_EXT, sourceExt!);
  320. outputFileNameBuilder.AddOrSetParameter(CS_TAG_FILE, sourceFileName!);
  321. for (int i = 0; i < qty; i++)
  322. {
  323. outputFileNameBuilder.AddOrSetParameter(CS_TAG_ORDINAL, i.ToString().PadLeft(3, '0'));
  324. var outputFileName = _fs.Path.GetFileName(outputFileNameBuilder.ToString());
  325. var outputFilePath = _fs.Path.GetDirectoryName(outputFileNameBuilder.ToString())!;
  326. var outputFileNameSanitized = FileUtils.SanitizedFileName(_fs, outputFileName);
  327. var outputPath = _fs.Path.Combine(_outputPath, _fs.Path.Combine(outputFilePath, outputFileNameSanitized));
  328. if (isDigital)
  329. {
  330. outputPath = _fs.Path.Combine(_outputPath,outputFilePath);
  331. outputPath = _fs.Path.Combine(outputPath, sourceEmail!);
  332. outputPath = _fs.Path.Combine(outputPath, outputFileNameSanitized);
  333. }
  334. _fs.Directory.CreateDirectory(_fs.Path.GetDirectoryName(outputPath)!);
  335. _fs.File.Copy(sourcePath!, outputPath, true);
  336. Log($"Soubor '{outputPath}' vytvořen.");
  337. row.SetField(_sourceColOrdinals[CS_COL_OUTPUT], outputPath);
  338. }
  339. ssProgress.Increment(1);
  340. }
  341. });
  342. ssProgress.Value = 0;
  343. }
  344. private void GenerateProtocol(string externalOrder, DateTime externalOrderDate, string protocolFile)
  345. {
  346. BlockErrorHandled(() =>
  347. {
  348. Log($"Nastavuji číslo externí objednávky: {externalOrder} a datum: {externalOrderDate.ToShortDateString()} ...");
  349. foreach (var row in _source.AsEnumerable())
  350. {
  351. row.SetField(_sourceColOrdinals[CS_COL_EXTERNALORDER], externalOrder);
  352. row.SetField(_sourceColOrdinals[CS_COL_EXTERNALORDERDATE], externalOrderDate.ToFileUtcString());
  353. }
  354. Log($"Generuji protokol ...");
  355. CsvUtils.DataTableToCsv(_fs, _source, protocolFile, AppSettings.Default.CSVDelimiter, (column) => { return NormalizeColumnName(column); });
  356. Log($"Protokol uložen do souboru '{protocolFile}'.");
  357. });
  358. }
  359. #endregion
  360. #region **** Refreshes ****
  361. private void RefreshToolButtons()
  362. {
  363. var canBeChecked = GetOrderCount() > 0 && _sourcePathCache.Count > 0;
  364. var canBeProcess = canBeChecked && !_source.AsEnumerable().Any(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH]))) && !string.IsNullOrEmpty(_outputPath);
  365. var canBeCreateProtocol = canBeProcess && _source.AsEnumerable().All(x => !string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_OUTPUT])));
  366. tsbCheck.Enabled = canBeChecked;
  367. tsbDo.Enabled = canBeProcess;
  368. tsbProtocol.Enabled = canBeCreateProtocol;
  369. RefreshNotMappedList();
  370. }
  371. private void RefreshNotMappedList()
  372. {
  373. var rows = _source.AsEnumerable().Where(x => string.IsNullOrEmpty(x.Field<string>(_sourceColOrdinals[CS_COL_SOURCE_PATH])));
  374. var list = new List<Tuple<int, string>>();
  375. foreach (var row in rows)
  376. {
  377. var id = row.Field<int>(_sourceColOrdinals[CS_COL_ID]);
  378. var fileName = _fs.Path.GetFileName(row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColUri]));
  379. var productName = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColProductFormat]);
  380. var orderNo = row.Field<string>(_sourceColOrdinals[AppSettings.Default.MapColOrderNo]);
  381. list.Add(new Tuple<int, string>(id, $"{fileName} [Jméno: {productName} / Obj.:{orderNo}]"));
  382. }
  383. lbNotMapped.DisplayMember = "Item2";
  384. lbNotMapped.ValueMember = "Item1";
  385. lbNotMapped.DataSource = list;
  386. lbNotMapped.Update();
  387. }
  388. #endregion
  389. #region **** Support opperations ****
  390. public static void CleanupDirectory(string directoryPath)
  391. {
  392. return;
  393. /*
  394. if (string.IsNullOrWhiteSpace(directoryPath))
  395. throw new ArgumentException("Directory path cannot be null or empty.", nameof(directoryPath));
  396. if (!Directory.Exists(directoryPath))
  397. throw new DirectoryNotFoundException($"Directory not found: {directoryPath}");
  398. try
  399. {
  400. var di = new DirectoryInfo(directoryPath);
  401. foreach (var file in di.GetFiles())
  402. {
  403. try
  404. {
  405. file.Delete();
  406. }
  407. catch { }
  408. }
  409. foreach (var dir in di.GetDirectories())
  410. {
  411. try
  412. {
  413. dir.Delete(true);
  414. }
  415. catch { }
  416. }
  417. }
  418. catch (Exception)
  419. {
  420. throw;
  421. }
  422. */
  423. }
  424. #endregion
  425. #endregion
  426. }
  427. }