wip: lab2

This commit is contained in:
Pyro 2024-12-12 23:56:42 +04:00
parent 03dfb3fb18
commit b8d67df1b2
15 changed files with 729 additions and 99 deletions

View File

@ -0,0 +1,6 @@
namespace ProjectConfectionaryFactory.Repositories.Implementations;
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Username=postgres;Password=postgres;Database=confectioneryfactoryotp;";
}

View File

@ -5,10 +5,10 @@ public class Client
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Surname { get; private set; } = string.Empty;
public double Phone { get; private set; }
public string Phone { get; private set; }
public string Address { get; private set; } = string.Empty;
public static Client CreateEntity(int id, string name, string surname, double phone, string address)
public static Client CreateEntity(int id, string name, string surname, string phone, string address)
{
return new Client
{

View File

@ -4,10 +4,10 @@ public class Supplier
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public double Phone { get; private set; }
public string Phone { get; private set; }
public string Address { get; private set; } = string.Empty;
public static Supplier CreateEntity(int id, string name, double phone, string address)
public static Supplier CreateEntity(int id, string name, string phone, string address)
{
return new Supplier
{

View File

@ -1,5 +1,6 @@
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Repositories;
using System.Text.RegularExpressions;
namespace ProjectConfectioneryFactory.Forms
{
@ -40,7 +41,7 @@ namespace ProjectConfectioneryFactory.Forms
{
try
{
if (string.IsNullOrWhiteSpace(textBoxClientName.Text) || string.IsNullOrWhiteSpace(textBoxClientSurname.Text) || string.IsNullOrWhiteSpace(maskedTextBoxPhone.Text) || string.IsNullOrWhiteSpace(textBoxAddress.Text))
if (string.IsNullOrWhiteSpace(textBoxClientName.Text) || string.IsNullOrWhiteSpace(textBoxClientSurname.Text) || !maskedTextBoxPhone.MaskCompleted || string.IsNullOrWhiteSpace(textBoxAddress.Text))
{
throw new Exception("Имеются незаполненные поля");
}
@ -66,7 +67,7 @@ namespace ProjectConfectioneryFactory.Forms
id,
textBoxClientName.Text,
textBoxClientSurname.Text,
Double.Parse(maskedTextBoxPhone.Text),
maskedTextBoxPhone.Text,
textBoxAddress.Text);
}
}

View File

@ -74,14 +74,14 @@ namespace ProjectConfectioneryFactory.Forms
var list = new List<OrderProduct>();
foreach (DataGridViewRow row in dataGridViewProducts.Rows)
{
if (row.Cells["ColumnProductsName"].Value == null ||
row.Cells["ColumnProductCount"].Value == null)
if (row.Cells["ColumnComponent"].Value == null ||
row.Cells["ColumnWeight"].Value == null)
{
continue;
}
list.Add(OrderProduct.CreateEntity(0,
Convert.ToInt32(row.Cells["ColumnProductsName"].Value),
Convert.ToInt32(row.Cells["ColumnProductCount"].Value)));
Convert.ToInt32(row.Cells["ColumnComponent"].Value),
Convert.ToInt32(row.Cells["ColumnWeight"].Value)));
}
return list;
}

View File

@ -95,7 +95,7 @@ namespace ProjectConfectioneryFactory.Forms
}
list.Add(ProductComponent.CreateEntity(0,
Convert.ToInt32(row.Cells["ColumnComponent"].Value),
Convert.ToInt32(row.Cells["ColumnWeight"].Value)));
Convert.ToDouble(row.Cells["ColumnWeight"].Value)));
}
return list;
}

View File

@ -39,7 +39,7 @@ namespace ProjectConfectioneryFactory.Forms
{
try
{
if (string.IsNullOrWhiteSpace(textBoxSupplierName.Text) || string.IsNullOrWhiteSpace(maskedTextBoxPhone.Text) || string.IsNullOrWhiteSpace(textBoxAddress.Text))
if (string.IsNullOrWhiteSpace(textBoxSupplierName.Text) || !maskedTextBoxPhone.MaskCompleted || string.IsNullOrWhiteSpace(textBoxAddress.Text))
{
throw new Exception("Имеются незаполненные поля");
}
@ -64,7 +64,7 @@ namespace ProjectConfectioneryFactory.Forms
private Supplier CreateSupplier(int id) => Supplier.CreateEntity(
id,
textBoxSupplierName.Text,
Double.Parse(maskedTextBoxPhone.Text),
maskedTextBoxPhone.Text,
textBoxAddress.Text);
}
}

