FormProductEdit.cs 29 KB

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