FormProductEdit.cs 32 KB

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