diff --git a/.vs/VSWorkspaceState.json b/.vs/VSWorkspaceState.json new file mode 100644 index 0000000..2eed879 --- /dev/null +++ b/.vs/VSWorkspaceState.json @@ -0,0 +1,7 @@ +{ + "ExpandedNodes": [ + "" + ], + "SelectedNode": "\\C:\\Users\\79061\\Desktop\\dddddddddddddddddd", + "PreviewInSolutionExplorer": false +} \ No newline at end of file diff --git a/.vs/dddddddddddddddddd/v17/.wsuo b/.vs/dddddddddddddddddd/v17/.wsuo new file mode 100644 index 0000000..2d13dfa Binary files /dev/null and b/.vs/dddddddddddddddddd/v17/.wsuo differ diff --git a/.vs/dddddddddddddddddd/v17/DocumentLayout.json b/.vs/dddddddddddddddddd/v17/DocumentLayout.json new file mode 100644 index 0000000..22cb232 --- /dev/null +++ b/.vs/dddddddddddddddddd/v17/DocumentLayout.json @@ -0,0 +1,23 @@ +{ + "Version": 1, + "WorkspaceRootPath": "C:\\Users\\79061\\Desktop\\dddddddddddddddddd\\", + "Documents": [], + "DocumentGroupContainers": [ + { + "Orientation": 0, + "VerticalTabListWidth": 256, + "DocumentGroups": [ + { + "DockedWidth": 200, + "SelectedChildIndex": -1, + "Children": [ + { + "$type": "Bookmark", + "Name": "ST:0:0:{1c4feeaa-4718-4aa9-859d-94ce25d182ba}" + } + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/.gitignore b/CompShop/.gitignore similarity index 100% rename from .gitignore rename to CompShop/.gitignore diff --git a/CompShop/CompShop/CompShop.csproj b/CompShop/CompShop/CompShop.csproj index 894afcd..36bb7a7 100644 --- a/CompShop/CompShop/CompShop.csproj +++ b/CompShop/CompShop/CompShop.csproj @@ -8,8 +8,16 @@ enable - - - + + + + + + + + + + + \ No newline at end of file diff --git a/CompShop/CompShop/Entites/Check.cs b/CompShop/CompShop/Entites/Check.cs index 2127902..2f4d40c 100644 --- a/CompShop/CompShop/Entites/Check.cs +++ b/CompShop/CompShop/Entites/Check.cs @@ -1,10 +1,15 @@ -namespace CompShop.Entites +using CompShop.Entites; + +namespace CompShop.Entites { public class Check { public int Id { get; set; } public List Products { get; set; } public Client Client { get; set; } + + [System.ComponentModel.Browsable(false)] + public int ClientId { get; set; } public DateTime PurchaseDate { get; set; } public static Check CreateEntity(int id, List products, Client client, DateTime purchaseDate) diff --git a/CompShop/CompShop/Entites/Client.cs b/CompShop/CompShop/Entites/Client.cs index bef56cc..55103ea 100644 --- a/CompShop/CompShop/Entites/Client.cs +++ b/CompShop/CompShop/Entites/Client.cs @@ -1,4 +1,10 @@ using CompShop.Entites.Enums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + namespace CompShop.Entites { public class Client @@ -18,5 +24,11 @@ namespace CompShop.Entites ClientType = clientType }; } + + public override string ToString() + { + return Name; + } } } + diff --git a/CompShop/CompShop/Entites/Product.cs b/CompShop/CompShop/Entites/Product.cs index aea69d1..9951bf4 100644 --- a/CompShop/CompShop/Entites/Product.cs +++ b/CompShop/CompShop/Entites/Product.cs @@ -12,11 +12,18 @@ namespace CompShop.Entites public static Product CreateEntity(int id, string name, string desc, decimal price, ProductType productType) { - return new Product { ID = id, + return new Product + { + ID = id, Name = name ?? string.Empty, Description = desc ?? string.Empty, Price = price, - ProductType = productType }; + ProductType = productType + }; + } + public override string ToString() + { + return Name; } } } diff --git a/CompShop/CompShop/Entites/ProductInCheck.cs b/CompShop/CompShop/Entites/ProductInCheck.cs index 9dab523..15e9a5c 100644 --- a/CompShop/CompShop/Entites/ProductInCheck.cs +++ b/CompShop/CompShop/Entites/ProductInCheck.cs @@ -1,12 +1,20 @@ -namespace CompShop.Entites +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Entites { public class ProductInCheck { public int ID { get; set; } + public int ProductID { get; set; } + public int CheckID { get; set; } public int Count { get; set; } public static ProductInCheck CreateElement(int id, int count) { - return new ProductInCheck { ID = id, Count = count}; + return new ProductInCheck { ProductID = id, Count = count }; } } } diff --git a/CompShop/CompShop/Entites/ProductsOnStorage.cs b/CompShop/CompShop/Entites/ProductsOnStorage.cs index 7bec734..e887310 100644 --- a/CompShop/CompShop/Entites/ProductsOnStorage.cs +++ b/CompShop/CompShop/Entites/ProductsOnStorage.cs @@ -1,9 +1,19 @@ -namespace CompShop.Entites +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Entites { public class ProductsOnStorage { public int Id { get; set; } + [System.ComponentModel.Browsable(false)] + public int ProductId { get; set; } public Product Product { get; set; } + [System.ComponentModel.Browsable(false)] + public int StorageId { get; set; } public Storage Storage { get; set; } public int Count { get; set; } @@ -11,5 +21,6 @@ { return new ProductsOnStorage { Storage = storage, Id = id, Product = product, Count = count }; } + } } diff --git a/CompShop/CompShop/Entites/Storage.cs b/CompShop/CompShop/Entites/Storage.cs index f7136e1..ecdfe9f 100644 --- a/CompShop/CompShop/Entites/Storage.cs +++ b/CompShop/CompShop/Entites/Storage.cs @@ -1,4 +1,11 @@ -namespace CompShop.Entites +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace CompShop.Entites { public class Storage { @@ -10,5 +17,10 @@ { return new Storage { Id = id, Size = size, Adress = adress }; } + + public override string ToString() + { + return Adress; + } } -} +} \ No newline at end of file diff --git a/CompShop/CompShop/Forms/Clients/ClientForm.cs b/CompShop/CompShop/Forms/Clients/ClientForm.cs index fab2adf..a14ddb5 100644 --- a/CompShop/CompShop/Forms/Clients/ClientForm.cs +++ b/CompShop/CompShop/Forms/Clients/ClientForm.cs @@ -1,5 +1,14 @@ using CompShop.Forms.Clients; using CompShop.Repos; +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; using Unity; namespace CompShop.Forms diff --git a/CompShop/CompShop/Forms/Clients/ClientFormSettings.cs b/CompShop/CompShop/Forms/Clients/ClientFormSettings.cs index 6c4d272..721f993 100644 --- a/CompShop/CompShop/Forms/Clients/ClientFormSettings.cs +++ b/CompShop/CompShop/Forms/Clients/ClientFormSettings.cs @@ -1,6 +1,15 @@ using CompShop.Entites.Enums; using CompShop.Entites; using CompShop.Repos; +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 CompShop.Forms.Clients { @@ -17,7 +26,7 @@ namespace CompShop.Forms.Clients try { var client = _repository.Read(value); - if (client != null) + if (client == null) { throw new InvalidDataException(nameof(client)); } @@ -67,7 +76,7 @@ namespace CompShop.Forms.Clients else { - _repository.Update(CreateClient(0)); + _repository.Create(CreateClient(0)); } Close(); diff --git a/CompShop/CompShop/Forms/Products/ProductForm.cs b/CompShop/CompShop/Forms/Products/ProductForm.cs index 7e330fa..f051627 100644 --- a/CompShop/CompShop/Forms/Products/ProductForm.cs +++ b/CompShop/CompShop/Forms/Products/ProductForm.cs @@ -1,4 +1,13 @@ using CompShop.Repos; +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; using Unity; namespace CompShop diff --git a/CompShop/CompShop/Forms/Products/ProductSettingsForm.cs b/CompShop/CompShop/Forms/Products/ProductSettingsForm.cs index 7fe0b45..fadb183 100644 --- a/CompShop/CompShop/Forms/Products/ProductSettingsForm.cs +++ b/CompShop/CompShop/Forms/Products/ProductSettingsForm.cs @@ -1,6 +1,9 @@ using CompShop.Entites; using CompShop.Entites.Enums; using CompShop.Repos; +using Microsoft.VisualBasic.FileIO; +using System; +using System.Windows.Forms; namespace CompShop { @@ -17,7 +20,7 @@ namespace CompShop try { var product = _productRepository.Read(value); - if (product != null) + if (product == null) { throw new InvalidDataException(nameof(product)); } @@ -31,6 +34,7 @@ namespace CompShop typeCheckedListBox.SetItemChecked(typeCheckedListBox.Items.IndexOf(elem), true); } } + //typeCombobox.SelectedItem = product.ProductType; priceNumeric.Value = product.Price; _productId = value; } @@ -53,6 +57,8 @@ namespace CompShop typeCheckedListBox.Items.Add(elem); } + //typeCombobox.DataSource = Enum.GetValues(typeof(ProductType)); + } private void ProductSettingsForm_Load(object sender, EventArgs e) diff --git a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs index 5a3fe52..1a7406a 100644 --- a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs +++ b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.Designer.cs @@ -56,15 +56,15 @@ productsDataGridView.Size = new Size(851, 400); productsDataGridView.TabIndex = 8; // - // editButton + // deleteButton // editButton.Location = new Point(881, 78); editButton.Name = "editButton"; editButton.Size = new Size(161, 60); editButton.TabIndex = 10; - editButton.Text = "Редактировать"; + editButton.Text = "Удалить"; editButton.UseVisualStyleBackColor = true; - editButton.Click += editButton_Click; + editButton.Click += deleteButton_Click; // // ProductsOnStorageForm // diff --git a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.cs b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.cs index 4282b98..44474df 100644 --- a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.cs +++ b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageForm.cs @@ -1,4 +1,13 @@ using CompShop.Repos; +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; using Unity; namespace CompShop.Forms.ProductsOnStorage @@ -56,25 +65,27 @@ namespace CompShop.Forms.ProductsOnStorage } } - private void editButton_Click(object sender, EventArgs e) + private void deleteButton_Click(object sender, EventArgs e) { if (!TryGetIdentifierFromSelectedRow(out var findId)) { return; } + if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) + { + return; + } + try { - var form = _container.Resolve(); - form.Id = findId; - form.ShowDialog(); + _productOnStorageRepository.Delete(findId); LoadList(); } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - } } diff --git a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs index 22a3f16..9311c3c 100644 --- a/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs +++ b/CompShop/CompShop/Forms/ProductsOnStorage/ProductsOnStorageSettingsForm.cs @@ -1,5 +1,14 @@ using CompShop.Entites; using CompShop.Repos; +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 CompShop.Forms.ProductsOnStorage { @@ -22,9 +31,22 @@ namespace CompShop.Forms.ProductsOnStorage { throw new InvalidDataException("Record not found"); } - - productCombobox.SelectedItem = record.Product; - storageCombobox.SelectedItem = record.Storage; + //ProductComboBox + foreach (var item in _productRepository.ReadAll()) + { + if (item.ID == record.ProductId) + { + productCombobox.SelectedItem = item; + } + } + //StorageCombobox + foreach (var item in _storageRepository.ReadAll()) + { + if (item.Id == record.StorageId) + { + storageCombobox.SelectedItem = item; + } + } countNumeric.Value = record.Count; _recordId = value; } @@ -59,7 +81,7 @@ namespace CompShop.Forms.ProductsOnStorage productCombobox.ValueMember = "Id"; storageCombobox.DataSource = _storageRepository.ReadAll().ToList(); - storageCombobox.DisplayMember = "Name"; + storageCombobox.DisplayMember = "Adress"; storageCombobox.ValueMember = "Id"; } @@ -67,7 +89,7 @@ namespace CompShop.Forms.ProductsOnStorage { try { - if (productCombobox.SelectedItem == null || storageCombobox.SelectedItem == null || countNumeric.Value < 1) + if (productCombobox.SelectedItem == null || storageCombobox.SelectedItem == null) { throw new Exception("Заполните все поля"); } @@ -76,14 +98,8 @@ namespace CompShop.Forms.ProductsOnStorage var selectedStorage = (Entites.Storage)storageCombobox.SelectedItem; var count = (int)countNumeric.Value; - if (_recordId.HasValue) - { - _productOnStorageRepository.Update(CreateProductOnStorage(_recordId.Value, selectedProduct, selectedStorage, count)); - } - else - { - _productOnStorageRepository.Create(CreateProductOnStorage(0, selectedProduct, selectedStorage, count)); - } + _productOnStorageRepository.Create(CreateProductOnStorage(0, selectedProduct, selectedStorage, count)); + Close(); } @@ -98,4 +114,4 @@ namespace CompShop.Forms.ProductsOnStorage return Entites.ProductsOnStorage.CreateEntity(id, product, storage, count); } } -} +} \ No newline at end of file diff --git a/CompShop/CompShop/Forms/Receipt/CheckForm.cs b/CompShop/CompShop/Forms/Receipt/CheckForm.cs index 15f642e..85639e4 100644 --- a/CompShop/CompShop/Forms/Receipt/CheckForm.cs +++ b/CompShop/CompShop/Forms/Receipt/CheckForm.cs @@ -1,4 +1,13 @@ using CompShop.Repos; +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; using Unity; namespace CompShop.Forms.Receipt diff --git a/CompShop/CompShop/Forms/Receipt/CheckSettingsForm .cs b/CompShop/CompShop/Forms/Receipt/CheckSettingsForm .cs index 23e6dbf..f1cee71 100644 --- a/CompShop/CompShop/Forms/Receipt/CheckSettingsForm .cs +++ b/CompShop/CompShop/Forms/Receipt/CheckSettingsForm .cs @@ -1,5 +1,15 @@ using CompShop.Entites; +using CompShop.Entites.Enums; using CompShop.Repos; +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 CompShop.Forms.Receipt { @@ -59,7 +69,7 @@ namespace CompShop.Forms.Receipt var list = new List(); foreach (DataGridViewRow row in productsDataGridView.Rows) { - if (row.Cells["ProductColoumn"].Value == null || row.Cells["ColumnCount"].Value == null) + if (row.Cells["ProductColoumn"].Value == null || row.Cells["ProductCount"].Value == null) { continue; } diff --git a/CompShop/CompShop/Forms/Storage/StorageForm.cs b/CompShop/CompShop/Forms/Storage/StorageForm.cs index cdd946a..471aa66 100644 --- a/CompShop/CompShop/Forms/Storage/StorageForm.cs +++ b/CompShop/CompShop/Forms/Storage/StorageForm.cs @@ -1,5 +1,14 @@ - +using CompShop.Forms.Clients; using CompShop.Repos; +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; using Unity; namespace CompShop.Forms.Storage diff --git a/CompShop/CompShop/Forms/Storage/StorageSettingsForm.cs b/CompShop/CompShop/Forms/Storage/StorageSettingsForm.cs index 0aa863f..1732729 100644 --- a/CompShop/CompShop/Forms/Storage/StorageSettingsForm.cs +++ b/CompShop/CompShop/Forms/Storage/StorageSettingsForm.cs @@ -1,5 +1,15 @@ -using CompShop.Repos; - +using CompShop.Entites.Enums; +using CompShop.Entites; +using CompShop.Repos; +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 CompShop.Forms.Storage { @@ -16,7 +26,7 @@ namespace CompShop.Forms.Storage try { var storage = _repository.Read(value); - if (storage != null) + if (storage == null) { throw new InvalidDataException(nameof(storage)); } @@ -61,7 +71,7 @@ namespace CompShop.Forms.Storage else { - _repository.Update(CreateStorage(0)); + _repository.Create(CreateStorage(0)); } Close(); diff --git a/CompShop/CompShop/Program.cs b/CompShop/CompShop/Program.cs index 22edc1e..6600383 100644 --- a/CompShop/CompShop/Program.cs +++ b/CompShop/CompShop/Program.cs @@ -1,7 +1,11 @@ using CompShop.Repos; using CompShop.Repos.Impements; +using Microsoft.Extensions.Logging; using Unity; using Unity.Lifetime; +using Serilog; +using Microsoft.Extensions.Configuration; + namespace CompShop { @@ -20,13 +24,28 @@ namespace CompShop { var container = new UnityContainer(); + container.RegisterInstance(CreateLoggerFactory()); + + container.RegisterType(new SingletonLifetimeManager()); 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/CompShop/CompShop/Repos/IConnectionString.cs b/CompShop/CompShop/Repos/IConnectionString.cs new file mode 100644 index 0000000..78bfc08 --- /dev/null +++ b/CompShop/CompShop/Repos/IConnectionString.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Repos +{ + public interface IConnectionString + { + string ConnectionString { get; } + } +} diff --git a/CompShop/CompShop/Repos/IProductInCheckRepositoty.cs b/CompShop/CompShop/Repos/IProductInCheckRepositoty.cs new file mode 100644 index 0000000..aea0369 --- /dev/null +++ b/CompShop/CompShop/Repos/IProductInCheckRepositoty.cs @@ -0,0 +1,16 @@ +using CompShop.Entites; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Repos +{ + public interface IProductInCheckRepository + { + IEnumerable ReadAll(); + ProductInCheck Read(int id); + void Create(ProductInCheck ps); + } +} diff --git a/CompShop/CompShop/Repos/IProductOnStorageRepository.cs b/CompShop/CompShop/Repos/IProductOnStorageRepository.cs index 138e378..3f36270 100644 --- a/CompShop/CompShop/Repos/IProductOnStorageRepository.cs +++ b/CompShop/CompShop/Repos/IProductOnStorageRepository.cs @@ -6,6 +6,6 @@ namespace CompShop.Repos IEnumerable ReadAll(); ProductsOnStorage Read(int id); void Create(ProductsOnStorage ps); - ProductsOnStorage Update(ProductsOnStorage storage); + void Delete(int id); } -} +} \ No newline at end of file diff --git a/CompShop/CompShop/Repos/Impements/CheckRepo.cs b/CompShop/CompShop/Repos/Impements/CheckRepo.cs index 912f9f4..48c2cc6 100644 --- a/CompShop/CompShop/Repos/Impements/CheckRepo.cs +++ b/CompShop/CompShop/Repos/Impements/CheckRepo.cs @@ -1,23 +1,122 @@ using CompShop.Entites; +using Dapper; +using Microsoft.Extensions.Logging; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; namespace CompShop.Repos.Impements { public class CheckRepo : ICheckRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + private readonly IClientRepository _clientRepository; + + public CheckRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IClientRepository clientRepository) + { + _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); + _logger = loggerFactory.CreateLogger(); + _clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository)); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); public void Create(Check check) { + _logger.LogInformation("Создание чека"); + using (var connection = CreateConnection()) + { + connection.Open(); + using (var transaction = connection.BeginTransaction()) + { + try + { + var checkSql = "INSERT INTO \"Checks\" (\"ClientId\", \"PurchaseDate\") VALUES (@ClientId, @PurchaseDate) RETURNING \"Id\""; + check.Id = connection.ExecuteScalar(checkSql, new + { + ClientId = check.Client.Id, + PurchaseDate = check.PurchaseDate + }, transaction); + var productSql = "INSERT INTO \"ProductsInCheck\" (\"CheckId\", \"ProductID\", \"Count\") VALUES (@CheckId, @ProductID, @Count)"; + foreach (var productInCheck in check.Products) + { + connection.Execute(productSql, new + { + CheckId = check.Id, + ProductID = productInCheck.ProductID, + Count = productInCheck.Count + }, transaction); + } + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + _logger.LogError(ex, "Ошибка при создании чека"); + throw; + } + } + } } public Check Read(int id) { - return Check.CreateEntity(0, new List(), new Client(), DateTime.Now); + _logger.LogInformation("Чтение чека по ID: {id}", id); + using (var connection = CreateConnection()) + { + try + { + var checkSql = "SELECT * FROM \"Checks\" WHERE \"Id\" = @Id"; + var check = connection.QuerySingleOrDefault(checkSql, new { Id = id }); + + if (check == null) return null; + + check.Client = _clientRepository.Read(check.Client.Id); + + var productSql = "SELECT * FROM \"ProductsInCheck\" WHERE \"CheckId\" = @CheckId"; + check.Products = connection.Query(productSql, new { CheckId = check.Id }).ToList(); + + return check; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении чека"); + throw; + } + } } public IEnumerable ReadAll() { - return new List(); + _logger.LogInformation("Чтение всех чеков"); + using (var connection = CreateConnection()) + { + try + { + var checksSql = "SELECT * FROM \"Checks\""; + var checks = connection.Query(checksSql).ToList(); + + foreach (var check in checks) + { + check.Client = _clientRepository.Read(check.ClientId); + + var productSql = "SELECT * FROM \"ProductsInCheck\" WHERE \"CheckId\" = @CheckId"; + check.Products = connection.Query(productSql, new { CheckId = check.Id }).ToList(); + } + + return checks; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении всех чеков"); + throw; + } + } } } } diff --git a/CompShop/CompShop/Repos/Impements/ClientRepo.cs b/CompShop/CompShop/Repos/Impements/ClientRepo.cs index e9afa95..c6f8c5d 100644 --- a/CompShop/CompShop/Repos/Impements/ClientRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ClientRepo.cs @@ -1,33 +1,142 @@ using CompShop.Entites; using CompShop.Entites.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; namespace CompShop.Repos.Impements { public class ClientRepo : IClientRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ClientRepo(IConnectionString connectionString, ILoggerFactory loggerFactory) + { + _connectionString = connectionString; + _logger = loggerFactory.CreateLogger(); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); + public void Create(Client client) { + _logger.LogInformation("Добавление клиента"); + _logger.LogDebug("Клиент: {json}", JsonConvert.SerializeObject(client)); + try + { + using (var connection = CreateConnection()) + { + var sql = "INSERT INTO \"Clients\" (\"Name\", \"PhoneNumber\", \"ClientType\") " + + "VALUES (@Name, @PhoneNumber, @ClientType)"; + + connection.Execute(sql, new + { + Name = client.Name, + PhoneNumber = client.PhoneNumber, + ClientType = (int)client.ClientType + }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении клиента"); + throw; + } } public void Delete(int id) { + _logger.LogInformation("Удаление клиента"); + _logger.LogDebug("Клиент ID: {id}", id); + try + { + using (var connection = CreateConnection()) + { + var sql = "DELETE FROM \"Clients\" WHERE \"Id\" = @Id"; + connection.Execute(sql, new { Id = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении клиента"); + throw; + } } public Client Read(int id) { - return Client.CreateEntity(0, string.Empty, string.Empty, ClientType.Individual); + _logger.LogInformation("Получение клиента по ID"); + _logger.LogDebug("Клиент ID: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = "SELECT * FROM \"Clients\" WHERE \"Id\" = @Id"; + return connection.QuerySingleOrDefault(sql, new { Id = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении клиента"); + throw; + } } public IEnumerable ReadAll() { - return new List(); + _logger.LogInformation("Получение всех клиентов"); + + try + { + using (var connection = CreateConnection()) + { + var sql = "SELECT * FROM \"Clients\""; + return connection.Query(sql); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении списка клиентов"); + throw; + } } public Client Update(Client client) { - return Client.CreateEntity(0, string.Empty, string.Empty, ClientType.Individual); + _logger.LogInformation("Обновление информации о клиенте"); + _logger.LogDebug("Клиент: {json}", JsonConvert.SerializeObject(client)); + + try + { + using (var connection = CreateConnection()) + { + var sql = "UPDATE \"Clients\" SET \"Name\" = @Name, \"PhoneNumber\" = @PhoneNumber, \"ClientType\" = @ClientType " + + "WHERE \"Id\" = @Id"; + + connection.Execute(sql, new + { + Id = client.Id, + Name = client.Name, + PhoneNumber = client.PhoneNumber, + ClientType = (int)client.ClientType + }); + + return client; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при обновлении информации о клиенте"); + throw; + } } } } diff --git a/CompShop/CompShop/Repos/Impements/ConnectionString.cs b/CompShop/CompShop/Repos/Impements/ConnectionString.cs new file mode 100644 index 0000000..07609d5 --- /dev/null +++ b/CompShop/CompShop/Repos/Impements/ConnectionString.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CompShop.Repos; + +namespace CompShop.Repos.Impements +{ + public class ConnectionString : IConnectionString + { + string IConnectionString.ConnectionString => "Host=localhost;Username=postgres;Password=Password;Database=CompShopDB"; + } +} diff --git a/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs b/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs new file mode 100644 index 0000000..24a258a --- /dev/null +++ b/CompShop/CompShop/Repos/Impements/ProductInCheckRepo.cs @@ -0,0 +1,135 @@ +using CompShop.Entites; +using Dapper; +using Microsoft.Extensions.Logging; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CompShop.Repos.Impements +{ + public class ProductInCheckRepo : IProductInCheckRepository + { + private readonly IProductRepository _productRepository; + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ProductInCheckRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IProductRepository productRepository) + { + _connectionString = connectionString; + _logger = loggerFactory.CreateLogger(); + _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); + + public void Create(ProductInCheck productInCheck) + { + _logger.LogInformation("Добавление товара в чек"); + _logger.LogDebug("Товар в чеке: {json}", Newtonsoft.Json.JsonConvert.SerializeObject(productInCheck)); + + using (var connection = CreateConnection()) + { + connection.Open(); + using (var transaction = connection.BeginTransaction()) + { + try + { + var sql = "INSERT INTO \"ProductsInCheck\" (\"ProductID\", \"Count\") " + + "VALUES (@ProductID, @Count) RETURNING \"ID\""; + + productInCheck.ID = connection.ExecuteScalar(sql, new + { + ProductID = productInCheck.ProductID, + Count = productInCheck.Count + }, transaction); + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + _logger.LogError(ex, "Ошибка при добавлении товара в чек"); + throw; + } + } + } + } + + public ProductInCheck Read(int id) + { + _logger.LogInformation("Получение товара в чеке по ID"); + _logger.LogDebug("ID товара в чеке: {id}", id); + + using (var connection = CreateConnection()) + { + try + { + var sql = "SELECT * FROM \"ProductsInCheck\" WHERE \"ID\" = @ID"; + var productInCheck = connection.QuerySingleOrDefault(sql, new { ID = id }); + if (productInCheck != null) + { + // Загрузка дополнительной информации о продукте при необходимости + var product = _productRepository.Read(productInCheck.ProductID); + productInCheck.ProductID = product?.ID ?? 0; + } + return productInCheck; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении товара в чеке"); + throw; + } + } + } + + public IEnumerable ReadAll() + { + _logger.LogInformation("Получение всех товаров в чеках"); + + using (var connection = CreateConnection()) + { + try + { + var sql = "SELECT * FROM \"ProductsInCheck\""; + var productsInCheck = connection.Query(sql).ToList(); + + foreach (var productInCheck in productsInCheck) + { + var product = _productRepository.Read(productInCheck.ProductID); + productInCheck.ProductID = product?.ID ?? 0; + } + return productsInCheck; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении списка товаров в чеках"); + throw; + } + } + } + + public void Delete(int id) + { + _logger.LogInformation("Удаление товара из чека"); + _logger.LogDebug("ID товара в чеке: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = "DELETE FROM \"ProductsInCheck\" WHERE \"ID\" = @ID"; + connection.Execute(sql, new { ID = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении товара из чека"); + throw; + } + } + } +} \ No newline at end of file diff --git a/CompShop/CompShop/Repos/Impements/ProductRepo.cs b/CompShop/CompShop/Repos/Impements/ProductRepo.cs index f8e2d59..b5fef52 100644 --- a/CompShop/CompShop/Repos/Impements/ProductRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ProductRepo.cs @@ -1,33 +1,151 @@ using CompShop.Entites; using CompShop.Entites.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using System.Data; +using System.Linq.Expressions; namespace CompShop.Repos.Impements { public class ProductRepo : IProductRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory) + { + _connectionString = connectionString; + //_logger = logger; + _logger = loggerFactory.CreateLogger(); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); + public void Create(Product product) { - + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + + try + { + using (var connection = CreateConnection()) + { + var sql = "INSERT INTO \"Products\" (\"Name\", \"Description\", \"Price\", \"ProductType\") " + + "VALUES (@Name, @Description, @Price, @ProductType)"; + + connection.Execute(sql, new + { + Name = product.Name, + Description = product.Description, + Price = product.Price, + ProductType = (int)product.ProductType + }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void Delete(int id) { - + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = "DELETE FROM \"Products\" WHERE \"Id\" = @Id"; + connection.Execute(sql, new { Id = id }); + } + } + catch (Exception e) + { + _logger.LogError(e, "Ошибка при удалении объекта"); + throw; + } } public Product Read(int id) { - return Product.CreateEntity(0, string.Empty, string.Empty, 0, ProductType.None); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = $"SELECT * FROM \"Products\" WHERE \"Id\" = {id}"; + return connection.QuerySingleOrDefault(sql); + } + } + catch (Exception e) + { + _logger.LogError(e, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadAll() { - return new List(); + _logger.LogInformation("Получение всех объектов"); + + try + { + using (var connection = CreateConnection()) + { + var sql = "SELECT * FROM \"Products\""; + return connection.Query(sql).ToList(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } + } public Product Update(Product product) { - return Product.CreateEntity(0, string.Empty, string.Empty, 0, ProductType.None); + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product)); + + try + { + using (var connection = CreateConnection()) + { + var sql = "UPDATE \"Products\" " + + "SET \"Name\" = @Name, " + + "\"Description\" = @Description, " + + "\"Price\" = @Price," + + "\"ProductType\" = @ProductType" + + " WHERE \"Id\" = @Id"; + + connection.Execute(sql, new + { + Id = product.ID, + Name = product.Name, + Description = product.Description, + Price = product.Price, + ProductType = (int)product.ProductType + }); + + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при изменении объекта"); + throw; + } + return product; + } } } diff --git a/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs b/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs index 8fc5199..81138df 100644 --- a/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs +++ b/CompShop/CompShop/Repos/Impements/ProductsOnStorageRepo.cs @@ -1,27 +1,137 @@ using CompShop.Entites; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; namespace CompShop.Repos.Impements { public class ProductsOnStorageRepo : IProductOnStorageRepository { - public void Create(ProductsOnStorage ps) + private readonly IProductRepository _productRepository; + private readonly IStorageRepository _storageRepository; + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ProductsOnStorageRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, + IProductRepository productRepository, + IStorageRepository storageRepository) { - + _connectionString = connectionString; + _logger = loggerFactory.CreateLogger(); + _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository)); + _storageRepository = storageRepository ?? throw new ArgumentNullException(nameof(storageRepository)); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); + + public void Create(ProductsOnStorage productsOnStorage) + { + _logger.LogInformation("Добавление продукта на склад"); + _logger.LogDebug("Продукт на складе: {json}", JsonConvert.SerializeObject(productsOnStorage)); + + using (var connection = CreateConnection()) + { + connection.Open(); + using (var transaction = connection.BeginTransaction()) + { + try + { + var sql = "INSERT INTO \"ProductsOnStorage\" (\"ProductId\", \"StorageId\", \"Count\") " + + "VALUES (@ProductId, @StorageId, @Count) RETURNING \"Id\""; + + productsOnStorage.Id = connection.ExecuteScalar(sql, new + { + ProductId = productsOnStorage.Product.ID, + StorageId = productsOnStorage.Storage.Id, + Count = productsOnStorage.Count + }, transaction); + + transaction.Commit(); + } + catch (Exception ex) + { + transaction.Rollback(); + _logger.LogError(ex, "Ошибка при добавлении продукта на склад"); + throw; + } + } + } } public ProductsOnStorage Read(int id) { - return ProductsOnStorage.CreateEntity(0, new Product(), new Storage(), 0); + _logger.LogInformation("Получение продукта на складе по ID"); + _logger.LogDebug("ID продукта на складе: {id}", id); + + using (var connection = CreateConnection()) + { + try + { + var sql = "SELECT * FROM \"ProductsOnStorage\" WHERE \"Id\" = @Id"; + var productOnStorage = connection.QuerySingleOrDefault(sql, new { Id = id }); + productOnStorage.Storage = _storageRepository.Read(productOnStorage.StorageId); + productOnStorage.Product = _productRepository.Read(productOnStorage.ProductId); + + return productOnStorage; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении продукта на складе"); + throw; + } + } } public IEnumerable ReadAll() { - return new List(); + _logger.LogInformation("Получение всех продуктов на складе"); + + using (var connection = CreateConnection()) + { + try + { + var sql = "SELECT * FROM \"ProductsOnStorage\""; + var answer = connection.Query(sql).ToList(); + foreach (var productOnStorage in answer) + { + productOnStorage.Product = _productRepository.Read(productOnStorage.ProductId); + productOnStorage.Storage = _storageRepository.Read(productOnStorage.StorageId); + } + return answer; + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении списка продуктов на складе"); + throw; + } + } } - public ProductsOnStorage Update(ProductsOnStorage storage) + public void Delete(int id) { - return ProductsOnStorage.CreateEntity(0, new Product(), new Storage(), 0); + _logger.LogInformation("Удаление товара со склада"); + _logger.LogDebug("Склад ID: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = "DELETE FROM \"ProductsOnStorage\" WHERE \"Id\" = @Id"; + connection.Execute(sql, new { Id = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении"); + throw; + } } } } + diff --git a/CompShop/CompShop/Repos/Impements/StorageRepo.cs b/CompShop/CompShop/Repos/Impements/StorageRepo.cs index 08a565d..944abe2 100644 --- a/CompShop/CompShop/Repos/Impements/StorageRepo.cs +++ b/CompShop/CompShop/Repos/Impements/StorageRepo.cs @@ -1,32 +1,140 @@ using CompShop.Entites; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; namespace CompShop.Repos.Impements { - public class StorageRepo: IStorageRepository + public class StorageRepo : IStorageRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public StorageRepo(IConnectionString connectionString, ILoggerFactory loggerFactory) + { + _connectionString = connectionString; + _logger = loggerFactory.CreateLogger(); + } + + private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString); + public void Create(Storage storage) { + _logger.LogInformation("Добавление склада"); + _logger.LogDebug("Склад: {json}", JsonConvert.SerializeObject(storage)); + try + { + using (var connection = CreateConnection()) + { + var sql = "INSERT INTO \"Storages\" (\"Size\", \"Adress\") " + + "VALUES (@Size, @Adress)"; + + connection.Execute(sql, new + { + Size = storage.Size, + Adress = storage.Adress + }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении склада"); + throw; + } } public void Delete(int id) { + _logger.LogInformation("Удаление склада"); + _logger.LogDebug("Склад ID: {id}", id); + try + { + using (var connection = CreateConnection()) + { + var sql = "DELETE FROM \"Storages\" WHERE \"Id\" = @Id"; + connection.Execute(sql, new { Id = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении склада"); + throw; + } } public Storage Read(int id) { - return Storage.CreateEntity(0, 0, string.Empty); + _logger.LogInformation("Получение склада по ID"); + _logger.LogDebug("Склад ID: {id}", id); + + try + { + using (var connection = CreateConnection()) + { + var sql = "SELECT * FROM \"Storages\" WHERE \"Id\" = @Id"; + return connection.QuerySingleOrDefault(sql, new { Id = id }); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении склада"); + throw; + } } public IEnumerable ReadAll() { - return new List(); + _logger.LogInformation("Получение всех складов"); + + try + { + using (var connection = CreateConnection()) + { + var sql = "SELECT * FROM \"Storages\""; + return connection.Query(sql).ToList(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении списка складов"); + throw; + } } public Storage Update(Storage storage) { - return Storage.CreateEntity(0, 0, string.Empty); + _logger.LogInformation("Обновление информации о складе"); + _logger.LogDebug("Склад: {json}", JsonConvert.SerializeObject(storage)); + + try + { + using (var connection = CreateConnection()) + { + var sql = "UPDATE \"Storages\" SET \"Size\" = @Size, \"Adress\" = @Adress " + + "WHERE \"Id\" = @Id"; + + connection.Execute(sql, new + { + Id = storage.Id, + Size = storage.Size, + Adress = storage.Adress + }); + + return storage; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при обновлении информации о складе"); + throw; + } } } -} +} \ No newline at end of file diff --git a/README.md b/CompShop/README.md similarity index 100% rename from README.md rename to CompShop/README.md