View File

@ -14,6 +14,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="Serilog" Version="4.0.2" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />

View File

@ -1,28 +1,124 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class ClientRepository : IClientRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepository> _logger;
public ClientRepository(IConnectionString connectionString, ILogger<ClientRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
}
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
public void DeleteClient(int id)
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Clients (Name, Surname, Phone, Address)
VALUES (@Name, @Surname, @Phone, @Address)";
connection.Execute(queryInsert, client);
}
public Client ReadClientById(int id)
catch (Exception ex)
{
return Client.CreateEntity(0, string.Empty, string.Empty, 0, string.Empty);
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
public IEnumerable<Client> ReadClients()
{
return [];
}
public void UpdateClient(Client client)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Clients
SET
Name=@Name,
Surname=@Surname,
Phone=@Phone,
Address=@Address
WHERE Id=@Id";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта"); throw;
}
}
public void DeleteClient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Clients
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Client ReadClientById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Clients
WHERE Id=@id";
var client = connection.QueryFirst<Client>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Client> ReadClients()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Clients";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,28 +1,123 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class ComponentRepository : IComponentRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ComponentRepository> _logger;
public ComponentRepository(IConnectionString connectionString, ILogger<ComponentRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateComponent(Component component)
{
}
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(component));
public void DeleteComponent(int id)
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Components (Name, Price, Weight)
VALUES (@Name, @Price, @Weight)";
connection.Execute(queryInsert, component);
}
public Component ReadComponentById(int id)
catch (Exception ex)
{
return Component.CreateEntity(0, string.Empty, 0, 0);
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
public IEnumerable<Component> ReadComponents()
{
return [];
}
public void UpdateComponent(Component component)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(component));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Components
SET
Name=@Name,
Price=@Price,
Weight=@Weight
WHERE Id=@Id";
connection.Execute(queryUpdate, component);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта"); throw;
}
}
public void DeleteComponent(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Components
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Component ReadComponentById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Components
WHERE Id=@id";
var component = connection.QueryFirst<Component>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(component));
return component;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Component> ReadComponents()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Components";
var components = connection.Query<Component>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(components));
return components;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,28 +1,149 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectConfectioneryFactory.Entities;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class OrderRepository : IOrderRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateOrder(Order order)
{
}
public void DeleteOrder(int id)
_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 (ClientId, Completed, Date)
VALUES (@ClientId, @Completed, @Date);
SELECT MAX(Id)
FROM Orders";
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
public Order ReadOrderById(int id)
var querySubInsert = @"
INSERT INTO OrderProducts (OrderId, ProductId, Count)
VALUES (@OrderId, @ProductId, @Count)";
foreach (var elem in order.OrderProducts)
{
return Order.CreateOperation(0, 0, false, null);
connection.Execute(querySubInsert, new { orderId, elem.ProductId, elem.Count }, transaction);
}
public IEnumerable<Order> ReadOrders()
transaction.Commit();
}
catch (Exception ex)
{
return [];
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateOrder(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 queryUpdate = @"
UPDATE Orders
SET
ClientId=@ClientId,
Completed=@Completed,
Date=@Date
WHERE Id=@Id";
var orderId = connection.QueryFirst<int>(queryUpdate, order, transaction);
var querySubUpdate = @"
UPDATE OrderProducts
SET
OrderId=@OrderId,
ProductId=@ProductId,
Count=@Count
WHERE Id=@Id";
foreach (var elem in order.OrderProducts)
{
connection.Execute(querySubUpdate, new { orderId, elem.ProductId, elem.Count }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteOrder(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Orders
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Order ReadOrderById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Orders
WHERE Id=@id";
var order = connection.QueryFirst<Order>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(order));
return order;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Order> ReadOrders()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Orders";
var orders = connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orders;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,29 +1,149 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using ProjectConfectioneryFactory.Entities.Enums;
using Npgsql;
using System.Transactions;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class ProductRepository : IProductRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ProductRepository> _logger;
public ProductRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateProduct(Product product)
{
}
public void DeleteProduct(int id)
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(product));
try
{
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Products (ConfectionaryType, Name, Price)
VALUES (@ConfectionaryType, @Name, @Price);
SELECT MAX(Id)
FROM Products;";
var productId = connection.QueryFirst<int>(queryInsert, product, transaction);
public Product ReadProductById(int id)
var querySubInsert = @"
INSERT INTO ProductComponents (ProductId, ComponentId, Weight)
VALUES (@ProductId, @ComponentId, @Weight)";
foreach (var elem in product.ProductComponents)
{
return Product.CreateEntity(0, ConfectioneryType.None, string.Empty, 0, null);
connection.Execute(querySubInsert, new { productId, elem.ComponentId, elem.Weight }, transaction);
}
public IEnumerable<Product> ReadProducts()
transaction.Commit();
}
catch (Exception ex)
{
return [];
_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);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryUpdate = @"
UPDATE Products
SET
сonfectionaryType=@сonfectionaryType,
Name=@Name,
Price=@Price
WHERE Id=@Id";
var productId = connection.QueryFirst<int>(queryUpdate, product, transaction);
var querySubUpdate = @"
UPDATE ProductComponents
SET
ProductId=@ProductId,
ComponentId=@ComponentId,
Weight=@Weight
WHERE Id=@Id";
foreach (var elem in product.ProductComponents)
{
connection.Execute(querySubUpdate, new { productId, elem.ComponentId, elem.Weight }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта"); throw;
}
}
public void DeleteProduct(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Products
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Product ReadProductById(int id)
{
_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<Product>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(product));
return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Product> ReadProducts()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Products";
var products = connection.Query<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return products;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,28 +1,122 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class SupplierRepository : ISupplierRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplierRepository> _logger;
public SupplierRepository(IConnectionString connectionString, ILogger<SupplierRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupplier(Supplier supplier)
{
}
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supplier));
public void DeleteSupplier(int id)
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Suppliers (Name, Phone, Address)
VALUES (@Name, @Phone, @Address)";
connection.Execute(queryInsert, supplier);
}
public Supplier ReadSupplierById(int id)
catch (Exception ex)
{
return Supplier.CreateEntity(0, string.Empty, 0, string.Empty);
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
public IEnumerable<Supplier> ReadSuppliers()
{
return [];
}
public void UpdateSupplier(Supplier supplier)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supplier));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Suppliers
SET
Name=@Name,
Phone=@Phone,
Address=@Address
WHERE Id=@Id";
connection.Execute(queryUpdate, supplier);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта"); throw;
}
}
public void DeleteSupplier(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Suppliers
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Supplier ReadSupplierById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Suppliers
WHERE Id=@id";
var supplier = connection.QueryFirst<Supplier>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(supplier));
return supplier;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Supplier> ReadSuppliers()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Suppliers";
var suppliers = connection.Query<Supplier>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(suppliers));
return suppliers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -1,28 +1,124 @@
using ProjectConfectioneryFactory.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using ProjectConfectioneryFactory.Entities;
using Npgsql;
namespace ProjectConfectioneryFactory.Repositories.Implementations;
public class SupplyRepository : ISupplyRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SupplyRepository> _logger;
public SupplyRepository(IConnectionString connectionString, ILogger<SupplyRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSupply(Supply supply)
{
}
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply));
public void DeleteSupply(int id)
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Supplys (SupplierId, ComponentId, Weight, Completed, Date)
VALUES (@SupplierId, @ComponentId, @Weight, @Completed, @Date)";
connection.Execute(queryInsert, supply);
}
public Supply ReadSupplyById(int id)
catch (Exception ex)
{
return Supply.CreateOperation(0, 0, 0, 0, false);
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
public IEnumerable<Supply> ReadSupplys()
{
return [];
}
public void UpdateSupply(Supply supply)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(supply));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Supplys
SET
SupplierId=@SupplierId,
ComponentId=@ComponentId,
Weight=@Weight,
Completed=@Completed,
Date=@Date
WHERE Id=@Id";
connection.Execute(queryUpdate, supply);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта"); throw;
}
}
public void DeleteSupply(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Supplys
WHERE Id=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта"); throw;
}
}
public Supply ReadSupplyById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT *
FROM Supplys
WHERE Id=@id";
var supply = connection.QueryFirst<Supply>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(supply));
return supply;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Supply> ReadSupplys()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Supplys";
var supplys = connection.Query<Supply>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(supplys));
return supplys;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}