FormProductEdit.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. tbdetMaximal.Text = string.Empty;
  351. tbdetMinimal.Text = string.Empty;
  352. cbdetParent.BeginUpdate();
  353. cbdetParent.Items.Clear();
  354. foreach (var product in _storage.GetProductsView(true, false).Select(x => x.Sku).Order())
  355. cbdetParent.Items.Add(product!);
  356. cbdetParent.EndUpdate();
  357. });
  358. }
  359. private void VisibleAllDetail(bool visible)
  360. {
  361. BlockErrorHandled(() =>
  362. {
  363. tbdetId.Visible = visible;
  364. ltbdetId.Visible = visible;
  365. tbdetName.Visible = visible;
  366. ltbdetName.Visible = visible;
  367. tbdetSku.Visible = visible;
  368. ltbdetSku.Visible = visible;
  369. tbdetShortDescription.Visible = visible;
  370. ltbdetShortDescription.Visible = visible;
  371. tbdetDescription.Visible = visible;
  372. ltbdetDescription.Visible = visible;
  373. tbdetPrice.Visible = visible;
  374. ltbdetPrice.Visible = visible;
  375. tbdetUri.Visible = visible;
  376. ltbdetUri.Visible = visible;
  377. cbdetCategories.Visible = visible;
  378. lcbdetCategories.Visible = visible;
  379. cbdetParent.Visible = visible;
  380. lcbdetParent.Visible = visible;
  381. tbdetMinimal.Visible = visible;
  382. ldetMinimal.Visible = visible;
  383. tbdetMaximal.Visible = visible;
  384. ldetMaximal.Visible = visible;
  385. });
  386. }
  387. private void ShowDetail(ProductDto? data)
  388. {
  389. BlockErrorHandled(() =>
  390. {
  391. _detailType = DetailType.Product;
  392. detProduct.Visible = false;
  393. ClearDetail();
  394. if (data == null)
  395. {
  396. detProduct.Visible = true;
  397. return;
  398. }
  399. var isVariant = data.IsVariant;
  400. tblbCaption.Text = isVariant ? "Varianta produktu" : "Produkt";
  401. VisibleAllDetail(true);
  402. if (isVariant)
  403. {
  404. // variant
  405. cbdetCategories.Visible = false;
  406. lcbdetCategories.Visible = false;
  407. }
  408. else
  409. {
  410. // head product
  411. cbdetParent.Visible = false;
  412. lcbdetParent.Visible = false;
  413. tbdetPrice.Visible = false;
  414. ltbdetPrice.Visible = false;
  415. cbdetCategories.SelectedIndex = cbdetCategories.FindStringExact(data.Category);
  416. tbdetMaximal.Visible = false;
  417. tbdetMinimal.Visible = false;
  418. ldetMaximal.Visible = false;
  419. ldetMinimal.Visible = false;
  420. }
  421. tbdetId.Text = data.Id.ToString();
  422. tbdetName.Text = data.ProductName;
  423. tbdetSku.Text = data.Sku;
  424. tbdetShortDescription.Text = data.ShortDescription;
  425. tbdetDescription.Text = data.Description;
  426. tbdetPrice.Value = data.Price;
  427. tbdetUri.Text = data.Uri;
  428. tbdetMaximal.Text = data.QuantityMaximum.ToString();
  429. tbdetMinimal.Text = data.QuantityMinimum.ToString();
  430. cbdetParent.SelectedIndex = cbdetParent.FindStringExact(data.ParentName);
  431. detProduct.Visible = true;
  432. });
  433. }
  434. private void ShowDetail(VariantDto? data)
  435. {
  436. BlockErrorHandled(() =>
  437. {
  438. _detailType = DetailType.Variant;
  439. tblbCaption.Text = "Varianta";
  440. detProduct.Visible = false;
  441. ClearDetail();
  442. if (data == null)
  443. {
  444. detProduct.Visible = true;
  445. return;
  446. }
  447. VisibleAllDetail(false);
  448. ltbdetName.Visible = true;
  449. tbdetName.Visible = true;
  450. ltbdetPrice.Visible = true;
  451. tbdetPrice.Visible = true;
  452. ldetMinimal.Visible = true;
  453. ldetMaximal.Visible = true;
  454. tbdetMaximal.Visible = true;
  455. tbdetMinimal.Visible = true;
  456. tbdetName.Text = data.Name;
  457. tbdetPrice.Value = data.Price;
  458. tbdetMaximal.Text = data.QuantityMaximum.ToString();
  459. tbdetMinimal.Text = data.QuantityMinimum.ToString();
  460. detProduct.Visible = true;
  461. });
  462. }
  463. private void ShowDetail(CategoryDto? data)
  464. {
  465. BlockErrorHandled(() =>
  466. {
  467. _detailType = DetailType.Category;
  468. tblbCaption.Text = "Kategorie";
  469. detProduct.Visible = false;
  470. ClearDetail();
  471. if (data == null)
  472. {
  473. detProduct.Visible = true;
  474. return;
  475. }
  476. VisibleAllDetail(false);
  477. ltbdetName.Visible = true;
  478. tbdetName.Visible = true;
  479. tbdetName.Text = data.Name;
  480. detProduct.Visible = true;
  481. });
  482. }
  483. private void SaveDetail(ProductDto? data)
  484. {
  485. BlockErrorHandled(() =>
  486. {
  487. if (data == null)
  488. return;
  489. data.ProductName = tbdetName.Text;
  490. if (!string.Equals(data.Sku, tbdetSku.Text, StringComparison.CurrentCultureIgnoreCase))
  491. {
  492. if (_storage.Products.Any(x => string.Equals(x.Sku, tbdetSku.Text, StringComparison.CurrentCultureIgnoreCase)))
  493. throw new Exception($"Produkt se zadaným SKU '{tbdetSku.Text}' již existuje!");
  494. if (!data.IsVariant)
  495. {
  496. foreach (ProductDto item in _storage.Products.Where(x => x.IsVariant && string.Equals(x.ParentName, data.Sku, StringComparison.CurrentCultureIgnoreCase)))
  497. {
  498. item.ParentName = tbdetSku.Text;
  499. }
  500. }
  501. }
  502. data.Sku = tbdetSku.Text;
  503. data.ShortDescription = tbdetShortDescription.Text;
  504. data.Description = tbdetDescription.Text;
  505. data.Price = tbdetPrice.Value;
  506. data.Uri = tbdetUri.Text;
  507. data.ParentName = cbdetParent.SelectedItem?.ToString() ?? string.Empty;
  508. data.Category = cbdetCategories.SelectedItem?.ToString() ?? string.Empty;
  509. data.QuantityMinimum = int.TryParse(tbdetMinimal.Text, out var resmin) ? resmin : 0;
  510. data.QuantityMaximum = int.TryParse(tbdetMaximal.Text, out var resmax) ? resmax : 0;
  511. _storage.CheckProductVariantValidity();
  512. });
  513. }
  514. private void SaveDetail(VariantDto? data)
  515. {
  516. BlockErrorHandled(() =>
  517. {
  518. if (data == null)
  519. return;
  520. // update products
  521. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.VariantName, data.Name, StringComparison.InvariantCultureIgnoreCase));
  522. foreach (var product in productsToUpdate)
  523. {
  524. product.VariantName = tbdetName.Text;
  525. product.Price = tbdetPrice.Value;
  526. product.QuantityMinimum = int.TryParse(tbdetMinimal.Text, out var resmina) ? resmina : 0;
  527. product.QuantityMaximum = int.TryParse(tbdetMaximal.Text, out var resmaxa) ? resmaxa : 0;
  528. }
  529. data.Name = tbdetName.Text;
  530. data.Price = tbdetPrice.Value;
  531. data.QuantityMinimum = int.TryParse(tbdetMinimal.Text, out var resmin) ? resmin : 0;
  532. data.QuantityMaximum = int.TryParse(tbdetMaximal.Text, out var resmax) ? resmax : 0;
  533. });
  534. }
  535. private void SaveDetail(CategoryDto? data)
  536. {
  537. BlockErrorHandled(() =>
  538. {
  539. if (data == null)
  540. return;
  541. // update products
  542. if (!string.Equals(data.Name, tbdetName.Text, StringComparison.InvariantCultureIgnoreCase))
  543. {
  544. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.Category, data.Name, StringComparison.InvariantCultureIgnoreCase));
  545. foreach (var product in productsToUpdate)
  546. {
  547. product.Category = tbdetName.Text;
  548. }
  549. data.Name = tbdetName.Text;
  550. }
  551. });
  552. }
  553. private void GenerateRepository(string selectedPath)
  554. {
  555. int skipedCnt = 0;
  556. int createdCnt = 0;
  557. BlockErrorHandled(() =>
  558. {
  559. if (!Directory.Exists(selectedPath))
  560. throw new Exception($"Složka '{selectedPath}' neexistuje.");
  561. foreach (var category in _storage.Categories)
  562. {
  563. var fullPath = Path.Combine(selectedPath, category.Name);
  564. if (!Directory.Exists(fullPath))
  565. {
  566. Directory.CreateDirectory(fullPath);
  567. createdCnt++;
  568. }
  569. else
  570. {
  571. skipedCnt++;
  572. }
  573. foreach (var variant in _storage.Variants)
  574. {
  575. var variantPath = Path.Combine(fullPath, variant.Name);
  576. if (!Directory.Exists(variantPath))
  577. {
  578. Directory.CreateDirectory(variantPath);
  579. createdCnt++;
  580. }
  581. else
  582. {
  583. skipedCnt++;
  584. }
  585. }
  586. }
  587. });
  588. MessageBox.Show($"Bylo vytvořeno {createdCnt} složek, {skipedCnt} již existovalo.", "Hotovo", MessageBoxButtons.OK, MessageBoxIcon.Information);
  589. }
  590. private void AddNewVariant()
  591. {
  592. BlockErrorHandled(() =>
  593. {
  594. var item = _storage.AddNewVariant();
  595. lvVariants.AddItem(item, true);
  596. });
  597. }
  598. private void AddNewCategory()
  599. {
  600. BlockErrorHandled(() =>
  601. {
  602. var item = _storage.AddNewCategory();
  603. lvCategories.AddItem(item, true);
  604. });
  605. }
  606. private void AddNewProduct()
  607. {
  608. BlockErrorHandled(() =>
  609. {
  610. var item = _storage.AddNewProduct();
  611. item.ProductName = _hashGenerator.NewId();
  612. item.Sku = item.ProductName;
  613. lvProducts.AddItem(item, true);
  614. });
  615. }
  616. private void AddNewProductVariant()
  617. {
  618. BlockErrorHandled(() =>
  619. {
  620. var item = _storage.AddNewProductVariant(GetSelectedProduct()?.FirstOrDefault()?.ParentName);
  621. item.ProductName = _hashGenerator.NewId();
  622. item.Sku = item.ProductName;
  623. lvProducts.AddItem(item, true);
  624. });
  625. }
  626. private void CloneProduct(ProductDto item)
  627. {
  628. BlockErrorHandled(() =>
  629. {
  630. var newItem = item.IsVariant ? _storage.AddNewProductVariant(item.ParentName) : _storage.AddNewProduct();
  631. item.CopyTo(newItem);
  632. lvProducts.AddItem(newItem, true);
  633. });
  634. }
  635. private void ApplyProductVariant()
  636. {
  637. BlockErrorHandled(() =>
  638. {
  639. var variants = GetSelectedVariants();
  640. if (variants == null)
  641. return;
  642. var totalCnt = 0;
  643. foreach (var variant in variants)
  644. {
  645. var productsToUpdate = _storage.Products.Where(x => x.IsVariant && string.Equals(x.VariantName, variant.Name, StringComparison.InvariantCultureIgnoreCase));
  646. totalCnt += productsToUpdate.Count();
  647. foreach (var product in productsToUpdate)
  648. {
  649. product.Price = variant.Price;
  650. }
  651. }
  652. MessageBox.Show($"Bylo upraveno {totalCnt} produktů", "Hotovo", MessageBoxButtons.OK, MessageBoxIcon.Information);
  653. });
  654. }
  655. private ProductDto[]? GetSelectedProduct()
  656. {
  657. if (lvProducts.SelectedItems.Count == 0)
  658. return null;
  659. var result = new List<ProductDto>();
  660. BlockErrorHandled(() =>
  661. {
  662. foreach (ListViewItem item in lvProducts.SelectedItems)
  663. {
  664. var product = _storage.GetProductByIdentifier(item.Tag?.ToString());
  665. if (product != null)
  666. result.Add(product);
  667. }
  668. });
  669. return result.ToArray();
  670. }
  671. private VariantDto[]? GetSelectedVariants()
  672. {
  673. if (lvVariants.SelectedItems.Count == 0)
  674. return null;
  675. var result = new List<VariantDto>();
  676. BlockErrorHandled(() =>
  677. {
  678. foreach (ListViewItem item in lvVariants.SelectedItems)
  679. {
  680. var variant = _storage.GetVariantByIdentifier(item.Tag?.ToString());
  681. if (variant != null)
  682. result.Add(variant);
  683. }
  684. });
  685. return result.ToArray();
  686. }
  687. private CategoryDto[]? GetSelectedCategories()
  688. {
  689. if (lvCategories.SelectedItems.Count == 0)
  690. return null;
  691. var result = new List<CategoryDto>();
  692. foreach (ListViewItem item in lvCategories.SelectedItems)
  693. {
  694. var category = _storage.GetCategoryByIdentifier(item.Tag?.ToString());
  695. if (category != null)
  696. result.Add(category);
  697. }
  698. return result.ToArray();
  699. }
  700. private void ImportProducts(string selectedPath, string urlPrefix, string shortDescription, string description, DateTime uploadDate)
  701. {
  702. BlockErrorHandled(() =>
  703. {
  704. if (!Directory.Exists(selectedPath))
  705. throw new Exception($"Složka '{selectedPath}' neexistuje.");
  706. // search for files
  707. var fsrch = new FileSearch(selectedPath, true);
  708. var filesCache = new List<string>();
  709. var files = fsrch.Search(new[] { AppSettings.Default.SourceSearchPattern, "*" });
  710. if (files.Length == 0)
  711. throw new Exception($"Nenalezeny žádné soubory pro zpracování ve složce '{selectedPath}'.");
  712. // construct list of files
  713. foreach (var file in files)
  714. if (!filesCache.Any(x => x == file))
  715. filesCache.Add(file);
  716. var tplParams = new Dictionary<string, string>
  717. {
  718. { "DD", uploadDate.Day.ToString("00") },
  719. { "MM", uploadDate.Month.ToString("00") },
  720. { "YY", uploadDate.Year.ToString().Substring(2,2) },
  721. { "YYYY", uploadDate.Year.ToString() },
  722. { "file", "file" },
  723. { "ext", "ext" },
  724. { "category", "category" },
  725. { "variant", "variant" }
  726. };
  727. foreach (var file in filesCache)
  728. {
  729. var product = new ProductDto();
  730. var pathParts = file.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
  731. if (pathParts.Length < 3) continue;
  732. var indexLast = pathParts.Length - 1;
  733. var sku = Path.GetFileNameWithoutExtension(pathParts[indexLast]);
  734. var variant = pathParts[indexLast - 1];
  735. var category = pathParts[indexLast - 2];
  736. tplParams["file"] = Path.GetFileNameWithoutExtension(pathParts[indexLast]);
  737. tplParams["ext"] = Path.GetExtension(pathParts[indexLast]);
  738. tplParams["variant"] = variant;
  739. tplParams["category"] = category;
  740. var parentDto = _storage.GetProductByName(Path.GetFileNameWithoutExtension(pathParts[indexLast]));
  741. if (parentDto == null)
  742. {
  743. // product has not parent, create new product
  744. parentDto = _storage.AddNewProduct();
  745. parentDto.ProductName = Path.GetFileNameWithoutExtension(pathParts[indexLast]);
  746. parentDto.Sku = sku + "_" + _hashGenerator.NewId();
  747. parentDto.Category = category;
  748. parentDto.ShortDescription = new ExtendedParametrizedString(shortDescription, tplParams, "{", "}").ToString();
  749. parentDto.Description = new ExtendedParametrizedString(description, tplParams, "{", "}").ToString();
  750. parentDto.Uri = new ExtendedParametrizedString(urlPrefix, tplParams, "{", "}").ToString();
  751. parentDto.VariantType = "Formát";
  752. }
  753. product = _storage.AddNewProductVariant(parentDto.Sku);
  754. product.Uri = new ExtendedParametrizedString(urlPrefix, tplParams, "{", "}").ToString();
  755. product.ProductName = Path.GetFileNameWithoutExtension(pathParts[indexLast]) + " - " + variant;
  756. product.Sku = sku + "_" + _hashGenerator.NewId();
  757. product.Price = 0;
  758. product.VariantName = variant;
  759. product.VariantType = "Formát";
  760. product.ShortDescription = new ExtendedParametrizedString(shortDescription, tplParams, "{", "}").ToString();
  761. product.Description = new ExtendedParametrizedString(description, tplParams, "{", "}").ToString();
  762. }
  763. _storage.CheckProductVariantValidity();
  764. foreach (var product in _storage.Products.Where(x => !x.IsVariant))
  765. {
  766. product.Hidden2_1 = 1;
  767. var variantString = string.Join(",", _storage.Products.Where(x => string.Equals(x.ParentName, product.Sku, StringComparison.InvariantCultureIgnoreCase)).Select(x => x.VariantName));
  768. product.VariantName = variantString;
  769. product.ShortDescription = $"{product.Category} - fotka: {product.ProductName}";
  770. product.Description = $"{product.Category} - fotka: {product.ProductName}";
  771. }
  772. });
  773. }
  774. private bool ConfirmMessage(string message)
  775. {
  776. return MessageBox.Show(message, "Potvrzení", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes;
  777. }
  778. private void BlockErrorHandled(Action block)
  779. {
  780. try
  781. {
  782. block();
  783. }
  784. catch (Exception ex)
  785. {
  786. // Log("Error: " + ex.Message);
  787. MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
  788. RefreshTools();
  789. }
  790. }
  791. #endregion
  792. }
  793. }