demMalyhin_Merkulov/AdmMainForm.cs

447 lines
19 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace demMalyhin
{
public partial class AdmMainForm : Form
{
private MySqlDataAdapter dataAdapter;
private DataTable prodTable;
private BindingSource bindingSource = new BindingSource();
public AdmMainForm()
{
InitializeComponent();
LoadProdData();
LoadSortOptions();
LoadFilterOptions();
}
private void LoadProdData() // загрузка данных в дгв
{
try
{
DB db = new DB();
using (MySqlConnection connection = db.getConnection())
{
connection.Open();
string query = "SELECT article_product AS `Артикул`, product_name AS `Название товара`, price AS `Цена`, supplier_name AS `Поставщик`, Manufacturer_name AS `Производитель`, Category_name AS `Категория`, sale_percent AS `Скидка`, unit_type AS `Единица измерения`, description AS `описание`, quantity_in_stock AS `Количество на складе`, photo AS `фото` FROM products LEFT JOIN Category ON products.category_id = Category.id_Category JOIN Supplier ON products.supplier_id = Supplier.id_Supplier JOIN Manufacturer ON products.manufacturer_id = Manufacturer.id_Manufacturer";
dataAdapter = new MySqlDataAdapter(query, connection);
prodTable = new DataTable();
dataAdapter.Fill(prodTable);
DataGridViewProduct.RowTemplate.Height = 60;
bindingSource.DataSource = prodTable;
DataGridViewProduct.DataSource = bindingSource;
DataGridViewProduct.AllowUserToAddRows = false;
DataGridViewProduct.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
DataGridViewProduct.ReadOnly = true; // настройки дгв
}
}
catch (MySqlException ex)
{
MessageBox.Show("Ошибка при подключении к базе данных или выполнении запроса: " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Произошла общая ошибка: " + ex.Message);
}
}
private void dataGridViewProd_Click(object sender, EventArgs e)
{
textBoxDesc.Text = DataGridViewProduct.CurrentRow.Cells[8].Value.ToString();
textBoxManuf.Text = DataGridViewProduct.CurrentRow.Cells[4].Value.ToString();
textBoxSup.Text = DataGridViewProduct.CurrentRow.Cells[3].Value.ToString();
textBoxPrice.Text = DataGridViewProduct.CurrentRow.Cells[2].Value.ToString();
textBoxUnit.Text = DataGridViewProduct.CurrentRow.Cells[7].Value.ToString();
textBoxStock.Text = DataGridViewProduct.CurrentRow.Cells[9].Value.ToString();
NameLabel.Text = DataGridViewProduct.CurrentRow.Cells[1].Value.ToString();
CategoryLabel.Text = DataGridViewProduct.CurrentRow.Cells[5].Value.ToString();
SaleLabel.Text = DataGridViewProduct.CurrentRow.Cells[6].Value.ToString() + "%";
try
{
object photoData = DataGridViewProduct.CurrentRow.Cells[10].Value;
if (photoData != DBNull.Value)
{
byte[] imageData = (byte[])photoData;
if (imageData != null && imageData.Length > 0)
{
using (MemoryStream ms = new MemoryStream(imageData))
{
pictureBoxPhoto.Image = Image.FromStream(ms);
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
else
{
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
else
{
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при загрузке изображения: " + ex.Message);
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
try
{
var currentRow = DataGridViewProduct.CurrentRow;
if (currentRow == null) return;
Color defaultColor = SystemColors.Window;
textBoxPrice.BackColor = defaultColor;
textBoxSup.BackColor = defaultColor;
textBoxManuf.BackColor = defaultColor;
textBoxStock.BackColor = defaultColor;
textBoxPrice.ForeColor = Color.Black;
textBoxPrice.Font = new Font(textBoxPrice.Font, FontStyle.Regular);
textBoxFP.Text = "";
decimal originalPrice = 0m;
int salePercent = 0;
int quantityInStock = 0;
decimal.TryParse(currentRow.Cells[2].Value?.ToString(), out originalPrice);
int.TryParse(currentRow.Cells[6].Value?.ToString(), out salePercent);
int.TryParse(currentRow.Cells[9].Value?.ToString(), out quantityInStock);
if (salePercent > 15)
{
Color highDiscountColor = ColorTranslator.FromHtml("#2E8B57");
textBoxPrice.BackColor = highDiscountColor;
textBoxSup.BackColor = highDiscountColor;
textBoxManuf.BackColor = highDiscountColor;
textBoxStock.BackColor = highDiscountColor;
textBoxDesc.BackColor = highDiscountColor;
textBoxFP.BackColor = highDiscountColor;
textBoxUnit.BackColor = highDiscountColor;
panel3.BackColor = highDiscountColor;
}
else
{
textBoxPrice.BackColor = Color.White;
textBoxSup.BackColor = Color.White;
textBoxManuf.BackColor = Color.White;
textBoxStock.BackColor = Color.White;
textBoxDesc.BackColor = Color.White;
textBoxFP.BackColor = Color.White;
textBoxUnit.BackColor = Color.White;
panel3.BackColor = Color.White;
}
if (salePercent > 0)
{
decimal finalPrice = originalPrice * (1 - (decimal)salePercent / 100);
textBoxPrice.Text = $"{originalPrice:N2}";
textBoxPrice.ForeColor = Color.Red;
textBoxPrice.Font = new Font(textBoxPrice.Font, FontStyle.Strikeout);
textBoxFP.Text = $"{finalPrice:N2}";
textBoxFP.ForeColor = Color.Black;
textBoxFP.Font = new Font(textBoxFP.Font, FontStyle.Regular);
}
else
{
textBoxPrice.Text = $"{originalPrice:N2}";
}
if (quantityInStock <= 0)
{
textBoxStock.BackColor = Color.LightBlue;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при обработке данных товара: " + ex.Message);
}
}
private void LoadSortOptions()
{
comboBoxSort.Items.Add("По умолчанию");
comboBoxSort.Items.Add("Название (А-Я)");
comboBoxSort.Items.Add("Название (Я-А)");
comboBoxSort.Items.Add("Цена (возрастающая)");
comboBoxSort.Items.Add("Цена (убывающая)");
comboBoxSort.SelectedIndex = 0;
}
private void comboBoxSort_SelectedIndexChanged(object sender, EventArgs e)
{
string sortOption = comboBoxSort.SelectedItem.ToString();
switch (sortOption)
{
case "По умолчанию":
bindingSource.Sort = "";
break;
case "Название (А-Я)":
bindingSource.Sort = "Название товара ASC";
break;
case "Название (Я-А)":
bindingSource.Sort = "Название товара DESC";
break;
case "Цена (возрастающая)":
bindingSource.Sort = "Цена ASC";
break;
case "Цена (убывающая)":
bindingSource.Sort = "Цена DESC";
break;
}
}
private void LoadFilterOptions()
{
comboBoxFilter.Items.Add("По умолчанию");
comboBoxFilter.Items.Add("Мужская обувь");
comboBoxFilter.Items.Add("Женская обувь");
comboBoxSort.SelectedIndex = 0;
}
private void comboBoxFilter_SelectedIndexChanged(object sender, EventArgs e)
{
string filterOption = comboBoxFilter.SelectedItem.ToString().Trim();
switch (filterOption)
{
case "По умолчанию":
bindingSource.Filter = "";
break;
case "Мужская обувь":
bindingSource.Filter = "[Категория] = 'Мужская обувь'";
break;
case "Женская обувь":
bindingSource.Filter = "[Категория] = 'Женская обувь'";
break;
default:
bindingSource.Filter = "";
break;
}
}
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
string searchText = textBoxSearch.Text.Trim();
if (string.IsNullOrEmpty(searchText))
{
bindingSource.Filter = "";
}
else
{
string s = searchText.Replace("'", "''");
string pattern = string.Format("%{0}%", s);
bindingSource.Filter = string.Format(
"[Артикул] LIKE '{0}' OR [Название товара] LIKE '{0}' OR [Поставщик] LIKE '{0}' OR [Производитель] LIKE '{0}' OR [Категория] LIKE '{0}' OR [Единица измерения] LIKE '{0}' OR " +
"Convert([Цена], 'System.String') LIKE '{0}' OR Convert([Скидка], 'System.String') LIKE '{0}' OR Convert([Количество на складе], 'System.String') LIKE '{0}'",
pattern);
}
}
private void AdmMainForm_Load(object sender, EventArgs e)
{
labelFIO.Text = LoginForm.ClientSurname + " " + LoginForm.ClientName + " " + LoginForm.ClientPatronymic;
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
LoginForm log = new LoginForm();
log.Show();
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
AddAdmProduct addProductForm = new AddAdmProduct();
DialogResult result = addProductForm.ShowDialog();
if (result == DialogResult.OK)
{
LoadProdData();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (DataGridViewProduct.SelectedRows.Count > 0)
{
string articleToEdit = Convert.ToString(DataGridViewProduct.SelectedRows[0].Cells["Артикул"].Value);
this.Hide();
AdmEditProduct editProductForm = new AdmEditProduct(articleToEdit);
DialogResult result = editProductForm.ShowDialog();
if (result == DialogResult.OK)
{
LoadProdData();
}
}
else
{
MessageBox.Show("Пожалуйста, выберите строку для редактирования.");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (DataGridViewProduct.SelectedRows.Count > 0)
{
int rowIndex = DataGridViewProduct.SelectedRows[0].Index;
string idToDelete = Convert.ToString(DataGridViewProduct.SelectedRows[0].Cells["Артикул"].Value);
if (IsProductInOrders(idToDelete))
{
MessageBox.Show(
"Невозможно удалить товар, так как он участвует в существующих заказах.",
"Предупреждение",
MessageBoxButtons.OK,
MessageBoxIcon.Warning
);
return; // Прекращаем выполнение, если товар найден в заказах
}
DialogResult result = MessageBox.Show(
"Вы действительно хотите удалить товар с артикулом '" + idToDelete + "'?",
"Подтверждение удаления",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question // Используем иконку вопроса
);
// Проверяем, нажал ли пользователь "Да"
if (result == DialogResult.Yes)
{
// Если пользователь подтвердил, вызываем метод удаления
DeleteData(idToDelete);
}
}
else
{
MessageBox.Show("Пожалуйста, выберите строку для удаления.");
}
}
private void DeleteData(string idToDelete)
{
try
{
DB db = new DB();
using (MySqlConnection connection = db.getConnection())
{
connection.Open();
string query = "DELETE FROM products WHERE article_product = @art";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@art", idToDelete);
int rowsAffected = command.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Запись успешно удалена.");
LoadProdData();
}
else
{
MessageBox.Show("Не удалось удалить запись.");
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show("Ошибка при подключении к базе данных или выполнении запроса удаления: " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Произошла общая ошибка при удалении: " + ex.Message);
}
}
private bool IsProductInOrders(string productArticle)
{
try
{
DB db = new DB();
using (MySqlConnection connection = db.getConnection())
{
connection.Open();
// Предполагаем, что в таблице orderitems столбец с артикулом товара называется 'product_article'
string query = "SELECT COUNT(*) FROM OrderItems WHERE product_article = @art";
using (MySqlCommand command = new MySqlCommand(query, connection))
{
command.Parameters.AddWithValue("@art", productArticle);
// ExecuteScalar возвращает первый столбец первой строки в результирующем наборе
// или null, если результирующий набор пуст.
// В нашем случае, COUNT(*) всегда вернет число.
long count = (long)command.ExecuteScalar();
return count > 0; // Если count > 0, значит товар участвует в заказах
}
}
}
catch (MySqlException ex)
{
MessageBox.Show("Ошибка при проверке наличия товара в заказах: " + ex.Message, "Ошибка базы данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return true; // Возвращаем true, чтобы предотвратить удаление при ошибке, для безопасности
}
catch (Exception ex)
{
MessageBox.Show("Произошла общая ошибка при проверке наличия товара в заказах: " + ex.Message, "Общая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return true; // Возвращаем true, чтобы предотвратить удаление при ошибке, для безопасности
}
}
private void OrdersBtn_Click(object sender, EventArgs e)
{
this.Hide();
AdmOrder ao = new AdmOrder();
ao.Show();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}