diff --git a/ProjectGasStation/ProjectGasStation/Entities/FuelFuelSale.cs b/ProjectGasStation/ProjectGasStation/Entities/FuelFuelSale.cs index 5b51aaa..ed9cf35 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/FuelFuelSale.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/FuelFuelSale.cs @@ -5,9 +5,8 @@ public class FuelFuelSale public int Id { get; private set; } public int FuelId { get; private set; } public int Quantity { get; private set; } - public decimal Price { get; private set; } - public static FuelFuelSale CreateFuelFuelSale(int id, int fuelId, int quantity, decimal price) + public static FuelFuelSale CreateFuelFuelSale(int id, int fuelId, int quantity) { - return new FuelFuelSale { Id = id, FuelId = fuelId, Quantity = quantity, Price = price}; + return new FuelFuelSale { Id = id, FuelId = fuelId, Quantity = quantity}; } } diff --git a/ProjectGasStation/ProjectGasStation/Entities/FuelSale.cs b/ProjectGasStation/ProjectGasStation/Entities/FuelSale.cs index 195785d..3fd7734 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/FuelSale.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/FuelSale.cs @@ -6,10 +6,9 @@ public class FuelSale public int SalespersonId { get; private set; } public int ShiftId { get; private set; } public DateTime SaleDate { get; private set; } - public decimal TotalPrice { get; private set; } public IEnumerable FuelFuelSale { get; private set; } = []; - public static FuelSale CreateFuelSale(int id, int salesPersonId, int shiftId, DateTime saleDate, decimal totalPrice, IEnumerable fuelFuelSale) + public static FuelSale CreateFuelSale(int id, int salesPersonId, int shiftId, DateTime saleDate, IEnumerable fuelFuelSale) { return new FuelSale { @@ -17,7 +16,6 @@ public class FuelSale SalespersonId = salesPersonId, ShiftId = shiftId, SaleDate = saleDate, - TotalPrice = totalPrice, FuelFuelSale = fuelFuelSale }; } diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormFuelSale.cs b/ProjectGasStation/ProjectGasStation/Forms/FormFuelSale.cs index 4ec3105..2965436 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormFuelSale.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormFuelSale.cs @@ -1,6 +1,5 @@ using ProjectGasStation.Entities; using ProjectGasStation.Repositories; -using ProjectGasStation.Repositories.Implementations; namespace ProjectGasStation.Forms; @@ -37,7 +36,7 @@ public partial class FormFuelSale : Form throw new Exception("Имеются незаполненные поля"); } _fuelSaleRepository.CreateFuelSale(FuelSale.CreateFuelSale(0, - (int)comboBoxSalesperson.SelectedValue!, (int)comboBoxShift.SelectedValue!, dateTimePickerDate.Value, 0, CreateListFuelFuelSaleFromDataGrid())); + (int)comboBoxSalesperson.SelectedValue!, (int)comboBoxShift.SelectedValue!, dateTimePickerDate.Value, CreateListFuelFuelSaleFromDataGrid())); Close(); } catch (Exception ex) @@ -60,7 +59,7 @@ public partial class FormFuelSale : Form } list.Add(FuelFuelSale.CreateFuelFuelSale(0, Convert.ToInt32(row.Cells["ColumnFuel"].Value), - Convert.ToInt32(row.Cells["ColumnQuantity"].Value), 0)); + Convert.ToInt32(row.Cells["ColumnQuantity"].Value))); } return list; } diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormShift.cs b/ProjectGasStation/ProjectGasStation/Forms/FormShift.cs index 717c162..f560a90 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormShift.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormShift.cs @@ -68,5 +68,14 @@ public partial class FormShift : Form private void buttonCancel_Click(object sender, EventArgs e) => Close(); - private Shift CreateShift(int id) => Shift.CreateShift(id, dateTimePickerStart.Value.TimeOfDay, dateTimePickerEnd.Value.TimeOfDay, dateTimePickerDate.Value.Date, (ShiftType)comboBoxType.SelectedItem!); + private Shift CreateShift(int id) + { + var startTime = dateTimePickerStart.Value.TimeOfDay; + var endTime = dateTimePickerEnd.Value.TimeOfDay; + + var startTimeRounded = new TimeSpan(startTime.Hours, startTime.Minutes, startTime.Seconds); + var endTimeRounded = new TimeSpan(endTime.Hours, endTime.Minutes, endTime.Seconds); + + return Shift.CreateShift(id, startTimeRounded, endTimeRounded, dateTimePickerDate.Value.Date, (ShiftType)comboBoxType.SelectedItem!); + } } diff --git a/ProjectGasStation/ProjectGasStation/Program.cs b/ProjectGasStation/ProjectGasStation/Program.cs index d180d65..bf71f36 100644 --- a/ProjectGasStation/ProjectGasStation/Program.cs +++ b/ProjectGasStation/ProjectGasStation/Program.cs @@ -1,6 +1,10 @@ using Unity; using ProjectGasStation.Repositories; using ProjectGasStation.Repositories.Implementations; +using Unity.Microsoft.Logging; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; namespace ProjectGasStation { @@ -21,6 +25,7 @@ namespace ProjectGasStation private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(); container.RegisterType(); @@ -29,7 +34,21 @@ namespace ProjectGasStation container.RegisterType(); container.RegisterType(); + container.RegisterType(); + return container; } + private static LoggerFactory CreateLoggerFactory() + { + var loggerFactory = new LoggerFactory(); + loggerFactory.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile("appsettings.json") + .Build()) + .CreateLogger()); + return loggerFactory; + } + } } \ No newline at end of file diff --git a/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj b/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj index d842400..1d4831d 100644 --- a/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj +++ b/ProjectGasStation/ProjectGasStation/ProjectGasStation.csproj @@ -9,7 +9,19 @@ + + + + + + + + + + + + @@ -42,4 +54,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectGasStation/ProjectGasStation/Repositories/IConnectionString.cs b/ProjectGasStation/ProjectGasStation/Repositories/IConnectionString.cs new file mode 100644 index 0000000..781a4f9 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/Repositories/IConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGasStation.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConnectionString.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..4c6a27d --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,6 @@ +namespace ProjectGasStation.Repositories.Implementations; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=030405;Database=OTP"; +} diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorFuelRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorFuelRepository.cs index 622a5c1..21c1206 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorFuelRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorFuelRepository.cs @@ -1,20 +1,96 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class ContractorFuelRepository : IContractorFuelRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ContractorFuelRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateContractorFuel(ContractorFuel contractorFuel) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(contractorFuel)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO ContractorFuel (ContractorId, Date) + VALUES (@ContractorId, @Date); + SELECT MAX(Id) FROM ContractorFuel"; + var contractorFuelId = + connection.QueryFirst(queryInsert, contractorFuel, transaction); + var querySubInsert = @" + INSERT INTO ContractorFuelFuel (ContractorFuelId, FuelId, Quantity) + VALUES (@ContractorFuelId, @FuelId, @Quantity)"; + foreach (var elem in contractorFuel.ContractorFuelFuel) + { + connection.Execute(querySubInsert, new + { + contractorFuelId, + elem.FuelId, + elem.Quantity + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteContractorFuel(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM ContractorFuel + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public IEnumerable ReadContractorFuels(DateTime? dateFrom = null, DateTime? dateTo = null, int? contractorId = null, int? fuelId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM ContractorFuel"; + var contractorFuels = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(contractorFuels)); + return contractorFuels; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorRepository.cs index dad027e..b0e348d 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ContractorRepository.cs @@ -1,29 +1,122 @@ -using ProjectGasStation.Entities; -using ProjectGasStation.Entities.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class ContractorRepository : IContractorRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ContractorRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateContractor(Contractor contractor) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(contractor)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Contractor (Name, Types) + VALUES (@Name, @Types)"; + connection.Execute(queryInsert, contractor); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteContractor(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Contractor + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Contractor ReadContractorById(int id) { - return Contractor.CreateContractor(0, string.Empty, ContractorFuelType.Diesel); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Contractor + WHERE Id=@id"; + var contractor = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(contractor)); + return contractor; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadContractors() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Contractor"; + var contractors = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(contractors)); + return contractors; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateContractor(Contractor contractor) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(contractor)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Contractor + SET + Name=@Name, + Types=@Types + WHERE Id=@Id"; + connection.Execute(queryUpdate, contractor); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelRepository.cs index f0f84c8..d667e7d 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelRepository.cs @@ -1,29 +1,122 @@ -using ProjectGasStation.Entities; -using ProjectGasStation.Entities.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class FuelRepository : IFuelRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public FuelRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateFuel(Fuel fuel) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(fuel)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Fuel (Type, Price) + VALUES (@Type, @Price)"; + connection.Execute(queryInsert, fuel); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteFuel(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Fuel + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Fuel ReadFuelById(int id) { - return Fuel.CreateFuel(0, FuelType.Diesel, 1.10); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Fuel + WHERE Id=@id"; + var fuel = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(fuel)); + return fuel; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadFuels() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Fuel"; + var fuels = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(fuels)); + return fuels; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateFuel(Fuel fuel) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(fuel)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Fuel + SET + Type=@Type, + Price=@Price + WHERE Id=@Id"; + connection.Execute(queryUpdate, fuel); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelSaleRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelSaleRepository.cs index f4f2358..7d6b324 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelSaleRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/FuelSaleRepository.cs @@ -1,19 +1,95 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class FuelSaleRepository : IFuelSaleRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public FuelSaleRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateFuelSale(FuelSale fuel) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(fuel)); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" + INSERT INTO FuelSale (SalespersonId, ShiftId, SaleDate) + VALUES (@SalespersonId, @ShiftId, @SaleDate); + SELECT MAX(Id) FROM FuelSale"; + var fuelSaleId = + connection.QueryFirst(queryInsert, fuel, transaction); + var querySubInsert = @" + INSERT INTO FuelFuelSale (FuelSaleId, FuelId, Quantity) + VALUES (@FuelSaleId, @FuelId, @Quantity)"; + foreach (var elem in fuel.FuelFuelSale) + { + connection.Execute(querySubInsert, new + { + fuelSaleId, + elem.FuelId, + elem.Quantity + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public IEnumerable ReadFuelSales(DateTime? dateFrom = null, DateTime? dateTo = null, int? gasStationId = null, int? fuelId = null, int? salespersonId = null, int? shiftId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM FuelSale"; + var fuelSales = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(fuelSales)); + return fuelSales; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void DeleteFuelSale(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM FuelSale + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SalespersonRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SalespersonRepository.cs index 78e835b..388e7bb 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SalespersonRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SalespersonRepository.cs @@ -1,28 +1,122 @@ -using ProjectGasStation.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class SalespersonRepository : ISalespersonRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public SalespersonRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateSalesperson(Salesperson salesperson) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(salesperson)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Salesperson (FirstName, LastName) + VALUES (@FirstName, @LastName)"; + connection.Execute(queryInsert, salesperson); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteSalesperson(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Salesperson + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Salesperson ReadSalespersonById(int id) { - return Salesperson.CreateSalesperson(0, string.Empty, string.Empty); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Salesperson + WHERE Id=@id"; + var salesperson = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(salesperson)); + return salesperson; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadSalespersons() { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Salesperson"; + var salespersons = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(salespersons)); + return salespersons; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateSalesperson(Salesperson salesperson) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(salesperson)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Salesperson + SET + FirstName=@FirstName, + LastName=@LastName + WHERE Id=@Id"; + connection.Execute(queryUpdate, salesperson); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ShiftRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ShiftRepository.cs index 523f522..151bee1 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ShiftRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ShiftRepository.cs @@ -1,29 +1,124 @@ -using ProjectGasStation.Entities; -using ProjectGasStation.Entities.Enums; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGasStation.Entities; namespace ProjectGasStation.Repositories.Implementations; public class ShiftRepository : IShiftRepository { + private readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public ShiftRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateShift(Shift shift) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(shift)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" + INSERT INTO Shift (StartTime, EndTime, Date, Type) + VALUES (@StartTime, @EndTime, @Date, @Type)"; + connection.Execute(queryInsert, shift); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteShift(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM Shift + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } public Shift ReadShiftById(int id) { - return Shift.CreateShift(0, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0), DateTime.UtcNow, ShiftType.Night); + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" + SELECT * FROM Shift + WHERE Id=@id"; + var shift = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", + JsonConvert.SerializeObject(shift)); + return shift; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } } public IEnumerable ReadShifts(DateTime? dateFrom = null, DateTime? dateTo = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM Shift"; + var shifts = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(shifts)); + return shifts; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } public void UpdateShift(Shift shift) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(shift)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" + UPDATE Shift + SET + StartTime=@StartTime, + EndTime=@EndTime, + Date=@Date, + Type=@Type + WHERE Id=@Id"; + connection.Execute(queryUpdate, shift); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } } diff --git a/ProjectGasStation/ProjectGasStation/appsettings.json b/ProjectGasStation/ProjectGasStation/appsettings.json new file mode 100644 index 0000000..92987f5 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/gas_log.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file