Лабораторная работа 2

This commit is contained in:
Есения Андрианова 2024-12-15 10:13:09 +04:00
parent a785f75585
commit a4be7708ad
34 changed files with 999 additions and 67 deletions

View File

@ -0,0 +1,7 @@
{
"ExpandedNodes": [
""
],
"SelectedNode": "\\C:\\Users\\79061\\Desktop\\dddddddddddddddddd",
"PreviewInSolutionExplorer": false
}

Binary file not shown.

View File

@ -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}"
}
]
}
]
}
]
}

View File

View File

@ -9,6 +9,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="6.0.12" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Unity" Version="5.11.10" />
</ItemGroup>

View File

@ -1,10 +1,15 @@
namespace CompShop.Entites
using CompShop.Entites;
namespace CompShop.Entites
{
public class Check
{
public int Id { get; set; }
public List<ProductInCheck> 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<ProductInCheck> products, Client client, DateTime purchaseDate)

View File

@ -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;
}
}
}

View File

@ -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;
}
}
}

View File

@ -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 };
}
}
}

View File

@ -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 };
}
}
}

View File

@ -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;
}
}
}

View File

@ -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

View File

@ -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();

View File

@ -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

View File

@ -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)

View File

@ -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
//

View File

@ -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<ProductsOnStorageSettingsForm>();
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);
}
}
}
}

View File

@ -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));
}
Close();
}

View File

@ -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

View File

@ -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<ProductInCheck>();
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;
}

View File

@ -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

View File

@ -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();

View File

@ -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<ILoggerFactory>(CreateLoggerFactory());
container.RegisterType<IConnectionString, ConnectionString>(new SingletonLifetimeManager());
container.RegisterType<IProductRepository, ProductRepo>(new TransientLifetimeManager());
container.RegisterType<IClientRepository, ClientRepo>(new TransientLifetimeManager());
container.RegisterType<IStorageRepository, StorageRepo>(new TransientLifetimeManager());
container.RegisterType<IProductOnStorageRepository, ProductsOnStorageRepo>(new TransientLifetimeManager());
container.RegisterType<IProductInCheckRepository, ProductInCheckRepo>(new TransientLifetimeManager());
container.RegisterType<ICheckRepository, CheckRepo>(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;
}
}
}

View File

@ -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; }
}
}

View File

@ -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<ProductInCheck> ReadAll();
ProductInCheck Read(int id);
void Create(ProductInCheck ps);
}
}

View File

@ -6,6 +6,6 @@ namespace CompShop.Repos
IEnumerable<ProductsOnStorage> ReadAll();
ProductsOnStorage Read(int id);
void Create(ProductsOnStorage ps);
ProductsOnStorage Update(ProductsOnStorage storage);
void Delete(int id);
}
}

View File

@ -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<CheckRepo> _logger;
private readonly IClientRepository _clientRepository;
public CheckRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IClientRepository clientRepository)
{
_connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
_logger = loggerFactory.CreateLogger<CheckRepo>();
_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<int>(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<ProductInCheck>(), 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<Check>(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<ProductInCheck>(productSql, new { CheckId = check.Id }).ToList();
return check;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении чека");
throw;
}
}
}
public IEnumerable<Check> ReadAll()
{
return new List<Check>();
_logger.LogInformation("Чтение всех чеков");
using (var connection = CreateConnection())
{
try
{
var checksSql = "SELECT * FROM \"Checks\"";
var checks = connection.Query<Check>(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<ProductInCheck>(productSql, new { CheckId = check.Id }).ToList();
}
return checks;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении всех чеков");
throw;
}
}
}
}
}

View File

@ -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<ClientRepo> _logger;
public ClientRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ClientRepo>();
}
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<Client>(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении клиента");
throw;
}
}
public IEnumerable<Client> ReadAll()
{
return new List<Client>();
_logger.LogInformation("Получение всех клиентов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"Clients\"";
return connection.Query<Client>(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;
}
}
}
}

View File

@ -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";
}
}

View File

@ -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<ProductInCheckRepo> _logger;
public ProductInCheckRepo(IConnectionString connectionString, ILoggerFactory loggerFactory, IProductRepository productRepository)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ProductInCheckRepo>();
_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<int>(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<ProductInCheck>(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<ProductInCheck> ReadAll()
{
_logger.LogInformation("Получение всех товаров в чеках");
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"ProductsInCheck\"";
var productsInCheck = connection.Query<ProductInCheck>(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;
}
}
}
}

View File

@ -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<ProductRepo> _logger;
public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
//_logger = logger;
_logger = loggerFactory.CreateLogger<ProductRepo>();
}
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<Product>(sql);
}
}
catch (Exception e)
{
_logger.LogError(e, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> ReadAll()
{
return new List<Product>();
_logger.LogInformation("Получение всех объектов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"Products\"";
return connection.Query<Product>(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;
}
}
}

View File

@ -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<ProductsOnStorageRepo> _logger;
public ProductsOnStorageRepo(IConnectionString connectionString, ILoggerFactory loggerFactory,
IProductRepository productRepository,
IStorageRepository storageRepository)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<ProductsOnStorageRepo>();
_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<int>(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<ProductsOnStorage>(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<ProductsOnStorage> ReadAll()
{
return new List<ProductsOnStorage>();
_logger.LogInformation("Получение всех продуктов на складе");
using (var connection = CreateConnection())
{
try
{
var sql = "SELECT * FROM \"ProductsOnStorage\"";
var answer = connection.Query<ProductsOnStorage>(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;
}
}
}
}

View File

@ -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
{
private readonly IConnectionString _connectionString;
private readonly ILogger<StorageRepo> _logger;
public StorageRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
_logger = loggerFactory.CreateLogger<StorageRepo>();
}
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<Storage>(sql, new { Id = id });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении склада");
throw;
}
}
public IEnumerable<Storage> ReadAll()
{
return new List<Storage>();
_logger.LogInformation("Получение всех складов");
try
{
using (var connection = CreateConnection())
{
var sql = "SELECT * FROM \"Storages\"";
return connection.Query<Storage>(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;
}
}
}
}