| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Globalization;
- using System.Windows;
- using System.Windows.Controls;
- using ComputerShopWpf.Services;
- using Npgsql;
- namespace ComputerShopWpf.Views
- {
- public partial class ProductsPage : Page
- {
- private readonly DatabaseService _database = new DatabaseService();
- public ProductsPage()
- {
- InitializeComponent();
- ApplyRole();
- LoadSuppliers();
- LoadProducts();
- }
- private void ApplyRole()
- {
- bool canEdit = UserSession.CanEditProducts();
- ProductNameTextBox.IsEnabled = canEdit;
- CategoryTextBox.IsEnabled = canEdit;
- PriceTextBox.IsEnabled = canEdit;
- StockTextBox.IsEnabled = canEdit;
- SuppliersComboBox.IsEnabled = canEdit;
- AddProductButton.IsEnabled = canEdit;
- }
- private void LoadProducts()
- {
- try
- {
- DataTable table = _database.ExecuteSelect(
- "SELECT * FROM v_products_dictionary ORDER BY product_name;");
- ProductsDataGrid.ItemsSource = table.DefaultView;
- }
- catch (Exception ex)
- {
- ShowDatabaseError(ex);
- }
- }
- private void LoadSuppliers()
- {
- try
- {
- DataTable table = _database.ExecuteSelect(
- "SELECT supplier_id, company_name FROM suppliers ORDER BY company_name;");
- SuppliersComboBox.ItemsSource = table.DefaultView;
- if (SuppliersComboBox.Items.Count > 0)
- {
- SuppliersComboBox.SelectedIndex = 0;
- }
- }
- catch (Exception ex)
- {
- ShowDatabaseError(ex);
- }
- }
- private void AddProductButton_Click(object sender, RoutedEventArgs e)
- {
- if (!UserSession.CanEditProducts())
- {
- MessageBox.Show("У вас нет прав для добавления товаров.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- string productName = ProductNameTextBox.Text.Trim();
- string category = CategoryTextBox.Text.Trim();
- if (string.IsNullOrWhiteSpace(productName) || string.IsNullOrWhiteSpace(category))
- {
- MessageBox.Show("Заполните название товара и категорию.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- decimal price;
- if (!TryParseDecimal(PriceTextBox.Text, out price) || price < 0)
- {
- MessageBox.Show("Цена должна быть числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- int stockQuantity;
- if (!int.TryParse(StockTextBox.Text.Trim(), out stockQuantity) || stockQuantity < 0)
- {
- MessageBox.Show("Остаток должен быть целым числом не меньше нуля.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- if (SuppliersComboBox.SelectedValue == null)
- {
- MessageBox.Show("Выберите поставщика.", "Товары", MessageBoxButton.OK, MessageBoxImage.Warning);
- return;
- }
- try
- {
- _database.ExecuteNonQuery(
- "INSERT INTO products(product_name, price, stock_quantity, category, supplier_id) VALUES (@product_name, @price, @stock_quantity, @category, @supplier_id);",
- new Dictionary<string, object>
- {
- { "@product_name", productName },
- { "@price", price },
- { "@stock_quantity", stockQuantity },
- { "@category", category },
- { "@supplier_id", Convert.ToInt32(SuppliersComboBox.SelectedValue) }
- });
- ClearForm();
- LoadProducts();
- }
- catch (Exception ex)
- {
- ShowDatabaseError(ex);
- }
- }
- private void RefreshButton_Click(object sender, RoutedEventArgs e)
- {
- LoadSuppliers();
- LoadProducts();
- }
- private void ClearForm()
- {
- ProductNameTextBox.Clear();
- CategoryTextBox.Clear();
- PriceTextBox.Clear();
- StockTextBox.Clear();
- if (SuppliersComboBox.Items.Count > 0)
- {
- SuppliersComboBox.SelectedIndex = 0;
- }
- }
- private static bool TryParseDecimal(string value, out decimal result)
- {
- value = (value ?? string.Empty).Trim().Replace(',', '.');
- return decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out result);
- }
- private static void ShowDatabaseError(Exception ex)
- {
- PostgresException postgresException = ex as PostgresException;
- if (postgresException != null)
- {
- MessageBox.Show("Ошибка PostgreSQL: " + postgresException.MessageText, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
- return;
- }
- NpgsqlException npgsqlException = ex as NpgsqlException;
- if (npgsqlException != null)
- {
- MessageBox.Show("Ошибка подключения к базе данных: " + npgsqlException.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
- return;
- }
- MessageBox.Show("Ошибка: " + ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
- }
- }
- }
|