ProductsPage.xaml.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Globalization;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using ComputerShopWpf.Services;
  8. using Npgsql;
  9. namespace ComputerShopWpf.Views
  10. {
  11. public partial class ProductsPage : Page
  12. {
  13. private readonly DatabaseService _database = new DatabaseService();
  14. public ProductsPage()
  15. {
  16. InitializeComponent();
  17. ApplyRole();
  18. LoadSuppliers();
  19. LoadProducts();
  20. }
  21. private void ApplyRole()
  22. {
  23. bool canEdit = UserSession.CanEditProducts();
  24. ProductNameTextBox.IsEnabled = canEdit;
  25. CategoryTextBox.IsEnabled = canEdit;
  26. PriceTextBox.IsEnabled = canEdit;
  27. StockTextBox.IsEnabled = canEdit;
  28. SuppliersComboBox.IsEnabled = canEdit;
  29. AddProductButton.IsEnabled = canEdit;
  30. }
  31. private void LoadProducts()
  32. {
  33. try
  34. {
  35. DataTable table = _database.ExecuteSelect(
  36. "SELECT * FROM v_products_dictionary ORDER BY product_name;");
  37. ProductsDataGrid.ItemsSource = table.DefaultView;
  38. }
  39. catch (Exception ex)
  40. {
  41. ShowDatabaseError(ex);
  42. }
  43. }
  44. private void LoadSuppliers()
  45. {
  46. try
  47. {
  48. DataTable table = _database.ExecuteSelect(
  49. "SELECT supplier_id, company_name FROM suppliers ORDER BY company_name;");
  50. SuppliersComboBox.ItemsSource = table.DefaultView;
  51. if (SuppliersComboBox.Items.Count > 0)
  52. {
  53. SuppliersComboBox.SelectedIndex = 0;
  54. }
  55. }
  56. catch (Exception ex)
  57. {
  58. ShowDatabaseError(ex);
  59. }
  60. }
  61. private void AddProductButton_Click(object sender, RoutedEventArgs e)
  62. {
  63. if (!UserSession.CanEditProducts())
  64. {
  65. MessageBox.Show("У вас нет прав для добавления товаров.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
  66. return;
  67. }
  68. string productName = ProductNameTextBox.Text.Trim();
  69. string category = CategoryTextBox.Text.Trim();
  70. if (string.IsNullOrWhiteSpace(productName) || string.IsNullOrWhiteSpace(category))
  71. {
  72. MessageBox.Show("Заполните название товара и категорию.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
  73. return;
  74. }
  75. decimal price;
  76. if (!TryParseDecimal(PriceTextBox.Text, out price) || price < 0)
  77. {
  78. MessageBox.Show("Цена должна быть числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
  79. return;
  80. }
  81. int stockQuantity;
  82. if (!int.TryParse(StockTextBox.Text.Trim(), out stockQuantity) || stockQuantity < 0)
  83. {
  84. MessageBox.Show("Остаток должен быть целым числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
  85. return;
  86. }
  87. if (SuppliersComboBox.SelectedValue == null)
  88. {
  89. MessageBox.Show("Выберите поставщика.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
  90. return;
  91. }
  92. try
  93. {
  94. _database.ExecuteNonQuery(
  95. "INSERT INTO products(product_name, price, stock_quantity, category, supplier_id) VALUES (@product_name, @price, @stock_quantity, @category, @supplier_id);",
  96. new Dictionary<string, object>
  97. {
  98. { "@product_name", productName },
  99. { "@price", price },
  100. { "@stock_quantity", stockQuantity },
  101. { "@category", category },
  102. { "@supplier_id", Convert.ToInt32(SuppliersComboBox.SelectedValue) }
  103. });
  104. ClearForm();
  105. LoadProducts();
  106. }
  107. catch (Exception ex)
  108. {
  109. ShowDatabaseError(ex);
  110. }
  111. }
  112. private void RefreshButton_Click(object sender, RoutedEventArgs e)
  113. {
  114. LoadSuppliers();
  115. LoadProducts();
  116. }
  117. private void ClearForm()
  118. {
  119. ProductNameTextBox.Clear();
  120. CategoryTextBox.Clear();
  121. PriceTextBox.Clear();
  122. StockTextBox.Clear();
  123. if (SuppliersComboBox.Items.Count > 0)
  124. {
  125. SuppliersComboBox.SelectedIndex = 0;
  126. }
  127. }
  128. private static bool TryParseDecimal(string value, out decimal result)
  129. {
  130. value = (value ?? string.Empty).Trim().Replace(',', '.');
  131. return decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
  132. }
  133. private static void ShowDatabaseError(Exception ex)
  134. {
  135. PostgresException postgresException = ex as PostgresException;
  136. if (postgresException != null)
  137. {
  138. MessageBox.Show("Ошибка PostgreSQL: " + postgresException.MessageText, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  139. return;
  140. }
  141. NpgsqlException npgsqlException = ex as NpgsqlException;
  142. if (npgsqlException != null)
  143. {
  144. MessageBox.Show("Ошибка подключения к базе данных: " + npgsqlException.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  145. return;
  146. }
  147. MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  148. }
  149. }
  150. }