diff --git a/ProjectAtelier/Entities/Client.cs b/ProjectAtelier/Entities/Client.cs index 6f2da15..5519b98 100644 --- a/ProjectAtelier/Entities/Client.cs +++ b/ProjectAtelier/Entities/Client.cs @@ -11,7 +11,7 @@ public class Client public int Id { get; set; } public string Name { get; private set; } = string.Empty; public string Phone { get; private set; } = string.Empty; - public Gender Gender { get; private set; } = Gender.None; // Используем flag Gender + public Gender Gender { get; private set; } // Используем flag Gender public static Client CreateEntity(int id, string name, string phone, Gender gender) { diff --git a/ProjectAtelier/Entities/Product.cs b/ProjectAtelier/Entities/Product.cs index 2a42baa..f845731 100644 --- a/ProjectAtelier/Entities/Product.cs +++ b/ProjectAtelier/Entities/Product.cs @@ -8,12 +8,12 @@ namespace ProjectAtelier.Entities; public class Product { - public int Id { get; private set; } - public string Name { get; private set; } = string.Empty; + public int Id { get; set; } + public string Name { get; set; } = string.Empty; - public ProductView View{ get; private set; } - public int CountMaterial { get; private set; } - public IEnumerable ProductMaterial { get; private set; } = []; + public ProductView View{ get; set; } + public int CountMaterial { get; set; } + public IEnumerable ProductMaterial { get; set; } = []; public static Product CreateEntity(int id, string name, ProductView view, int countmaterial, IEnumerable productMaterial) { return new Product diff --git a/ProjectAtelier/Entities/ProductMaterial.cs b/ProjectAtelier/Entities/ProductMaterial.cs index ff9ebf8..491bbaf 100644 --- a/ProjectAtelier/Entities/ProductMaterial.cs +++ b/ProjectAtelier/Entities/ProductMaterial.cs @@ -10,8 +10,8 @@ namespace ProjectAtelier.Entities; { public int Id { get; private set; } public int ProductId { get; private set; } - public int MaterialId { get; private set; } - public int Count { get; private set; } + public int MaterialId { get; set; } + public int Count { get; set; } public static ProductMaterial CreateOperation(int id, int productId, int materialid, int count) { diff --git a/ProjectAtelier/Entities/enum/Gender.cs b/ProjectAtelier/Entities/enum/Gender.cs index 80d13ae..dda581c 100644 --- a/ProjectAtelier/Entities/enum/Gender.cs +++ b/ProjectAtelier/Entities/enum/Gender.cs @@ -5,13 +5,13 @@ using System.Text; using System.Threading.Tasks; namespace ProjectAtelier.Entities; - [Flags] +[Flags] public enum Gender { None = 0, - Male = 1, - Female = 2, + M = 1, + F = 2, Other = 4 } diff --git a/ProjectAtelier/Entities/enum/OrderStatus.cs b/ProjectAtelier/Entities/enum/OrderStatus.cs index 325989d..cecc102 100644 --- a/ProjectAtelier/Entities/enum/OrderStatus.cs +++ b/ProjectAtelier/Entities/enum/OrderStatus.cs @@ -8,8 +8,8 @@ namespace ProjectAtelier.Entities; public enum OrderStatus { None = 0, - NotCompleted = 1, - Reserv = 2, - Completed = 3 + Обработка = 1, + Пошив = 2, + Готово = 3 } diff --git a/ProjectAtelier/Entities/enum/ProductView.cs b/ProjectAtelier/Entities/enum/ProductView.cs index 33c14e8..b2815d8 100644 --- a/ProjectAtelier/Entities/enum/ProductView.cs +++ b/ProjectAtelier/Entities/enum/ProductView.cs @@ -9,8 +9,11 @@ namespace ProjectAtelier.Entities; public enum ProductView { None = 0, - Shirt = 1, - Trousers = 2, - Jacket = 3 + Рубашка = 1, + Брюки = 2, + Пиджак = 3, + Халат= 4, + Футболка= 5 + } diff --git a/ProjectAtelier/Forms/FormClient.cs b/ProjectAtelier/Forms/FormClient.cs index 8be7ddb..0e509a4 100644 --- a/ProjectAtelier/Forms/FormClient.cs +++ b/ProjectAtelier/Forms/FormClient.cs @@ -1,4 +1,5 @@ -using ProjectAtelier.Entities; +using Microsoft.VisualBasic.FileIO; +using ProjectAtelier.Entities; using ProjectAtelier.Repositories; using System; using System.Collections.Generic; @@ -28,10 +29,23 @@ namespace ProjectAtelier.Forms { throw new InvalidDataException(nameof(client)); } + //textBoxName.Text = client.Name; + //textBoxPhone.Text = client.Phone; + //SetCheckedListBoxGender(client.Gender); // Устанавливаем выбранные элементы + //_clientId = value;/////////////////////////////// + foreach (Gender elem in Enum.GetValues(typeof(Gender))) + { + if ((elem & client.Gender) != 0) + { + checkedListBoxGender.SetItemChecked(checkedListBoxGender.Items.IndexOf( + elem), true); + } + } textBoxName.Text = client.Name; textBoxPhone.Text = client.Phone; - SetCheckedListBoxGender(client.Gender); // Устанавливаем выбранные элементы _clientId = value; + + } catch (Exception ex) { @@ -44,21 +58,25 @@ namespace ProjectAtelier.Forms public FormClient(IClientRepository clientRepository) { InitializeComponent(); - _clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository)); + _clientRepository = clientRepository ?? + throw new ArgumentNullException(nameof(clientRepository)); + foreach (var elem in Enum.GetValues(typeof(Gender))) + { + checkedListBoxGender.Items.Add(elem); + } - // Инициализация CheckedListBox с элементами перечисления Gender - checkedListBoxGender.Items.AddRange(Enum.GetValues(typeof(Gender)).Cast().ToArray()); } private void ButtonAdd_Click(object sender, EventArgs e) { try { - if (string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxPhone.Text)) + if (string.IsNullOrWhiteSpace(textBoxName.Text) || + string.IsNullOrWhiteSpace(textBoxPhone.Text) || + checkedListBoxGender.CheckedItems.Count == 0) { throw new Exception("Имеются незаполненные поля"); } - if (_clientId.HasValue) { _clientRepository.UpdateClient(CreateClient(_clientId.Value)); @@ -71,34 +89,22 @@ namespace ProjectAtelier.Forms } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при сохранении", + MessageBoxButtons.OK, MessageBoxIcon.Error); } + } - private void ButtonCancel_Click(object sender, EventArgs e) => Close(); - + private void ButtonCancel_Click(object sender, EventArgs e) =>Close(); private Client CreateClient(int id) { - // Получаем выбранные значения из CheckedListBox Gender gender = Gender.None; - foreach (var item in checkedListBoxGender.CheckedItems) + foreach (var elem in checkedListBoxGender.CheckedItems) { - gender |= (Gender)item; + gender |= (Gender)elem; } - return Client.CreateEntity(id, textBoxName.Text, textBoxPhone.Text, gender); } - - private void SetCheckedListBoxGender(Gender gender) - { - checkedListBoxGender.ClearSelected(); - foreach (var item in checkedListBoxGender.Items) - { - if (gender.HasFlag((Gender)item)) - { - checkedListBoxGender.SetItemChecked(checkedListBoxGender.Items.IndexOf(item), true); - } - } - } } + } \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormClientS.cs b/ProjectAtelier/Forms/FormClientS.cs index 59a58f0..aeef57c 100644 --- a/ProjectAtelier/Forms/FormClientS.cs +++ b/ProjectAtelier/Forms/FormClientS.cs @@ -66,7 +66,7 @@ namespace ProjectAtelier.Forms } try { - var form = _container.Resolve(); + var form = _container.Resolve(); form.Id = findId; form.ShowDialog(); LoadList(); @@ -76,7 +76,7 @@ namespace ProjectAtelier.Forms MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = _clientRepository.ReadClient(); + private void LoadList() => dataGridView.DataSource = _clientRepository.ReadClients(); private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ProjectAtelier/Forms/FormProductMaterial.Designer.cs b/ProjectAtelier/Forms/FormProductMaterial.Designer.cs index 3a05021..6d6bae7 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.Designer.cs +++ b/ProjectAtelier/Forms/FormProductMaterial.Designer.cs @@ -30,8 +30,9 @@ { groupBox = new GroupBox(); dataGridView = new DataGridView(); - ColumnMaterials = new DataGridViewComboBoxColumn(); + ColumnMaterial = new DataGridViewComboBoxColumn(); ColumnCount = new DataGridViewTextBoxColumn(); + ColumProduct = new DataGridViewTextBoxColumn(); buttonAdd = new Button(); buttonCancel = new Button(); labelName = new Label(); @@ -60,7 +61,7 @@ // dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterials, ColumnCount }); + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnMaterial, ColumnCount, ColumProduct }); dataGridView.Dock = DockStyle.Fill; dataGridView.Location = new Point(3, 24); dataGridView.Margin = new Padding(3, 4, 3, 4); @@ -71,13 +72,13 @@ dataGridView.Size = new Size(642, 328); dataGridView.TabIndex = 0; // - // ColumnMaterials + // ColumnMaterial // - ColumnMaterials.HeaderText = "Materials"; - ColumnMaterials.MinimumWidth = 6; - ColumnMaterials.Name = "ColumnMaterials"; - ColumnMaterials.Resizable = DataGridViewTriState.True; - ColumnMaterials.SortMode = DataGridViewColumnSortMode.Automatic; + ColumnMaterial.HeaderText = "Materials"; + ColumnMaterial.MinimumWidth = 6; + ColumnMaterial.Name = "ColumnMaterial"; + ColumnMaterial.Resizable = DataGridViewTriState.True; + ColumnMaterial.SortMode = DataGridViewColumnSortMode.Automatic; // // ColumnCount // @@ -85,6 +86,12 @@ ColumnCount.MinimumWidth = 6; ColumnCount.Name = "ColumnCount"; // + // ColumProduct + // + ColumProduct.HeaderText = "ColumnName"; + ColumProduct.MinimumWidth = 6; + ColumProduct.Name = "ColumProduct"; + // // buttonAdd // buttonAdd.Anchor = AnchorStyles.Bottom | AnchorStyles.Left; @@ -121,7 +128,7 @@ // labelType // labelType.AutoSize = true; - labelType.Location = new Point(35, 104); + labelType.Location = new Point(35, 109); labelType.Name = "labelType"; labelType.Size = new Size(96, 20); labelType.TabIndex = 4; @@ -148,7 +155,7 @@ // comboBoxProduct.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxProduct.FormattingEnabled = true; - comboBoxProduct.Location = new Point(215, 104); + comboBoxProduct.Location = new Point(215, 101); comboBoxProduct.Margin = new Padding(3, 4, 3, 4); comboBoxProduct.Name = "comboBoxProduct"; comboBoxProduct.Size = new Size(161, 28); @@ -192,13 +199,14 @@ private DataGridView dataGridView; private Button buttonAdd; private Button buttonCancel; - private DataGridViewComboBoxColumn ColumnMaterials; - private DataGridViewTextBoxColumn ColumnCount; private Label labelName; private Label labelType; private Label labelCountInWarehouse; private TextBox textBoxName; private ComboBox comboBoxProduct; private NumericUpDown numericUpDownCount; + private DataGridViewComboBoxColumn ColumnMaterial; + private DataGridViewTextBoxColumn ColumnCount; + private DataGridViewTextBoxColumn ColumProduct; } } \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductMaterial.cs b/ProjectAtelier/Forms/FormProductMaterial.cs index 519a910..76bba16 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.cs +++ b/ProjectAtelier/Forms/FormProductMaterial.cs @@ -1,5 +1,15 @@ using ProjectAtelier.Entities; using ProjectAtelier.Repositories; +using ProjectAtelier.Repositories.Implementations; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; namespace ProjectAtelier.Forms { @@ -23,10 +33,17 @@ namespace ProjectAtelier.Forms comboBoxProduct.SelectedItem = product.View; numericUpDownCount.Value = product.CountMaterial; _productId = value; + + // Заполняем DataGridView данными из product.ProductMaterial + dataGridView.Rows.Clear(); + foreach (var material in product.ProductMaterial) + { + dataGridView.Rows.Add(material.MaterialId, material.Count); + } } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при полученииданных", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } @@ -38,20 +55,18 @@ namespace ProjectAtelier.Forms _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductView)); - - ColumnMaterials.DataSource = materialRepository.ReadMaterials(); - ColumnMaterials.DisplayMember = "Name"; - ColumnMaterials.ValueMember = "Id"; + } private void buttonAdd_Click(object sender, EventArgs e) { if (dataGridView.RowCount < 1) { - throw new Exception("Имеются незаполненны поля"); + MessageBox.Show("Имеются незаполненные поля", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } try { - if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 1) + if (string.IsNullOrWhiteSpace(textBoxName.Text) || comboBoxProduct.SelectedIndex < 0) { throw new Exception("Имеются незаполненные поля"); } @@ -76,17 +91,25 @@ namespace ProjectAtelier.Forms var list = new List(); foreach (DataGridViewRow row in dataGridView.Rows) { - if (row.Cells["ColumProduct"].Value == null || row.Cells["ColumMaterials"].Value == null || row.Cells["ColumnCount"].Value == null) + if (row.Cells["ColumnMaterial"].Value == null || row.Cells["ColumnCount"].Value == null) { continue; } - list.Add(ProductMaterial.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnMaterial"].Value), - Convert.ToInt32(row.Cells["ColumnProduct"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); + list.Add(new ProductMaterial + { + MaterialId = Convert.ToInt32(row.Cells["ColumnMaterial"].Value), + Count = Convert.ToInt32(row.Cells["ColumnCount"].Value) + }); } return list; } - private Product CreateProduct(int id) => Product.CreateEntity(id, textBoxName.Text, (ProductView)comboBoxProduct.SelectedItem!, Convert.ToInt32(numericUpDownCount.Value), CreateListMaterialFromDataGrid()); - - + private Product CreateProduct(int id) => new Product + { + Id = id, + Name = textBoxName.Text, + View = (ProductView)comboBoxProduct.SelectedItem, + CountMaterial = Convert.ToInt32(numericUpDownCount.Value), + ProductMaterial = CreateListMaterialFromDataGrid() + }; } -} +} \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductMaterial.resx b/ProjectAtelier/Forms/FormProductMaterial.resx index 8b2ff64..605ec60 100644 --- a/ProjectAtelier/Forms/FormProductMaterial.resx +++ b/ProjectAtelier/Forms/FormProductMaterial.resx @@ -117,4 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + True + \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductOrder.Designer.cs b/ProjectAtelier/Forms/FormProductOrder.Designer.cs index 0492cc8..4a9c1eb 100644 --- a/ProjectAtelier/Forms/FormProductOrder.Designer.cs +++ b/ProjectAtelier/Forms/FormProductOrder.Designer.cs @@ -36,12 +36,12 @@ comboBoxStatus = new ComboBox(); groupBox = new GroupBox(); dataGridView = new DataGridView(); - ColumnProducts = new DataGridViewComboBoxColumn(); - ColumnCount = new DataGridViewTextBoxColumn(); comboBoxClient = new ComboBox(); labelClient = new Label(); dateTimePicker = new DateTimePicker(); label1 = new Label(); + ColumProduct = new DataGridViewComboBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); groupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -120,7 +120,7 @@ // dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnProducts, ColumnCount }); + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumProduct, ColumnCount }); dataGridView.Dock = DockStyle.Fill; dataGridView.Location = new Point(3, 24); dataGridView.Margin = new Padding(3, 4, 3, 4); @@ -131,19 +131,6 @@ dataGridView.Size = new Size(499, 408); dataGridView.TabIndex = 0; // - // ColumnProducts - // - ColumnProducts.HeaderText = "Изделие"; - ColumnProducts.MinimumWidth = 6; - ColumnProducts.Name = "ColumnProducts"; - ColumnProducts.ReadOnly = true; - // - // ColumnCount - // - ColumnCount.HeaderText = "Количество"; - ColumnCount.MinimumWidth = 6; - ColumnCount.Name = "ColumnCount"; - // // comboBoxClient // comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList; @@ -179,6 +166,19 @@ label1.TabIndex = 11; label1.Text = "Дата"; // + // ColumProduct + // + ColumProduct.HeaderText = "Изделие"; + ColumProduct.MinimumWidth = 6; + ColumProduct.Name = "ColumProduct"; + ColumProduct.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.MinimumWidth = 6; + ColumnCount.Name = "ColumnCount"; + // // FormProductOrder // AutoScaleDimensions = new SizeF(8F, 20F); @@ -216,9 +216,9 @@ private DataGridView dataGridView; private ComboBox comboBoxClient; private Label labelClient; - private DataGridViewComboBoxColumn ColumnProducts; - private DataGridViewTextBoxColumn ColumnCount; private DateTimePicker dateTimePicker; private Label label1; + private DataGridViewComboBoxColumn ColumProduct; + private DataGridViewTextBoxColumn ColumnCount; } } \ No newline at end of file diff --git a/ProjectAtelier/Forms/FormProductOrder.cs b/ProjectAtelier/Forms/FormProductOrder.cs index 89e63f8..44b36cc 100644 --- a/ProjectAtelier/Forms/FormProductOrder.cs +++ b/ProjectAtelier/Forms/FormProductOrder.cs @@ -21,12 +21,12 @@ namespace ProjectAtelier.Forms comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus)); - ColumnProducts.DataSource = productRepository.ReadProducts(); - ColumnProducts.DisplayMember = "Name"; - ColumnProducts.ValueMember = "Id"; + ColumProduct.DataSource = productRepository.ReadProducts(); + ColumProduct.DisplayMember = "Name"; + ColumProduct.ValueMember = "Id"; // Заполняем ComboBox для выбора клиента - comboBoxClient.DataSource = clientRepository.ReadClient(); + comboBoxClient.DataSource = clientRepository.ReadClients(); comboBoxClient.DisplayMember = "Name"; comboBoxClient.ValueMember = "Id"; diff --git a/ProjectAtelier/Forms/FormProducts.Designer.cs b/ProjectAtelier/Forms/FormProducts.Designer.cs index 9aca103..dc224c8 100644 --- a/ProjectAtelier/Forms/FormProducts.Designer.cs +++ b/ProjectAtelier/Forms/FormProducts.Designer.cs @@ -88,6 +88,7 @@ buttonRemove.Size = new Size(94, 92); buttonRemove.TabIndex = 1; buttonRemove.UseVisualStyleBackColor = true; + buttonRemove.Click += buttonRemove_Click; // // buttonAdd // diff --git a/ProjectAtelier/Forms/FormProducts.cs b/ProjectAtelier/Forms/FormProducts.cs index b0160a4..c4321b5 100644 --- a/ProjectAtelier/Forms/FormProducts.cs +++ b/ProjectAtelier/Forms/FormProducts.cs @@ -97,6 +97,6 @@ namespace ProjectAtelier.Forms return true; } - + } } diff --git a/ProjectAtelier/Program.cs b/ProjectAtelier/Program.cs index b58f412..d597934 100644 --- a/ProjectAtelier/Program.cs +++ b/ProjectAtelier/Program.cs @@ -3,6 +3,10 @@ using ProjectAtelier.Repositories; using ProjectAtelier.REPOSITORY.Implementations; using ProjectAtelier.REPOSITORY; using Unity; +using Unity.Microsoft.Logging; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; namespace ProjectAtelier { @@ -22,14 +26,28 @@ namespace ProjectAtelier private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); + container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); container.RegisterType(); - + + container.RegisterType(); return container; } + private static LoggerFactory CreateLoggerFactory() + { + var loggerFactory = new LoggerFactory(); + loggerFactory.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json") + .Build()) + .CreateLogger()); + return loggerFactory; + } } } \ No newline at end of file diff --git a/ProjectAtelier/ProjectAtelier.csproj b/ProjectAtelier/ProjectAtelier.csproj index accbdf0..113ee2f 100644 --- a/ProjectAtelier/ProjectAtelier.csproj +++ b/ProjectAtelier/ProjectAtelier.csproj @@ -9,7 +9,18 @@ + + + + + + + + + + + @@ -27,4 +38,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectAtelier/REPOSITORY/Implementations/MaterialReplenishmentRepository.cs b/ProjectAtelier/REPOSITORY/Implementations/MaterialReplenishmentRepository.cs index 48e93a9..b617e6d 100644 --- a/ProjectAtelier/REPOSITORY/Implementations/MaterialReplenishmentRepository.cs +++ b/ProjectAtelier/REPOSITORY/Implementations/MaterialReplenishmentRepository.cs @@ -1,4 +1,9 @@ -using ProjectAtelier.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectAtelier.Entities; +using ProjectAtelier.Repositories; using System; using System.Collections.Generic; using System.Linq; @@ -9,21 +14,93 @@ namespace ProjectAtelier.REPOSITORY.Implementations; public class MaterialReplenishmentRepository : IMaterialReplenishmentRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public MaterialReplenishmentRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateMaterialSpent(MaterialReplenishment material) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO MaterialReplenishment (Count, DataTime, IDMaterial) + VALUES (@Count, @DataTime, @IDMaterial)"; + connection.Execute(queryInsert, material); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public MaterialReplenishment ReadMaterialSpentById(int id) { - return MaterialReplenishment.CreateOperation(0, 0, DateTime.Now, 0); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM MaterialReplenishment + WHERE Id=@id"; + var material = connection.QueryFirst(querySelect, new + { + id + }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(material)); + return material; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } - public IEnumerable ReadMaterialsSpent() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM MaterialReplenishment"; + var materials = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials)); + return materials; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateMaterialSpent(MaterialReplenishment material) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE MaterialReplenishment + SET + Count=@Count, + DataTime=@DataTime, + IDMaterial=@IDMaterial + WHERE Id=@Id"; + connection.Execute(queryUpdate, material); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } \ No newline at end of file diff --git a/ProjectAtelier/Repositories/IClientRepository.cs b/ProjectAtelier/Repositories/IClientRepository.cs index 79e5277..9ba4988 100644 --- a/ProjectAtelier/Repositories/IClientRepository.cs +++ b/ProjectAtelier/Repositories/IClientRepository.cs @@ -9,7 +9,7 @@ namespace ProjectAtelier.Repositories; public interface IClientRepository { - IEnumerable ReadClient(); + IEnumerable ReadClients(); Client ReadClientById(int id); void CreateClient(Client client); void UpdateClient(Client client); diff --git a/ProjectAtelier/Repositories/IConnectionString.cs b/ProjectAtelier/Repositories/IConnectionString.cs new file mode 100644 index 0000000..018fde7 --- /dev/null +++ b/ProjectAtelier/Repositories/IConnectionString.cs @@ -0,0 +1,5 @@ +namespace ProjectAtelier.Repositories; +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/ProjectAtelier/Repositories/IOrderRepository.cs b/ProjectAtelier/Repositories/IOrderRepository.cs index 3c2aa7b..e343442 100644 --- a/ProjectAtelier/Repositories/IOrderRepository.cs +++ b/ProjectAtelier/Repositories/IOrderRepository.cs @@ -10,7 +10,6 @@ namespace ProjectAtelier.Repositories; public interface IOrderRepository { IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderStatus = null, int? orderId = null); - Order ReadOrderById(int orderId); void CreateOrder(Order order); void DeleteOrder(int id); } diff --git a/ProjectAtelier/Repositories/Implementations/ClientRepository.cs b/ProjectAtelier/Repositories/Implementations/ClientRepository.cs index 40b2463..6d5c634 100644 --- a/ProjectAtelier/Repositories/Implementations/ClientRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/ClientRepository.cs @@ -1,33 +1,126 @@ -using ProjectAtelier.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectAtelier.Entities; + namespace ProjectAtelier.Repositories.Implementations; public class ClientRepository : IClientRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public ClientRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateClient(Client client) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(client)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO Clients (Name, Phone, Gender) +VALUES (@Name, @Phone, @Gender)"; + connection.Execute(queryInsert, client); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } - - public void DeleteClient(int id) - { - } - - public IEnumerable ReadClient() - { - return []; - } - - public Client ReadClientById(int id) - { - return Client.CreateEntity(id, string.Empty, string.Empty, Gender.None); - } - public void UpdateClient(Client client) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(client)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" +UPDATE Clients +SET +Name=@Name, +Phone=@Phone, +Gender=@Gender +WHERE Id=@Id"; + connection.Execute(queryUpdate, client); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } -} + public void DeleteClient(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" +DELETE FROM Clients +WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public Client ReadClientById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Clients + WHERE Id=@id"; + var client = connection.QueryFirst(querySelect, new + { + id + }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client)); + return client; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadClients() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Clients"; + var Client = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(Client)); + return Client; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } +} \ No newline at end of file diff --git a/ProjectAtelier/Repositories/Implementations/ConnectionString.cs b/ProjectAtelier/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..573ef97 --- /dev/null +++ b/ProjectAtelier/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectAtelier.Repositories.Implementations; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Server=localhost; Port=5432;Database=atelier;User Id=postgres; Password=postgres"; +} \ No newline at end of file diff --git a/ProjectAtelier/Repositories/Implementations/MaterialRepository.cs b/ProjectAtelier/Repositories/Implementations/MaterialRepository.cs index 5b1dedd..172ed14 100644 --- a/ProjectAtelier/Repositories/Implementations/MaterialRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/MaterialRepository.cs @@ -1,4 +1,8 @@ -using ProjectAtelier.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectAtelier.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,25 +13,113 @@ namespace ProjectAtelier.Repositories.Implementations; public class MaterialRepository : IMaterialRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public MaterialRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateMaterial(Material material) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Materials (Name, UseCount, CountInWareHouse) + VALUES (@Name, @UseCount, @CountInWareHouse)"; + connection.Execute(queryInsert, material); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateMaterial(Material material) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(material)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Materials + SET + Name=@Name, + UseCount=@UseCount, + CountInWareHouse=@CountInWareHouse + WHERE Id=@Id"; + connection.Execute(queryUpdate, material); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteMaterial(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Materials + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadMaterials() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Materials"; + var materials = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials)); + return materials; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Material ReadMaterialById(int id) { - return Material.CreateEntity(id, string.Empty, 0, 0); - } - - public void UpdateMaterial(Material material) - { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Materials + WHERE Id=@id"; + var material = connection.QueryFirst(querySelect, new + { + id + }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(material)); + return material; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } } diff --git a/ProjectAtelier/Repositories/Implementations/OrderRepository.cs b/ProjectAtelier/Repositories/Implementations/OrderRepository.cs index a9ae836..cf4f0cf 100644 --- a/ProjectAtelier/Repositories/Implementations/OrderRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/OrderRepository.cs @@ -1,4 +1,8 @@ -using ProjectAtelier.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectAtelier.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,20 +13,82 @@ namespace ProjectAtelier.Repositories.Implementations; public class OrderRepository : IOrderRepository { - public void CreateOrder(Order feedReplenishment) + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public OrderRepository(IConnectionString connectionString, ILogger logger) { + _connectionString = connectionString; + _logger = logger; + } + public void CreateOrder(Order order) + { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO Orders (DataTime, Status, Characteristic, IdClient) + VALUES (@DataTime, @Status, @Characteristic, @IdClient); + SELECT MAX(Id) FROM Orders"; + var orderId = connection.QueryFirst(queryInsert, order, transaction); + var querySubInsert = @" + INSERT INTO Orders_Products (OrderId, ProductId, Count) + VALUES (@OrderId, @ProductId, @Count)"; + foreach (var elem in order.OrderProduct) + { + connection.Execute(querySubInsert, new + { + orderId, + elem.ProductId, + elem.Count + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteOrder(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Orders + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderStatus = null, int? orderId = null) { - return []; - } - public Order ReadOrderById(int id) - { - return Order.CreateOperation(id, 0, string.Empty, [], 0, DateTime.Now); + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM Orders"; + var order = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(order)); + return order; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectAtelier/Repositories/Implementations/ProductRepository.cs b/ProjectAtelier/Repositories/Implementations/ProductRepository.cs index 7f2436a..87e2ddc 100644 --- a/ProjectAtelier/Repositories/Implementations/ProductRepository.cs +++ b/ProjectAtelier/Repositories/Implementations/ProductRepository.cs @@ -1,4 +1,8 @@ -using ProjectAtelier.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectAtelier.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,25 +13,157 @@ namespace ProjectAtelier.Repositories.Implementations; public class ProductRepository : IProductRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + public ProductRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateProduct(Product product) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO Products (Name, View, CountMaterial) + VALUES (@Name, @View, @CountMaterial); + SELECT MAX(Id) FROM Products"; + var productId = connection.QueryFirst(queryInsert, product, transaction); + var querySubInsert = @" + INSERT INTO Product_Materials (ProductId, MaterialId, Count) + VALUES (@ProductId, @MaterialId, @Count)"; + foreach (var elem in product.ProductMaterial) + { + connection.Execute(querySubInsert, new + { + productId, + elem.MaterialId, + elem.Count + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteProduct(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Products + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadProducts() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM Products"; + var product = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(product)); + return product; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public Product ReadProductById(int id) { - return Product.CreateEntity(id, string.Empty, 0, 0, []); + _logger.LogInformation("Получение объекта по ID: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Products WHERE Id = @Id; + SELECT m.*, pm.Count FROM Materials m + JOIN Product_Materials pm ON m.Id = pm.MaterialId + WHERE pm.ProductId = @Id"; + using var multi = connection.QueryMultiple(querySelect, new { Id = id }); + var product = multi.Read().FirstOrDefault(); + if (product != null) + { + var materials = multi.Read().ToList(); + product.ProductMaterial = materials.Select(m => new ProductMaterial + { + MaterialId = m.Id, + Count = m.UseCount // Исправлено здесь + }).ToList(); + } + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product)); + return product; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объекта по ID: {id}", id); + throw; + } } public void UpdateProduct(Product product) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + + var queryUpdate = @" + UPDATE Products + SET Name = @Name, View = @View, CountMaterial = @CountMaterial + WHERE Id = @Id"; + connection.Execute(queryUpdate, product, transaction); + + var queryDelete = @" + DELETE FROM Product_Materials + WHERE ProductId = @ProductId"; + connection.Execute(queryDelete, new { ProductId = product.Id }, transaction); + + var querySubInsert = @" + INSERT INTO Product_Materials (ProductId, MaterialId, Count) + VALUES (@ProductId, @MaterialId, @Count)"; + foreach (var elem in product.ProductMaterial) + { + connection.Execute(querySubInsert, new + { + ProductId = product.Id, + elem.MaterialId, + elem.Count + }, transaction); + } + + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectAtelier/appsettings.json b/ProjectAtelier/appsettings.json new file mode 100644 index 0000000..540cd04 --- /dev/null +++ b/ProjectAtelier/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file