From c7a8b337e7c9ea097e0b2666fbb4d6487a5db396 Mon Sep 17 00:00:00 2001 From: LivelyPuer Date: Fri, 20 Dec 2024 01:12:17 +0400 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=95=D0=93=D0=90=20=D0=9A=D0=9E=D0=9C?= =?UTF-8?q?=D0=9C=D0=98=D0=A2=202.0.=20=D0=9F=D0=BE=D0=B4=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D0=B0=D1=82=D1=8C=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Forms/FormCustomers.Designer.cs | 29 +++-- .../Forms/FormOrder.Designer.cs | 19 --- .../ProjectOpticsStore/Forms/FormOrder.cs | 38 ++++++ .../ProjectOpticsStore/Forms/FormOrder.resx | 6 - .../Forms/FormOrders.Designer.cs | 24 ++-- .../ProjectOpticsStore/Forms/FormOrders.cs | 5 + .../Forms/FormProduct.Designer.cs | 4 +- .../ProjectOpticsStore/Forms/FormProduct.cs | 24 ++-- .../Forms/FormProducts.Designer.cs | 29 +++-- .../Forms/FormStores.Designer.cs | 29 +++-- .../Forms/FormSupplies.Designer.cs | 19 +-- .../ProjectOpticsStore/Program.cs | 22 ++++ .../ProjectOpticsStore.csproj | 19 +++ .../Repositories/IConnectionString.cs | 6 + .../Implementations/ConnectionString.cs | 6 + .../Implementations/CustomerRepository.cs | 102 ++++++++++++++-- .../Implementations/OrderRepository.cs | 81 +++++++++++- .../Implementations/ProductRepository.cs | 115 ++++++++++++++++-- .../Implementations/StoreRepository.cs | 108 ++++++++++++++-- .../Implementations/SupplyRepository.cs | 46 ++++++- .../ProjectOpticsStore/appsettings.json | 15 +++ 21 files changed, 626 insertions(+), 120 deletions(-) create mode 100644 ProjectOpticsStore/ProjectOpticsStore/Repositories/IConnectionString.cs create mode 100644 ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ConnectionString.cs create mode 100644 ProjectOpticsStore/ProjectOpticsStore/appsettings.json diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormCustomers.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormCustomers.Designer.cs index 12090e8..db7a1b4 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormCustomers.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormCustomers.Designer.cs @@ -43,18 +43,20 @@ panelButtons.Controls.Add(buttonUpd); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; - panelButtons.Location = new Point(650, 0); + panelButtons.Location = new Point(569, 0); + panelButtons.Margin = new Padding(3, 2, 3, 2); panelButtons.Name = "panelButtons"; - panelButtons.Size = new Size(150, 450); + panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 1; // // buttonDel // buttonDel.BackgroundImage = Properties.Resources.Button_Delete; buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(20, 323); + buttonDel.Location = new Point(18, 242); + buttonDel.Margin = new Padding(3, 2, 3, 2); buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(113, 100); + buttonDel.Size = new Size(99, 75); buttonDel.TabIndex = 2; buttonDel.UseVisualStyleBackColor = true; buttonDel.Click += ButtonDel_Click; @@ -63,9 +65,10 @@ // buttonUpd.BackgroundImage = Properties.Resources.Button_Edit; buttonUpd.BackgroundImageLayout = ImageLayout.Stretch; - buttonUpd.Location = new Point(20, 174); + buttonUpd.Location = new Point(18, 130); + buttonUpd.Margin = new Padding(3, 2, 3, 2); buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(113, 100); + buttonUpd.Size = new Size(99, 75); buttonUpd.TabIndex = 1; buttonUpd.UseVisualStyleBackColor = true; buttonUpd.Click += ButtonUpd_Click; @@ -74,9 +77,10 @@ // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(20, 26); + buttonAdd.Location = new Point(18, 20); + buttonAdd.Margin = new Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(113, 100); + buttonAdd.Size = new Size(99, 75); buttonAdd.TabIndex = 0; buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; @@ -89,21 +93,24 @@ dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewData.Dock = DockStyle.Fill; dataGridViewData.Location = new Point(0, 0); + dataGridViewData.Margin = new Padding(3, 2, 3, 2); dataGridViewData.MultiSelect = false; dataGridViewData.Name = "dataGridViewData"; dataGridViewData.ReadOnly = true; dataGridViewData.RowHeadersVisible = false; dataGridViewData.RowHeadersWidth = 51; - dataGridViewData.Size = new Size(650, 450); + dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewData.Size = new Size(569, 338); dataGridViewData.TabIndex = 2; // // FormCustomers // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(dataGridViewData); Controls.Add(panelButtons); + Margin = new Padding(3, 2, 3, 2); Name = "FormCustomers"; StartPosition = FormStartPosition.CenterParent; Text = "Заказчики"; diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.Designer.cs index eaf2425..5f9630e 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.Designer.cs @@ -37,8 +37,6 @@ label3 = new Label(); comboBoxStatus = new ComboBox(); dataGridViewProducts = new DataGridView(); - ColumnProduct = new DataGridViewComboBoxColumn(); - ColumnQuantity = new DataGridViewTextBoxColumn(); groupBox1 = new GroupBox(); ((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit(); groupBox1.SuspendLayout(); @@ -120,7 +118,6 @@ // dataGridViewProducts // dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridViewProducts.Columns.AddRange(new DataGridViewColumn[] { ColumnProduct, ColumnQuantity }); dataGridViewProducts.Dock = DockStyle.Fill; dataGridViewProducts.Location = new Point(3, 23); dataGridViewProducts.Name = "dataGridViewProducts"; @@ -129,20 +126,6 @@ dataGridViewProducts.Size = new Size(392, 236); dataGridViewProducts.TabIndex = 14; // - // ColumnProduct - // - ColumnProduct.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - ColumnProduct.HeaderText = "Товар"; - ColumnProduct.MinimumWidth = 6; - ColumnProduct.Name = "ColumnProduct"; - // - // ColumnQuantity - // - ColumnQuantity.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - ColumnQuantity.HeaderText = "Количество"; - ColumnQuantity.MinimumWidth = 6; - ColumnQuantity.Name = "ColumnQuantity"; - // // groupBox1 // groupBox1.Controls.Add(dataGridViewProducts); @@ -186,7 +169,5 @@ private ComboBox comboBoxStatus; private DataGridView dataGridViewProducts; private GroupBox groupBox1; - private DataGridViewComboBoxColumn ColumnProduct; - private DataGridViewTextBoxColumn ColumnQuantity; } } \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs index 7a107ad..c125daa 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.cs @@ -33,11 +33,49 @@ public partial class FormOrder : Form dataGridViewProducts.AllowUserToAddRows = true; dataGridViewProducts.AllowUserToDeleteRows = true; + // Настройка таблицы товаров + InitializeDataGridViewProducts(); + // Настройка DateTimePicker для даты заказа dateTimePickerOrderDate.Value = DateTime.Now; dateTimePickerOrderDate.Enabled = false; } + private void InitializeDataGridViewProducts() + { + // Отключаем авто-генерацию столбцов + dataGridViewProducts.AutoGenerateColumns = false; + + // Устанавливаем режим авторазмера столбцов + dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + + // Столбец "Товар" + var productColumn = new DataGridViewComboBoxColumn + { + Name = "ColumnProduct", + HeaderText = "Товар", + DataSource = _productRepository.ReadProducts() + .Select(p => new { p.Id, p.Type }) // Пример данных: Id и Name + .ToList(), + DisplayMember = "Type", + ValueMember = "Id", + FlatStyle = FlatStyle.Flat + }; + dataGridViewProducts.Columns.Add(productColumn); + + // Столбец "Количество" + var quantityColumn = new DataGridViewTextBoxColumn + { + Name = "ColumnQuantity", + HeaderText = "Количество", + ValueType = typeof(int) + }; + dataGridViewProducts.Columns.Add(quantityColumn); + + productColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + quantityColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + private void ButtonSave_Click(object sender, EventArgs e) { diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.resx b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.resx index 70d9360..8b2ff64 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.resx +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrder.resx @@ -117,10 +117,4 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True - - - True - \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs index 8c8ba74..ff1d271 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.Designer.cs @@ -41,18 +41,20 @@ panelButtons.Controls.Add(buttonDel); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; - panelButtons.Location = new Point(650, 0); + panelButtons.Location = new Point(569, 0); + panelButtons.Margin = new Padding(3, 2, 3, 2); panelButtons.Name = "panelButtons"; - panelButtons.Size = new Size(150, 450); + panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 2; // // buttonDel // buttonDel.BackgroundImage = Properties.Resources.Button_Delete; buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(20, 323); + buttonDel.Location = new Point(18, 242); + buttonDel.Margin = new Padding(3, 2, 3, 2); buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(113, 100); + buttonDel.Size = new Size(99, 75); buttonDel.TabIndex = 2; buttonDel.UseVisualStyleBackColor = true; buttonDel.Click += ButtonDel_Click; @@ -61,9 +63,10 @@ // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(20, 26); + buttonAdd.Location = new Point(18, 20); + buttonAdd.Margin = new Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(113, 100); + buttonAdd.Size = new Size(99, 75); buttonAdd.TabIndex = 0; buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; @@ -76,21 +79,24 @@ dataGridViewOrders.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewOrders.Dock = DockStyle.Fill; dataGridViewOrders.Location = new Point(0, 0); + dataGridViewOrders.Margin = new Padding(3, 2, 3, 2); dataGridViewOrders.MultiSelect = false; dataGridViewOrders.Name = "dataGridViewOrders"; dataGridViewOrders.ReadOnly = true; dataGridViewOrders.RowHeadersVisible = false; dataGridViewOrders.RowHeadersWidth = 51; - dataGridViewOrders.Size = new Size(650, 450); + dataGridViewOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewOrders.Size = new Size(569, 338); dataGridViewOrders.TabIndex = 3; // // FormOrders // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(dataGridViewOrders); Controls.Add(panelButtons); + Margin = new Padding(3, 2, 3, 2); Name = "FormOrders"; Text = "Заказать товары"; Load += FormOrders_Load; diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs index 5b6f721..ca28af2 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormOrders.cs @@ -73,6 +73,11 @@ public partial class FormOrders : Form private void LoadList() { dataGridViewOrders.DataSource = _orderRepository.ReadOrders(); + + if (dataGridViewOrders.Columns.Contains("OrderProducts")) + { + dataGridViewOrders.Columns["OrderProducts"].Visible = false; + } } // Метод для получения идентификатора заказа из выбранной строки в DataGridView diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.Designer.cs index b920a82..4872f61 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.Designer.cs @@ -104,9 +104,9 @@ label4.AutoSize = true; label4.Location = new Point(32, 287); label4.Name = "label4"; - label4.Size = new Size(97, 20); + label4.Size = new Size(72, 20); label4.TabIndex = 8; - label4.Text = "ID магазина:"; + label4.Text = "Магазин:"; // // label5 // diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.cs index 3381bda..cc50fc2 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProduct.cs @@ -1,11 +1,12 @@ -using ProjectOpticsStore.Entities; -using ProjectOpticsStore.Entities.Enums; +using ProjectOpticsStore.Entities.Enums; using ProjectOpticsStore.Repositories; + namespace ProjectOpticsStore.Forms; public partial class FormProduct : Form { private readonly IProductRepository _productRepository; + private readonly IStoreRepository _storeRepository; private int? _productId; public int Id @@ -34,7 +35,7 @@ public partial class FormProduct : Form // Заполнение текстовых полей textBoxPower.Text = product.Power.ToString(); textBoxPrice.Text = product.Price.ToString(); - comboBoxStore.Text = product.Store.ToString(); + comboBoxStore.SelectedValue = product.Store; textBoxThickness.Text = product.Thickness.ToString("F2"); textBoxDisease.Text = product.Disease; @@ -48,16 +49,22 @@ public partial class FormProduct : Form } } - public FormProduct(IProductRepository productRepository) + public FormProduct(IProductRepository productRepository, IStoreRepository storeRepository) { InitializeComponent(); _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + _storeRepository = storeRepository ?? throw new ArgumentNullException(nameof(storeRepository)); - // Заполнение CheckedListBox значениями перечисления + // Инициализация CheckedListBox значениями перечисления foreach (var elem in Enum.GetValues(typeof(ProductTypeEnum))) { checkedListBoxProductType.Items.Add(elem); } + + // Инициализация ComboBox для магазинов + comboBoxStore.DataSource = _storeRepository.ReadStores().ToList(); + comboBoxStore.DisplayMember = "Address"; // Отображаем адрес магазина + comboBoxStore.ValueMember = "Id"; // Значение это идентификатор магазина } private void ButtonSave_Click(object sender, EventArgs e) @@ -68,7 +75,7 @@ public partial class FormProduct : Form if (checkedListBoxProductType.CheckedItems.Count == 0 || string.IsNullOrWhiteSpace(textBoxPower.Text) || string.IsNullOrWhiteSpace(textBoxPrice.Text) || - string.IsNullOrWhiteSpace(comboBoxStore.Text) || + comboBoxStore.SelectedValue == null || string.IsNullOrWhiteSpace(textBoxThickness.Text)) { throw new Exception("Имеются незаполненные поля."); @@ -103,13 +110,16 @@ public partial class FormProduct : Form productType |= (ProductTypeEnum)elem; } + // Получение идентификатора магазина из ComboBox (это целое число) + int storeId = (int)comboBoxStore.SelectedValue!; + // Создание сущности Product return Product.CreateEntity( id, productType, double.Parse(textBoxPower.Text), int.Parse(textBoxPrice.Text), - int.Parse(comboBoxStore.Text), + storeId, // Передаем идентификатор магазина, а не адрес float.Parse(textBoxThickness.Text), textBoxDisease.Text ); diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProducts.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProducts.Designer.cs index 80299ff..467e38a 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProducts.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormProducts.Designer.cs @@ -43,18 +43,20 @@ panelButtons.Controls.Add(buttonUpd); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; - panelButtons.Location = new Point(650, 0); + panelButtons.Location = new Point(569, 0); + panelButtons.Margin = new Padding(3, 2, 3, 2); panelButtons.Name = "panelButtons"; - panelButtons.Size = new Size(150, 450); + panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 3; // // buttonDel // buttonDel.BackgroundImage = Properties.Resources.Button_Delete; buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(20, 323); + buttonDel.Location = new Point(18, 242); + buttonDel.Margin = new Padding(3, 2, 3, 2); buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(113, 100); + buttonDel.Size = new Size(99, 75); buttonDel.TabIndex = 2; buttonDel.UseVisualStyleBackColor = true; buttonDel.Click += ButtonDel_Click; @@ -63,9 +65,10 @@ // buttonUpd.BackgroundImage = Properties.Resources.Button_Edit; buttonUpd.BackgroundImageLayout = ImageLayout.Stretch; - buttonUpd.Location = new Point(20, 174); + buttonUpd.Location = new Point(18, 130); + buttonUpd.Margin = new Padding(3, 2, 3, 2); buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(113, 100); + buttonUpd.Size = new Size(99, 75); buttonUpd.TabIndex = 1; buttonUpd.UseVisualStyleBackColor = true; buttonUpd.Click += ButtonUpd_Click; @@ -74,9 +77,10 @@ // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(20, 26); + buttonAdd.Location = new Point(18, 20); + buttonAdd.Margin = new Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(113, 100); + buttonAdd.Size = new Size(99, 75); buttonAdd.TabIndex = 0; buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; @@ -89,21 +93,24 @@ dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewProducts.Dock = DockStyle.Fill; dataGridViewProducts.Location = new Point(0, 0); + dataGridViewProducts.Margin = new Padding(3, 2, 3, 2); dataGridViewProducts.MultiSelect = false; dataGridViewProducts.Name = "dataGridViewProducts"; dataGridViewProducts.ReadOnly = true; dataGridViewProducts.RowHeadersVisible = false; dataGridViewProducts.RowHeadersWidth = 51; - dataGridViewProducts.Size = new Size(650, 450); + dataGridViewProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewProducts.Size = new Size(569, 338); dataGridViewProducts.TabIndex = 4; // // FormProducts // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(dataGridViewProducts); Controls.Add(panelButtons); + Margin = new Padding(3, 2, 3, 2); Name = "FormProducts"; Text = "Работа с товарами"; Load += FormProducts_Load; diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormStores.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormStores.Designer.cs index b8546b4..dbcec96 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormStores.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormStores.Designer.cs @@ -43,18 +43,20 @@ panelButtons.Controls.Add(buttonUpd); panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; - panelButtons.Location = new Point(650, 0); + panelButtons.Location = new Point(569, 0); + panelButtons.Margin = new Padding(3, 2, 3, 2); panelButtons.Name = "panelButtons"; - panelButtons.Size = new Size(150, 450); + panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 4; // // buttonDel // buttonDel.BackgroundImage = Properties.Resources.Button_Delete; buttonDel.BackgroundImageLayout = ImageLayout.Stretch; - buttonDel.Location = new Point(20, 323); + buttonDel.Location = new Point(18, 242); + buttonDel.Margin = new Padding(3, 2, 3, 2); buttonDel.Name = "buttonDel"; - buttonDel.Size = new Size(113, 100); + buttonDel.Size = new Size(99, 75); buttonDel.TabIndex = 2; buttonDel.UseVisualStyleBackColor = true; buttonDel.Click += ButtonDel_Click; @@ -63,9 +65,10 @@ // buttonUpd.BackgroundImage = Properties.Resources.Button_Edit; buttonUpd.BackgroundImageLayout = ImageLayout.Stretch; - buttonUpd.Location = new Point(20, 174); + buttonUpd.Location = new Point(18, 130); + buttonUpd.Margin = new Padding(3, 2, 3, 2); buttonUpd.Name = "buttonUpd"; - buttonUpd.Size = new Size(113, 100); + buttonUpd.Size = new Size(99, 75); buttonUpd.TabIndex = 1; buttonUpd.UseVisualStyleBackColor = true; buttonUpd.Click += ButtonUpd_Click; @@ -74,9 +77,10 @@ // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(20, 26); + buttonAdd.Location = new Point(18, 20); + buttonAdd.Margin = new Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(113, 100); + buttonAdd.Size = new Size(99, 75); buttonAdd.TabIndex = 0; buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; @@ -89,21 +93,24 @@ dataGridViewStores.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewStores.Dock = DockStyle.Fill; dataGridViewStores.Location = new Point(0, 0); + dataGridViewStores.Margin = new Padding(3, 2, 3, 2); dataGridViewStores.MultiSelect = false; dataGridViewStores.Name = "dataGridViewStores"; dataGridViewStores.ReadOnly = true; dataGridViewStores.RowHeadersVisible = false; dataGridViewStores.RowHeadersWidth = 51; - dataGridViewStores.Size = new Size(650, 450); + dataGridViewStores.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewStores.Size = new Size(569, 338); dataGridViewStores.TabIndex = 5; // // FormStores // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(dataGridViewStores); Controls.Add(panelButtons); + Margin = new Padding(3, 2, 3, 2); Name = "FormStores"; Text = "Так сказать магазины"; Load += FormStores_Load; diff --git a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs index 2945ac1..bc80e61 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Forms/FormSupplies.Designer.cs @@ -39,18 +39,20 @@ // panelButtons.Controls.Add(buttonAdd); panelButtons.Dock = DockStyle.Right; - panelButtons.Location = new Point(650, 0); + panelButtons.Location = new Point(569, 0); + panelButtons.Margin = new Padding(3, 2, 3, 2); panelButtons.Name = "panelButtons"; - panelButtons.Size = new Size(150, 450); + panelButtons.Size = new Size(131, 338); panelButtons.TabIndex = 5; // // buttonAdd // buttonAdd.BackgroundImage = Properties.Resources.Button_Add; buttonAdd.BackgroundImageLayout = ImageLayout.Stretch; - buttonAdd.Location = new Point(20, 26); + buttonAdd.Location = new Point(18, 20); + buttonAdd.Margin = new Padding(3, 2, 3, 2); buttonAdd.Name = "buttonAdd"; - buttonAdd.Size = new Size(113, 100); + buttonAdd.Size = new Size(99, 75); buttonAdd.TabIndex = 0; buttonAdd.UseVisualStyleBackColor = true; buttonAdd.Click += ButtonAdd_Click; @@ -63,21 +65,24 @@ dataGridViewSupplies.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewSupplies.Dock = DockStyle.Fill; dataGridViewSupplies.Location = new Point(0, 0); + dataGridViewSupplies.Margin = new Padding(3, 2, 3, 2); dataGridViewSupplies.MultiSelect = false; dataGridViewSupplies.Name = "dataGridViewSupplies"; dataGridViewSupplies.ReadOnly = true; dataGridViewSupplies.RowHeadersVisible = false; dataGridViewSupplies.RowHeadersWidth = 51; - dataGridViewSupplies.Size = new Size(650, 450); + dataGridViewSupplies.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridViewSupplies.Size = new Size(569, 338); dataGridViewSupplies.TabIndex = 6; // // FormSupplies // - AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(700, 338); Controls.Add(dataGridViewSupplies); Controls.Add(panelButtons); + Margin = new Padding(3, 2, 3, 2); Name = "FormSupplies"; Text = "Определенным образом поставка"; Load += FormSupplies_Load; diff --git a/ProjectOpticsStore/ProjectOpticsStore/Program.cs b/ProjectOpticsStore/ProjectOpticsStore/Program.cs index d5c6142..7c815d0 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Program.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Program.cs @@ -1,7 +1,11 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using ProjectOpticsStore.Repositories; using ProjectOpticsStore.Repositories.Implementations; +using Serilog; using Unity; using Unity.Lifetime; +using Unity.Microsoft.Logging; namespace ProjectOpticsStore { @@ -18,15 +22,33 @@ namespace ProjectOpticsStore ApplicationConfiguration.Initialize(); Application.Run(CreateContainer().Resolve()); } + + private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); container.RegisterType(new TransientLifetimeManager()); + container.RegisterType(new TransientLifetimeManager()); 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/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj b/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj index e5042c8..ac8876e 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj +++ b/ProjectOpticsStore/ProjectOpticsStore/ProjectOpticsStore.csproj @@ -13,7 +13,20 @@ + + + + + + + + + + + + + @@ -31,4 +44,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/IConnectionString.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/IConnectionString.cs new file mode 100644 index 0000000..e9914c0 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/IConnectionString.cs @@ -0,0 +1,6 @@ +namespace ProjectOpticsStore.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ConnectionString.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..cb682bd --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,6 @@ +namespace ProjectOpticsStore.Repositories.Implementations; + +internal class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Host=127.0.0.1;Database=opticsstore;Username=postgres;Password=postgres"; +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/CustomerRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/CustomerRepository.cs index f70a461..a5b5e02 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/CustomerRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/CustomerRepository.cs @@ -1,28 +1,116 @@ -using ProjectOpticsStore.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectOpticsStore.Entities; namespace ProjectOpticsStore.Repositories.Implementations; internal class CustomerRepository : ICustomerRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public CustomerRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateCustomer(Customer customer) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Customers (FullName) + VALUES (@FullName)"; + connection.Execute(queryInsert, customer); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateCustomer(Customer customer) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(customer)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Customers + SET + FullName=@Fullname + WHERE Id=@Id"; + connection.Execute(queryUpdate, customer); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteCustomer(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Customers + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Customer ReadCustomerById(int id) { - return Customer.CreateEntity(0, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Customers + WHERE Id=@id"; + var customer = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(customer)); + return customer; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadCustomers() { - return []; - } - - public void UpdateCustomer(Customer customer) - { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Customers"; + var customers = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(customers)); + return customers; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs index be3008c..f2deeac 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/OrderRepository.cs @@ -1,17 +1,92 @@ -namespace ProjectOpticsStore.Repositories.Implementations; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectOpticsStore.Entities; + +namespace ProjectOpticsStore.Repositories.Implementations; internal class OrderRepository : IOrderRepository { + 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 (CustomerId, DateCreated, Status) + VALUES (@CustomerId, @DateCreated, @Status); + SELECT MAX(Id) FROM Orders"; + var OrderId = connection.QueryFirst(queryInsert, order, transaction); + + var querySubInsert = @" + INSERT INTO Orders_Products (OrderId, ProductId, Quantity) + VALUES (@OrderId, @ProductId, @Quantity)"; + foreach (var elem in order.OrderProducts) + { + connection.Execute(querySubInsert, new { OrderId, elem.ProductId, elem.Quantity }, 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? dateFrom = null, DateTime? dateTo = null, int? customerId = null) { - return []; + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Orders"; + var orders = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); + return orders; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } } -} +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ProductRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ProductRepository.cs index 2c312cd..5437bcd 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ProductRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/ProductRepository.cs @@ -1,33 +1,124 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ProjectOpticsStore.Entities.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; namespace ProjectOpticsStore.Repositories.Implementations; internal 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); + var queryInsert = @" + INSERT INTO Products (Type, Power, Price, Store, Thickness, Disease) + VALUES (@Type, @Power, @Price, @Store, @Thickness, @Disease)"; + connection.Execute(queryInsert, product); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateProduct(Product product) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + try + { + + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Products + SET + Type=@Type, + Power=@Power, + Price=@Price, + Store=@Store, + Thickness=@Thickness, + Disease=@Disease + WHERE Id=@Id"; + connection.Execute(queryUpdate, product); + } + 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 Product ReadProductById(int id) { - return Product.CreateEntity(0, ProductTypeEnum.None, 0, 0, 0, 0, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Products + WHERE Id=@id"; + var product = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product)); + return product; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadProducts() { - return []; - } + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - public void UpdateProduct(Product product) - { + // SQL-запрос для получения всех продуктов + var querySelect = "SELECT * FROM Products"; + + var products = connection.Query(querySelect); + return products; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } -} +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/StoreRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/StoreRepository.cs index f22c8a9..d59b7b3 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/StoreRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/StoreRepository.cs @@ -1,33 +1,115 @@ -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 ProjectOpticsStore.Entities; -using ProjectOpticsStore.Entities.Enums; namespace ProjectOpticsStore.Repositories.Implementations; internal class StoreRepository : IStoreRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public StoreRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateStore(Store store) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Stores (Address) + VALUES (@Address)"; + connection.Execute(queryInsert, store); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateStore(Store store) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(store)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Stores + SET + Address=@Address + WHERE Id=@Id"; + connection.Execute(queryUpdate, store); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteStore(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Stores + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Store ReadStoreById(int id) { - return Store.CreateEntity(0, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Stores + WHERE Id=@id"; + var store = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(store)); + return store; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadStores() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Stores"; + var stores = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(stores)); + return stores; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } - - public void UpdateStore(Store store) - { - } -} +} \ No newline at end of file diff --git a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs index 536ed71..f741e9e 100644 --- a/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs +++ b/ProjectOpticsStore/ProjectOpticsStore/Repositories/Implementations/SupplyRepository.cs @@ -1,15 +1,57 @@ -using ProjectOpticsStore.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectOpticsStore.Entities; namespace ProjectOpticsStore.Repositories.Implementations; internal class SupplyRepository : ISupplyRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public SupplyRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateSupply(Supply supply) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Supplies (StoreId, OperationDate, ProductId, Quantity) + VALUES (@StoreId, @OperationDate, @ProductId, @Quantity)"; + connection.Execute(queryInsert, supply); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadSupplies(DateTime? dateFrom = null, DateTime? dateTo = null, int? storeId = null, int? productId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Supplies"; + var supplies = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supplies)); + return supplies; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectOpticsStore/ProjectOpticsStore/appsettings.json b/ProjectOpticsStore/ProjectOpticsStore/appsettings.json new file mode 100644 index 0000000..4d62eb7 --- /dev/null +++ b/ProjectOpticsStore/ProjectOpticsStore/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/schedule_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file