ClientsPage.xaml.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Windows;
  5. using System.Windows.Controls;
  6. using ComputerShopWpf.Helpers;
  7. using ComputerShopWpf.Services;
  8. using Npgsql;
  9. namespace ComputerShopWpf.Views
  10. {
  11. public partial class ClientsPage : Page
  12. {
  13. private readonly DatabaseService _database = new DatabaseService();
  14. private int _selectedClientId;
  15. public ClientsPage()
  16. {
  17. InitializeComponent();
  18. ApplyRole();
  19. LoadClients();
  20. }
  21. private void ApplyRole()
  22. {
  23. AddButton.IsEnabled = UserSession.CanEditClients();
  24. UpdateButton.IsEnabled = UserSession.CanEditClients();
  25. DeleteButton.IsEnabled = UserSession.CanDeleteClients();
  26. }
  27. private void LoadClients()
  28. {
  29. try
  30. {
  31. DataTable table = _database.ExecuteSelect(
  32. "SELECT client_id, first_name, last_name, address, phone, email FROM clients ORDER BY client_id;");
  33. ClientsDataGrid.ItemsSource = table.DefaultView;
  34. }
  35. catch (Exception ex)
  36. {
  37. ShowDatabaseError(ex);
  38. }
  39. }
  40. private void AddButton_Click(object sender, RoutedEventArgs e)
  41. {
  42. string errorMessage;
  43. if (!ValidationHelper.ValidateClient(FirstNameTextBox.Text, LastNameTextBox.Text, AddressTextBox.Text, PhoneTextBox.Text, EmailTextBox.Text, out errorMessage))
  44. {
  45. MessageBox.Show(errorMessage, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
  46. return;
  47. }
  48. try
  49. {
  50. _database.ExecuteNonQuery(
  51. "INSERT INTO clients(first_name, last_name, address, phone, email) VALUES (@first_name, @last_name, @address, @phone, @email);",
  52. GetClientParameters());
  53. ClearForm();
  54. LoadClients();
  55. }
  56. catch (Exception ex)
  57. {
  58. ShowDatabaseError(ex);
  59. }
  60. }
  61. private void UpdateButton_Click(object sender, RoutedEventArgs e)
  62. {
  63. if (_selectedClientId == 0)
  64. {
  65. MessageBox.Show("Выберите клиента для изменения.", "Клиенты", MessageBoxButton.OK, MessageBoxImage.Information);
  66. return;
  67. }
  68. string errorMessage;
  69. if (!ValidationHelper.ValidateClient(FirstNameTextBox.Text, LastNameTextBox.Text, AddressTextBox.Text, PhoneTextBox.Text, EmailTextBox.Text, out errorMessage))
  70. {
  71. MessageBox.Show(errorMessage, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
  72. return;
  73. }
  74. try
  75. {
  76. Dictionary<string, object> parameters = GetClientParameters();
  77. parameters.Add("@client_id", _selectedClientId);
  78. _database.ExecuteNonQuery(
  79. "UPDATE clients SET first_name = @first_name, last_name = @last_name, address = @address, phone = @phone, email = @email WHERE client_id = @client_id;",
  80. parameters);
  81. ClearForm();
  82. LoadClients();
  83. }
  84. catch (Exception ex)
  85. {
  86. ShowDatabaseError(ex);
  87. }
  88. }
  89. private void DeleteButton_Click(object sender, RoutedEventArgs e)
  90. {
  91. if (_selectedClientId == 0)
  92. {
  93. MessageBox.Show("Выберите клиента для удаления.", "Клиенты", MessageBoxButton.OK, MessageBoxImage.Information);
  94. return;
  95. }
  96. if (MessageBox.Show("Удалить выбранного клиента?", "Подтверждение", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
  97. {
  98. return;
  99. }
  100. try
  101. {
  102. _database.ExecuteNonQuery(
  103. "DELETE FROM clients WHERE client_id = @client_id;",
  104. new Dictionary<string, object> { { "@client_id", _selectedClientId } });
  105. ClearForm();
  106. LoadClients();
  107. }
  108. catch (PostgresException ex)
  109. {
  110. if (ex.SqlState == "23503")
  111. {
  112. MessageBox.Show("Невозможно удалить клиента, так как у него есть заказы.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  113. return;
  114. }
  115. ShowDatabaseError(ex);
  116. }
  117. catch (Exception ex)
  118. {
  119. ShowDatabaseError(ex);
  120. }
  121. }
  122. private void RefreshButton_Click(object sender, RoutedEventArgs e)
  123. {
  124. LoadClients();
  125. }
  126. private void ClientsDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  127. {
  128. DataRowView row = ClientsDataGrid.SelectedItem as DataRowView;
  129. if (row == null)
  130. {
  131. return;
  132. }
  133. _selectedClientId = Convert.ToInt32(row["client_id"]);
  134. FirstNameTextBox.Text = Convert.ToString(row["first_name"]);
  135. LastNameTextBox.Text = Convert.ToString(row["last_name"]);
  136. AddressTextBox.Text = Convert.ToString(row["address"]);
  137. PhoneTextBox.Text = Convert.ToString(row["phone"]);
  138. EmailTextBox.Text = Convert.ToString(row["email"]);
  139. }
  140. private Dictionary<string, object> GetClientParameters()
  141. {
  142. return new Dictionary<string, object>
  143. {
  144. { "@first_name", FirstNameTextBox.Text.Trim() },
  145. { "@last_name", LastNameTextBox.Text.Trim() },
  146. { "@address", AddressTextBox.Text.Trim() },
  147. { "@phone", string.IsNullOrWhiteSpace(PhoneTextBox.Text) ? null : PhoneTextBox.Text.Trim() },
  148. { "@email", string.IsNullOrWhiteSpace(EmailTextBox.Text) ? null : EmailTextBox.Text.Trim() }
  149. };
  150. }
  151. private void ClearForm()
  152. {
  153. _selectedClientId = 0;
  154. FirstNameTextBox.Clear();
  155. LastNameTextBox.Clear();
  156. AddressTextBox.Clear();
  157. PhoneTextBox.Clear();
  158. EmailTextBox.Clear();
  159. }
  160. private static void ShowDatabaseError(Exception ex)
  161. {
  162. PostgresException postgresException = ex as PostgresException;
  163. if (postgresException != null)
  164. {
  165. MessageBox.Show("Ошибка PostgreSQL: " + postgresException.MessageText, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  166. return;
  167. }
  168. NpgsqlException npgsqlException = ex as NpgsqlException;
  169. if (npgsqlException != null)
  170. {
  171. MessageBox.Show("Ошибка подключения к базе данных: " + npgsqlException.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  172. return;
  173. }
  174. MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  175. }
  176. }
  177. }