FormProductEdit.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. using qdr.app.studiou.orders2printpack.Extensions;
  2. using qdr.app.studiou.orders2printpack.ProductStorage;
  3. using qdr.app.studiou.orders2printpack.Properties;
  4. using Quadarax.Foundation.Core.IO;
  5. using Quadarax.Foundation.Core.Value;
  6. using Quadarax.Foundation.Core.Value.Generators;
  7. using System.ComponentModel;
  8. using System.Data;
  9. namespace qdr.app.studiou.orders2printpack
  10. {
  11. public partial class FormProductEdit : Form
  12. {
  13. #region *** Enumerations ***
  14. public enum DetailType
  15. {
  16. Product,
  17. Variant,
  18. Category
  19. }
  20. #endregion
  21. #region *** Private Fields ***
  22. private ProductStorage.ProductStorage _storage = new ProductStorage.ProductStorage();
  23. private DetailType _detailType = DetailType.Product;
  24. private ProductDto? _currentDetailProduct;
  25. private VariantDto? _currentDetailVariant;
  26. private CategoryDto? _currentDetailCategory;
  27. private TinyHash _hashGenerator = new TinyHash(10);
  28. private ProductDto _productClipboard = new ProductDto();
  29. private VariantDto _variantClipboard = new VariantDto();
  30. private CategoryDto _categoryClipboard = new CategoryDto();
  31. #endregion
  32. #region *** Constructor ***
  33. public FormProductEdit()
  34. {
  35. InitializeComponent();
  36. _storage.AppendVariantsFromString(AppSettings.Default.PredefinedVariants);
  37. _storage.AppendCategoriesFromString(AppSettings.Default.PredefinedCategories);
  38. tsslblOutput.Text = "Soubor nezadán";
  39. RefreshViews();
  40. RefreshTools();
  41. }
  42. #endregion
  43. #region *** Form Handlers ***
  44. protected override void OnClosing(CancelEventArgs e)
  45. {
  46. AppSettings.Default.PredefinedVariants = _storage.GetVariantsAsString();
  47. AppSettings.Default.PredefinedCategories = _storage.GetCategoriesAsString();
  48. AppSettings.Default.Save();
  49. base.OnClosing(e);
  50. }
  51. #endregion
  52. #region *** Toolbar Handlers ***
  53. private void tbbutSave_Click(object sender, EventArgs e)
  54. {
  55. SaveProductFile(tsslblOutput.Text);
  56. MessageBox.Show($"Data ({_storage.Products.Count()} položek) byla uložena do souboru '{tsslblOutput.Text}'", "Uloženo", MessageBoxButtons.OK, MessageBoxIcon.Information);
  57. }
  58. private void tbbutNew_Click(object sender, EventArgs e)
  59. {
  60. _storage = new ProductStorage.ProductStorage();
  61. _storage.AppendVariantsFromString(AppSettings.Default.PredefinedVariants);
  62. _storage.AppendCategoriesFromString(AppSettings.Default.PredefinedCategories);
  63. _currentDetailProduct = null;
  64. ClearDetail();
  65. RefreshViews();
  66. RefreshTools();
  67. }
  68. private void tbbutOpen_Click(object sender, EventArgs e)
  69. {
  70. if (dlgOpenFile.ShowDialog() == DialogResult.OK)
  71. OpenProductFile(dlgOpenFile.FileName);
  72. }
  73. private void tbbutProduct_Click(object sender, EventArgs e)
  74. {
  75. tbbutProduct.Checked = !tbbutProduct.Checked;
  76. RefreshProductList();
  77. }
  78. private void tbbutVariant_Click(object sender, EventArgs e)
  79. {
  80. tbbutVariant.Checked = !tbbutVariant.Checked;
  81. RefreshProductList();
  82. }
  83. private void tbbutProdNew_Click(object sender, EventArgs e)
  84. {
  85. AddNewProduct();
  86. RefreshTools();
  87. }
  88. private void tbbutProdVarNew_Click(object sender, EventArgs e)
  89. {
  90. AddNewProductVariant();
  91. RefreshTools();
  92. }
  93. private void tbbutDetSave_Click(object sender, EventArgs e)
  94. {
  95. switch (_detailType)
  96. {
  97. case DetailType.Product:
  98. SaveDetail(_currentDetailProduct);
  99. RefreshProductList();
  100. break;
  101. case DetailType.Variant:
  102. SaveDetail(_currentDetailVariant);
  103. RefreshVariantList();
  104. RefreshProductList();
  105. break;
  106. case DetailType.Category:
  107. SaveDetail(_currentDetailCategory);
  108. RefreshCategoryList();
  109. break;
  110. }
  111. }
  112. private void tbbutProdDelete_Click(object sender, EventArgs e)
  113. {
  114. var selected = GetSelectedProduct();
  115. if (selected == null)
  116. return;
  117. if (!ConfirmMessage($"Opravdu chcete smazat {selected.Length} vybraných produktů?"))
  118. return;
  119. _storage.RemoveProduct(selected.Select(x => x.GetIdentifier()).ToArray());
  120. RefreshProductList();
  121. RefreshTools();
  122. }
  123. private void tbbutProdClone_Click(object sender, EventArgs e)
  124. {
  125. var selected = GetSelectedProduct()?.FirstOrDefault();
  126. if (selected == null)
  127. return;
  128. CloneProduct(selected);
  129. RefreshTools();
  130. }
  131. private void tbbutDetCopy_Click(object sender, EventArgs e)
  132. {
  133. switch (_detailType)
  134. {
  135. case DetailType.Product:
  136. if (_currentDetailProduct == null)
  137. return;
  138. _currentDetailProduct.CopyTo(_productClipboard);
  139. break;
  140. case DetailType.Variant:
  141. if (_currentDetailVariant == null)
  142. return;
  143. _currentDetailVariant.CopyTo(_variantClipboard);
  144. break;
  145. case DetailType.Category:
  146. if (_currentDetailCategory == null)
  147. return;
  148. _currentDetailCategory.CopyTo(_categoryClipboard);
  149. break;
  150. }
  151. }
  152. private void tbbutDetPaste_Click(object sender, EventArgs e)
  153. {
  154. switch (_detailType)
  155. {
  156. case DetailType.Product:
  157. if (_currentDetailProduct == null)
  158. return;
  159. _productClipboard.Id = _currentDetailProduct.Id;
  160. ShowDetail(_productClipboard);
  161. break;
  162. case DetailType.Variant:
  163. if (_currentDetailVariant == null)
  164. return;
  165. ShowDetail(_variantClipboard);
  166. break;
  167. case DetailType.Category:
  168. if (_currentDetailCategory == null)
  169. return;
  170. ShowDetail(_categoryClipboard);
  171. break;
  172. }
  173. }
  174. private void tbbutVarNew_Click(object sender, EventArgs e)
  175. {
  176. AddNewVariant();
  177. }
  178. private void tbbutVarDelete_Click(object sender, EventArgs e)
  179. {
  180. var selected = GetSelectedVariants();
  181. if (selected == null)
  182. return;
  183. if (!ConfirmMessage($"Opravdu chcete smazat {selected.Length} vybraných variant?"))
  184. return;
  185. _storage.RemoveVariants(selected.Select(x => x.GetIdentifier()).ToArray());
  186. RefreshVariantList();
  187. }
  188. private void tbbutVarApply_Click(object sender, EventArgs e)
  189. {
  190. ApplyProductVariant();
  191. RefreshProductList();
  192. }
  193. private void tbbutCatNew_Click(object sender, EventArgs e)
  194. {
  195. AddNewCategory();
  196. }
  197. private void tbbutCatDelete_Click(object sender, EventArgs e)
  198. {
  199. var selected = GetSelectedCategories();
  200. if (selected == null)
  201. return;
  202. if (!ConfirmMessage($"Opravdu chcete smazat {selected.Length} vybraných kategorií?"))
  203. return;
  204. _storage.RemoveCategories(selected.Select(x => x.GetIdentifier()).ToArray());
  205. RefreshCategoryList();
  206. }
  207. private void tbbutCatApply_Click(object sender, EventArgs e)
  208. {
  209. }
  210. private void tbbutImport_Click(object sender, EventArgs e)
  211. {
  212. var dlg = new dlgImport();
  213. if (dlg.ShowDialog() == DialogResult.OK)
  214. {
  215. ImportProducts(dlg.ImportDir, dlg.UrlPrefix, dlg.ShortDescription, dlg.Description, dlg.UploadDate);
  216. }
  217. RefreshViews();
  218. RefreshTools();
  219. }
  220. #endregion
  221. #region *** Refreshes ***
  222. private void RefreshTools()
  223. {
  224. tsslblProducts.Text = $"Produkty: {_storage.Products.Count(x => !x.IsVariant)}";
  225. tsslblVariants.Text = $"Varianty: {_storage.Products.Count(x => x.IsVariant)}";
  226. }
  227. private void RefreshViews()
  228. {
  229. RefreshProductList();
  230. RefreshCategoryList();
  231. RefreshVariantList();
  232. }
  233. private void RefreshProductList()
  234. {
  235. BlockErrorHandled(() =>
  236. {
  237. lvProducts.SaveSelection();
  238. lvProducts.BindData(_storage.GetProductsView(tbbutProduct.Checked, tbbutVariant.Checked), itemCustomProcessCallback: (lvItem, data) =>
  239. {
  240. if (!data.IsValid)
  241. lvItem.BackColor = Color.IndianRed;
  242. });
  243. lvProducts.RestoreSelection();
  244. });
  245. }
  246. private void RefreshCategoryList()
  247. {
  248. BlockErrorHandled(() =>
  249. {
  250. lvCategories.SaveSelection();
  251. lvCategories.BindData(_storage.Categories);
  252. lvCategories.RestoreSelection();
  253. });
  254. }
  255. private void RefreshVariantList()
  256. {
  257. BlockErrorHandled(() =>
  258. {
  259. lvVariants.SaveSelection();
  260. lvVariants.BindData(_storage.Variants);
  261. lvVariants.RestoreSelection();
  262. });
  263. }
  264. #endregion
  265. #region *** ListView Handlers ***
  266. private void lvProducts_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
  267. {
  268. if (e.Item != null)
  269. {
  270. var product = _storage.GetProductByIdentifier(e.Item.Tag?.ToString());
  271. ShowDetail(product);
  272. _currentDetailProduct = product;
  273. }
  274. }
  275. private void lvVariants_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
  276. {
  277. if (e.Item != null)
  278. {
  279. var variant = _storage.GetVariantByIdentifier(e.Item.Tag?.ToString());
  280. ShowDetail(variant);
  281. _currentDetailVariant = variant;
  282. }
  283. }
  284. private void lvCategories_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
  285. {
  286. if (e.Item != null)
  287. {
  288. var category = _storage.GetCategoryByIdentifier(e.Item.Tag?.ToString());
  289. ShowDetail(category);
  290. _currentDetailCategory = category;
  291. }
  292. }
  293. #endregion
  294. #region *** Operations ***
  295. private void OpenProductFile(string fileName)
  296. {
  297. BlockErrorHandled(() =>
  298. {
  299. tsslblOutput.Text = fileName;
  300. if (!File.Exists(fileName))
  301. return;
  302. _storage.Load(fileName, ",");
  303. RefreshTools();
  304. RefreshViews();
  305. });
  306. }
  307. private void SaveProductFile(string? fileName)
  308. {
  309. BlockErrorHandled(() =>
  310. {
  311. if (fileName == null)
  312. return;
  313. tsslblOutput.Text = fileName;
  314. _storage.Save(fileName, ",");
  315. RefreshTools();
  316. });
  317. }
  318. private void ClearDetail()
  319. {
  320. BlockErrorHandled(() =>
  321. {
  322. tbdetId.Text = string.Empty;
  323. tbdetName.Text = string.Empty;
  324. tbdetSku.Text = string.Empty;
  325. tbdetShortDescription.Text = string.Empty;
  326. tbdetDescription.Text = string.Empty;
  327. cbdetCategories.BeginUpdate();
  328. cbdetCategories.Items.Clear();
  329. foreach (var category in _storage.Categories)
  330. cbdetCategories.Items.Add(category.Name);
  331. cbdetCategories.EndUpdate();
  332. tbdetPrice.Value = 0;
  333. tbdetUri.Text = string.Empty;
  334. cbdetParent.BeginUpdate();
  335. cbdetParent.Items.Clear();
  336. foreach (var product in _storage.GetProductsView(true, false).Select(x => x.Sku).Order())
  337. cbdetParent.Items.Add(product!);
  338. cbdetParent.EndUpdate();
  339. });
  340. }
  341. private void VisibleAllDetail(bool visible)
  342. {
  343. BlockErrorHandled(() =>
  344. {
  345. tbdetId.Visible = visible;
  346. ltbdetId.Visible = visible;
  347. tbdetName.Visible = visible;
  348. ltbdetName.Visible = visible;
  349. tbdetSku.Visible = visible;
  350. ltbdetSku.Visible = visible;
  351. tbdetShortDescription.Visible = visible;
  352. ltbdetShortDescription.Visible = visible;
  353. tbdetDescription.Visible = visible;
  354. ltbdetDescription.Visible = visible;
  355. tbdetPrice.Visible = visible;
  356. ltbdetPrice.Visible = visible;
  357. tbdetUri.Visible = visible;
  358. ltbdetUri.Visible = visible;
  359. cbdetCategories.Visible = visible;
  360. lcbdetCategories.Visible = visible;
  361. cbdetParent.Visible = visible;
  362. lcbdetParent.Visible = visible;
  363. });
  364. }
  365. private void ShowDetail(ProductDto? data)
  366. {
  367. BlockErrorHandled(() =>
  368. {
  369. _detailType = DetailType.Product;
  370. detProduct.Visible = false;
  371. ClearDetail();
  372. if (data == null)
  373. {
  374. detProduct.Visible = true;
  375. return;
  376. }
  377. var isVariant = data.IsVariant;
  378. tblbCaption.Text = isVariant ? "Varianta produktu" : "Produkt";
  379. VisibleAllDetail(true);
  380. if (isVariant)
  381. {
  382. // variant
  383. cbdetCategories.Visible = false;
  384. lcbdetCategories.Visible = false;
  385. }
  386. else
  387. {
  388. // head product
  389. cbdetParent.Visible = false;
  390. lcbdetParent.Visible = false;
  391. tbdetPrice.Visible = false;
  392. ltbdetPrice.Visible = false;
  393. cbdetCategories.SelectedIndex = cbdetCategories.FindStringExact(data.Category);
  394. }
  395. tbdetId.Text = data.Id.ToString();
  396. tbdetName.Text = data.ProductName;
  397. tbdetSku.Text = data.Sku;
  398. tbdetShortDescription.Text = data.ShortDescription;
  399. tbdetDescription.Text = data.Description;
  400. tbdetPrice.Value = data.Price;
  401. tbdetUri.Text = data.Uri;
  402. cbdetParent.SelectedIndex = cbdetParent.FindStringExact(data.ParentName);
  403. detProduct.Visible = true;
  404. });
  405. }
  406. private void ShowDetail(VariantDto? data)
  407. {
  408. BlockErrorHandled(() =>
  409. {
  410. _detailType = DetailType.Variant;
  411. tblbCaption.Text = "Varianta";
  412. detProduct.Visible = false;
  413. ClearDetail();
  414. if (data == null)
  415. {
  416. detProduct.Visible = true;
  417. return;
  418. }
  419. VisibleAllDetail(false);
  420. ltbdetName.Visible = true;
  421. tbdetName.Visible = true;
  422. ltbdetPrice.Visible = true;
  423. tbdetPrice.Visible = true;
  424. tbdetName.Text = data.Name;
  425. tbdetPrice.Value = data.Price;
  426. detProduct.Visible = true;
  427. });
  428. }
  429. private void ShowDetail(CategoryDto? data)
  430. {
  431. BlockErrorHandled(() =>
  432. {
  433. _detailType = DetailType.Category;
  434. tblbCaption.Text = "Kategorie";
  435. detProduct.Visible = false;
  436. ClearDetail();
  437. if (data == null)
  438. {
  439. detProduct.Visible = true;
  440. return;
  441. }
  442. VisibleAllDetail(false);
  443. ltbdetName.Visible = true;
  444. tbdetName.Visible = true;
  445. tbdetName.Text = data.Name;
  446. detProduct.Visible = true;
  447. });
  448. }
  449. private void SaveDetail(ProductDto? data)
  450. {
  451. BlockErrorHandled(() =>
  452. {
  453. if (data == null)
  454. return;
  455. data.ProductName = tbdetName.Text;
  456. if (!string.Equals(data.Sku,tbdetSku.Text,StringComparison.CurrentCultureIgnoreCase)){
  457. if (_storage.Products.Any(x => string.Equals(x.Sku, tbdetSku.Text, StringComparison.CurrentCultureIgnoreCase)))
  458. throw new Exception($"Produkt se zadaným SKU '{tbdetSku.Text}' již existuje!");
  459. if (!data.IsVariant)
  460. {
  461. foreach(ProductDto item in _storage.Products.Where(x=>x.IsVariant && string.Equals(x.ParentName, data.Sku, StringComparison.CurrentCultureIgnoreCase)))
  462. {
  463. item.ParentName = tbdetSku.Text;
  464. }
  465. }
  466. }
  467. data.Sku = tbdetSku.Text;
  468. data.ShortDescription = tbdetShortDescription.Text;
  469. data.Description = tbdetDescription.Text;
  470. data.Price = tbdetPrice.Value;
  471. data.Uri = tbdetUri.Text;
  472. data.ParentName = cbdetParent.SelectedItem?.ToString() ?? string.Empty;
  473. data.Category = cbdetCategories.SelectedItem?.ToString() ?? string.Empty;
  474. _storage.CheckProductVariantValidity();
  475. });
  476. }
  477. private void SaveDetail(VariantDto? data)
  478. {
  479. BlockErrorHandled(() =>
  480. {
  481. if (data == null)
  482. return;
  483. // update products
  484. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.VariantName, data.Name, StringComparison.InvariantCultureIgnoreCase));
  485. foreach (var product in productsToUpdate)
  486. {
  487. product.VariantName = tbdetName.Text;
  488. product.Price = tbdetPrice.Value;
  489. }
  490. data.Name = tbdetName.Text;
  491. data.Price = tbdetPrice.Value;
  492. });
  493. }
  494. private void SaveDetail(CategoryDto? data)
  495. {
  496. BlockErrorHandled(() =>
  497. {
  498. if (data == null)
  499. return;
  500. // update products
  501. if (!string.Equals(data.Name, tbdetName.Text, StringComparison.InvariantCultureIgnoreCase))
  502. {
  503. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.Category, data.Name, StringComparison.InvariantCultureIgnoreCase));
  504. foreach (var product in productsToUpdate)
  505. {
  506. product.Category = tbdetName.Text;
  507. }
  508. data.Name = tbdetName.Text;
  509. }
  510. });
  511. }
  512. private void AddNewVariant()
  513. {
  514. BlockErrorHandled(() =>
  515. {
  516. var item = _storage.AddNewVariant();
  517. lvVariants.AddItem(item, true);
  518. });
  519. }
  520. private void AddNewCategory()
  521. {
  522. BlockErrorHandled(() =>
  523. {
  524. var item = _storage.AddNewCategory();
  525. lvCategories.AddItem(item, true);
  526. });
  527. }
  528. private void AddNewProduct()
  529. {
  530. BlockErrorHandled(() =>
  531. {
  532. var item = _storage.AddNewProduct();
  533. item.ProductName = _hashGenerator.NewId();
  534. item.Sku = item.ProductName;
  535. lvProducts.AddItem(item, true);
  536. });
  537. }
  538. private void AddNewProductVariant()
  539. {
  540. BlockErrorHandled(() =>
  541. {
  542. var item = _storage.AddNewProductVariant(GetSelectedProduct()?.FirstOrDefault()?.ParentName);
  543. item.ProductName = _hashGenerator.NewId();
  544. item.Sku = item.ProductName;
  545. lvProducts.AddItem(item, true);
  546. });
  547. }
  548. private void CloneProduct(ProductDto item)
  549. {
  550. BlockErrorHandled(() =>
  551. {
  552. var newItem = item.IsVariant ? _storage.AddNewProductVariant(item.ParentName) : _storage.AddNewProduct();
  553. item.CopyTo(newItem);
  554. lvProducts.AddItem(newItem, true);
  555. });
  556. }
  557. private void ApplyProductVariant()
  558. {
  559. BlockErrorHandled(() =>
  560. {
  561. var variants = GetSelectedVariants();
  562. if (variants == null)
  563. return;
  564. var totalCnt = 0;
  565. foreach (var variant in variants)
  566. {
  567. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.VariantName, variant.Name, StringComparison.InvariantCultureIgnoreCase));
  568. totalCnt += productsToUpdate.Count();
  569. foreach (var product in productsToUpdate)
  570. {
  571. product.Price = variant.Price;
  572. }
  573. }
  574. MessageBox.Show($"Bylo upraveno {totalCnt} produktů", "Hotovo", MessageBoxButtons.OK, MessageBoxIcon.Information);
  575. });
  576. }
  577. private ProductDto[]? GetSelectedProduct()
  578. {
  579. if (lvProducts.SelectedItems.Count == 0)
  580. return null;
  581. var result = new List<ProductDto>();
  582. BlockErrorHandled(() =>
  583. {
  584. foreach (ListViewItem item in lvProducts.SelectedItems)
  585. {
  586. var product = _storage.GetProductByIdentifier(item.Tag?.ToString());
  587. if (product != null)
  588. result.Add(product);
  589. }
  590. });
  591. return result.ToArray();
  592. }
  593. private VariantDto[]? GetSelectedVariants()
  594. {
  595. if (lvVariants.SelectedItems.Count == 0)
  596. return null;
  597. var result = new List<VariantDto>();
  598. BlockErrorHandled(() =>
  599. {
  600. foreach (ListViewItem item in lvVariants.SelectedItems)
  601. {
  602. var variant = _storage.GetVariantByIdentifier(item.Tag?.ToString());
  603. if (variant != null)
  604. result.Add(variant);
  605. }
  606. });
  607. return result.ToArray();
  608. }
  609. private CategoryDto[]? GetSelectedCategories()
  610. {
  611. if (lvCategories.SelectedItems.Count == 0)
  612. return null;
  613. var result = new List<CategoryDto>();
  614. foreach (ListViewItem item in lvCategories.SelectedItems)
  615. {
  616. var category = _storage.GetCategoryByIdentifier(item.Tag?.ToString());
  617. if (category != null)
  618. result.Add(category);
  619. }
  620. return result.ToArray();
  621. }
  622. private void ImportProducts(string selectedPath, string urlPrefix, string shortDescription, string description, DateTime uploadDate)
  623. {
  624. BlockErrorHandled(() =>
  625. {
  626. if (!Directory.Exists(selectedPath))
  627. throw new Exception($"Složka '{selectedPath}' neexistuje.");
  628. // search for files
  629. var fsrch = new FileSearch(selectedPath, true);
  630. var filesCache = new List<string>();
  631. var files = fsrch.Search(new[] {AppSettings.Default.SourceSearchPattern , "*" });
  632. if (files.Length == 0)
  633. throw new Exception($"Nenalezeny žádné soubory pro zpracování ve složce '{selectedPath}'.");
  634. // construct list of files
  635. foreach (var file in files)
  636. if (!filesCache.Any(x => x == file))
  637. filesCache.Add(file);
  638. var tplParams = new Dictionary<string, string>
  639. {
  640. { "DD", uploadDate.Day.ToString("##") },
  641. { "MM", uploadDate.Month.ToString("##") },
  642. { "YY", uploadDate.Year.ToString().Substring(2,2) },
  643. { "YYYY", uploadDate.Year.ToString() },
  644. { "file", "file" },
  645. { "ext", "ext" },
  646. { "category", "category" },
  647. { "variant", "variant" }
  648. };
  649. foreach (var file in filesCache)
  650. {
  651. var product = new ProductDto();
  652. var pathParts = file.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
  653. if (pathParts.Length < 3) continue;
  654. var indexLast = pathParts.Length - 1;
  655. var sku = pathParts[indexLast];
  656. var variant = pathParts[indexLast - 1];
  657. var category = pathParts[indexLast - 2];
  658. tplParams["file"] = Path.GetFileNameWithoutExtension(pathParts[indexLast]);
  659. tplParams["ext"] = Path.GetExtension(pathParts[indexLast]);
  660. tplParams["variant"] = variant;
  661. tplParams["category"] = category;
  662. var parentDto = _storage.GetProductByName(Path.GetFileNameWithoutExtension(pathParts[indexLast]));
  663. if (parentDto == null)
  664. {
  665. // product has not parent, create new product
  666. parentDto = _storage.AddNewProduct();
  667. parentDto.ProductName = Path.GetFileNameWithoutExtension(pathParts[indexLast]);
  668. parentDto.Sku = sku + "_" + _hashGenerator.NewId();
  669. parentDto.Category = category;
  670. parentDto.ShortDescription = new ExtendedParametrizedString(shortDescription, tplParams, "{", "}").ToString();
  671. parentDto.Description = new ExtendedParametrizedString(description, tplParams, "{", "}").ToString();
  672. parentDto.Uri = new ExtendedParametrizedString(urlPrefix, tplParams, "{", "}").ToString();
  673. }
  674. product = _storage.AddNewProductVariant(parentDto.Sku);
  675. product.Uri = new ExtendedParametrizedString(urlPrefix, tplParams, "{", "}").ToString();
  676. product.ShortDescription = new ExtendedParametrizedString(shortDescription, tplParams, "{", "}").ToString();
  677. product.Description = new ExtendedParametrizedString(description, tplParams, "{", "}").ToString();
  678. product.ProductName = Path.GetFileNameWithoutExtension(pathParts[indexLast]) + " - " + variant;
  679. product.Sku = sku + "_" + _hashGenerator.NewId();
  680. product.Price = 0;
  681. product.VariantName = variant;
  682. }
  683. _storage.CheckProductVariantValidity();
  684. });
  685. }
  686. private bool ConfirmMessage(string message)
  687. {
  688. return MessageBox.Show(message, "Potvrzení", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
  689. }
  690. private void BlockErrorHandled(Action block)
  691. {
  692. try
  693. {
  694. block();
  695. }
  696. catch (Exception ex)
  697. {
  698. // Log("Error: " + ex.Message);
  699. MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  700. RefreshTools();
  701. }
  702. }
  703. #endregion
  704. }
  705. }