From 7277ac55640f85681fe2fc6cdc6e2bb6bdd5e160 Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Thu, 28 Nov 2024 22:46:58 +0400 Subject: [PATCH 1/6] =?UTF-8?q?=D0=BD=D0=B0=D1=87=D0=B0=D0=BB=D0=BE=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectGarage/Program.cs | 2 ++ ProjectGarage/ProjectGarage.csproj | 15 +++++++++++++++ ProjectGarage/Repositories/IConnectionString.cs | 12 ++++++++++++ .../Implementations/ConnectionString.cs | 12 ++++++++++++ .../Implementations/DriverRepository.cs | 7 +++++++ ProjectGarage/Resources/appsettings.json | 15 +++++++++++++++ garage.txt | 0 7 files changed, 63 insertions(+) create mode 100644 ProjectGarage/Repositories/IConnectionString.cs create mode 100644 ProjectGarage/Repositories/Implementations/ConnectionString.cs create mode 100644 ProjectGarage/Resources/appsettings.json create mode 100644 garage.txt diff --git a/ProjectGarage/Program.cs b/ProjectGarage/Program.cs index 72fc364..559f30f 100644 --- a/ProjectGarage/Program.cs +++ b/ProjectGarage/Program.cs @@ -29,6 +29,8 @@ namespace ProjectGarage container.RegisterType(); container.RegisterType(); + container.RegisterType(); + return container; } } diff --git a/ProjectGarage/ProjectGarage.csproj b/ProjectGarage/ProjectGarage.csproj index accbdf0..166436b 100644 --- a/ProjectGarage/ProjectGarage.csproj +++ b/ProjectGarage/ProjectGarage.csproj @@ -9,7 +9,16 @@ + + + + + + + + + @@ -27,4 +36,10 @@ + + + PreserveNewest + + + \ No newline at end of file diff --git a/ProjectGarage/Repositories/IConnectionString.cs b/ProjectGarage/Repositories/IConnectionString.cs new file mode 100644 index 0000000..6ef769f --- /dev/null +++ b/ProjectGarage/Repositories/IConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Repositories; + +public interface IConnectionString +{ + public string ConnectionString { get; } +} diff --git a/ProjectGarage/Repositories/Implementations/ConnectionString.cs b/ProjectGarage/Repositories/Implementations/ConnectionString.cs new file mode 100644 index 0000000..152a14c --- /dev/null +++ b/ProjectGarage/Repositories/Implementations/ConnectionString.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGarage.Repositories.Implementations; + +public class ConnectionString : IConnectionString +{ + string IConnectionString.ConnectionString => ""; +} diff --git a/ProjectGarage/Repositories/Implementations/DriverRepository.cs b/ProjectGarage/Repositories/Implementations/DriverRepository.cs index 0fba152..f263df5 100644 --- a/ProjectGarage/Repositories/Implementations/DriverRepository.cs +++ b/ProjectGarage/Repositories/Implementations/DriverRepository.cs @@ -9,6 +9,13 @@ namespace ProjectGarage.Repositories.Implementations; public class DriverRepository : IDriverRepository { + public readonly IConnectionString _connectionString; + + public DriverRepository(IConnectionString connectionString) + { + _connectionString = connectionString; + } + public void CreateDriver(Driver driver) { } diff --git a/ProjectGarage/Resources/appsettings.json b/ProjectGarage/Resources/appsettings.json new file mode 100644 index 0000000..91d6319 --- /dev/null +++ b/ProjectGarage/Resources/appsettings.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "C\\Users\\dimoo\\OneDrive\\Рабочий стол\\Учеба\\2 курс\\Лабы 2 курс\\ОТП\\garage.txt", + "rollingInterval": "Day" + } + } + ] + } +} \ No newline at end of file diff --git a/garage.txt b/garage.txt new file mode 100644 index 0000000..e69de29 -- 2.25.1 From 0942dd8be33d27901f04a04977881f05422b28c4 Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Sat, 30 Nov 2024 16:03:41 +0400 Subject: [PATCH 2/6] a little work --- ProjectGarage/Program.cs | 18 ++++++++++++++++++ ProjectGarage/ProjectGarage.csproj | 3 ++- .../Implementations/ConnectionString.cs | 2 +- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/ProjectGarage/Program.cs b/ProjectGarage/Program.cs index 559f30f..b6f110f 100644 --- a/ProjectGarage/Program.cs +++ b/ProjectGarage/Program.cs @@ -1,6 +1,11 @@ using ProjectGarage.Repositories; using ProjectGarage.Repositories.Implementations; +using Unity.Lifetime; using Unity; +using Unity.Microsoft.Logging; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Serilog; namespace ProjectGarage { @@ -21,6 +26,7 @@ namespace ProjectGarage private static IUnityContainer CreateContainer() { var container = new UnityContainer(); + container.AddExtension(new LoggingExtension(CreateLoggerFactory())); container.RegisterType(); container.RegisterType(); @@ -33,5 +39,17 @@ namespace ProjectGarage 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/ProjectGarage/ProjectGarage.csproj b/ProjectGarage/ProjectGarage.csproj index 166436b..19ad3ed 100644 --- a/ProjectGarage/ProjectGarage.csproj +++ b/ProjectGarage/ProjectGarage.csproj @@ -13,7 +13,8 @@ - + + diff --git a/ProjectGarage/Repositories/Implementations/ConnectionString.cs b/ProjectGarage/Repositories/Implementations/ConnectionString.cs index 152a14c..938ce31 100644 --- a/ProjectGarage/Repositories/Implementations/ConnectionString.cs +++ b/ProjectGarage/Repositories/Implementations/ConnectionString.cs @@ -8,5 +8,5 @@ namespace ProjectGarage.Repositories.Implementations; public class ConnectionString : IConnectionString { - string IConnectionString.ConnectionString => ""; + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres"; } -- 2.25.1 From 6030309361a9ac239b4e14df7626c1d3033cc0e1 Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Mon, 2 Dec 2024 23:02:30 +0400 Subject: [PATCH 3/6] =?UTF-8?q?=D0=BF=D1=80=D0=B8=D0=BD=D1=86=D0=B8=D0=BF?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=BD=D1=8F=D1=82=D0=B5=D0=BD,=20=D1=81=D0=BA?= =?UTF-8?q?=D0=BE=D1=80=D0=BE=20=D0=B1=D1=83=D0=B4=D0=B5=D1=82=20=D0=B1?= =?UTF-8?q?=D1=83=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectGarage/Entities/Driver.cs | 3 +- ProjectGarage/ProjectGarage.csproj | 2 + .../Implementations/DriverRepository.cs | 118 ++++++++++++++++-- ProjectGarage/Resources/appsettings.json | 2 +- garage.txt | 0 5 files changed, 112 insertions(+), 13 deletions(-) delete mode 100644 garage.txt diff --git a/ProjectGarage/Entities/Driver.cs b/ProjectGarage/Entities/Driver.cs index 02ecffc..506df4b 100644 --- a/ProjectGarage/Entities/Driver.cs +++ b/ProjectGarage/Entities/Driver.cs @@ -19,14 +19,13 @@ public class Driver public int TruckId { get;private set; } - public static Driver CreateDriver(int id, string fname, string lname ,string phone_num, int tryckid) + public static Driver CreateDriver(int id, string fname, string lname, int tryckid) { return new Driver { Id = id, First_name = fname, Last_name = lname, - Phone_Number = phone_num ?? string.Empty, TruckId = tryckid }; } diff --git a/ProjectGarage/ProjectGarage.csproj b/ProjectGarage/ProjectGarage.csproj index 19ad3ed..0e8c74c 100644 --- a/ProjectGarage/ProjectGarage.csproj +++ b/ProjectGarage/ProjectGarage.csproj @@ -13,6 +13,8 @@ + + diff --git a/ProjectGarage/Repositories/Implementations/DriverRepository.cs b/ProjectGarage/Repositories/Implementations/DriverRepository.cs index f263df5..b7d753e 100644 --- a/ProjectGarage/Repositories/Implementations/DriverRepository.cs +++ b/ProjectGarage/Repositories/Implementations/DriverRepository.cs @@ -1,6 +1,11 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,24 +16,117 @@ public class DriverRepository : IDriverRepository { public readonly IConnectionString _connectionString; - public DriverRepository(IConnectionString connectionString) + private readonly ILogger _logger; + + public DriverRepository(IConnectionString connectionString, ILogger logger) { _connectionString = connectionString; + _logger = logger; } public void CreateDriver(Driver driver) { + _logger.LogInformation("Добавление объект"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(driver)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + var queryInsert = @" +INSERT INTO driver (driver_fname, driver_lname, id_truck) VALUES +(@First_name, @Last_name, @TruckID);"; + connection.Execute(queryInsert, driver); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } - public void DeleteDriver(int id) - { - } - - public Driver ReadDriverByID(int id) => Driver.CreateDriver(0, string.Empty, string.Empty, string.Empty, 0); - - public IEnumerable ReadDrivers() => []; - public void UpdateDriver(Driver driver) { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(driver)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" +UPDATE driver +SET +driver_fname=@First_name, +driver_lname=@Last_name, +id_truck=@TruckID +WHERE id_driver=@Id"; + connection.Execute(queryUpdate, driver); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } + } + + public void DeleteDriver(int driverId) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", driverId); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" +DELETE FROM driver +WHERE id_driver=@id"; + connection.Execute(queryDelete, new { driverId }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + + public Driver ReadDriverByID(int driverId) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", driverId); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" +SELECT * FROM route_list +WHERE id=@routeListId"; + var driver = connection.QueryFirst(querySelect, new { driverId }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(driver)); + + return driver; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadDrivers() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM driver"; + var driver = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(driver)); + return driver; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGarage/Resources/appsettings.json b/ProjectGarage/Resources/appsettings.json index 91d6319..e5d07ff 100644 --- a/ProjectGarage/Resources/appsettings.json +++ b/ProjectGarage/Resources/appsettings.json @@ -6,7 +6,7 @@ { "Name": "File", "Args": { - "path": "C\\Users\\dimoo\\OneDrive\\Рабочий стол\\Учеба\\2 курс\\Лабы 2 курс\\ОТП\\garage.txt", + "path": "Logs/garage.txt", "rollingInterval": "Day" } } diff --git a/garage.txt b/garage.txt deleted file mode 100644 index e69de29..0000000 -- 2.25.1 From bd528d9f0d10cc2f37f7ac9ed3279a0048d69240 Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Tue, 3 Dec 2024 09:30:28 +0400 Subject: [PATCH 4/6] =?UTF-8?q?=D0=BF=D0=BE=D0=BB=D0=BE=D0=BC=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectGarage/Entities/Driver.cs | 2 -- ProjectGarage/Forms/FormDriver.cs | 2 +- ProjectGarage/Forms/FormDrivers.cs | 1 - ProjectGarage/Forms/FormTruck.cs | 1 + ProjectGarage/Forms/FormTrucks.cs | 4 ++-- ProjectGarage/ProjectGarage.csproj | 2 +- .../Repositories/Implementations/DriverRepository.cs | 12 ++++++------ ProjectGarage/{Resources => }/appsettings.json | 0 8 files changed, 11 insertions(+), 13 deletions(-) rename ProjectGarage/{Resources => }/appsettings.json (100%) diff --git a/ProjectGarage/Entities/Driver.cs b/ProjectGarage/Entities/Driver.cs index 506df4b..3c4dd3c 100644 --- a/ProjectGarage/Entities/Driver.cs +++ b/ProjectGarage/Entities/Driver.cs @@ -15,8 +15,6 @@ public class Driver public string Last_name { get;private set; } = string.Empty; - public string Phone_Number { get;private set; } = string.Empty; - public int TruckId { get;private set; } public static Driver CreateDriver(int id, string fname, string lname, int tryckid) diff --git a/ProjectGarage/Forms/FormDriver.cs b/ProjectGarage/Forms/FormDriver.cs index ea1a7f6..5bdc702 100644 --- a/ProjectGarage/Forms/FormDriver.cs +++ b/ProjectGarage/Forms/FormDriver.cs @@ -82,6 +82,6 @@ namespace ProjectGarage.Forms private void ButtonCancelDriver_Click(object sender, EventArgs e) => Close(); private Driver CreateDriver(int id) => Driver.CreateDriver(id, textBoxFirstName.Text, - textBoxLastName.Text, textBoxPhoneNum.Text, (int)comboBoxTruckID.SelectedIndex!);// + textBoxLastName.Text, (int)comboBoxTruckID.SelectedIndex!);// } } diff --git a/ProjectGarage/Forms/FormDrivers.cs b/ProjectGarage/Forms/FormDrivers.cs index b5444ad..cf1853d 100644 --- a/ProjectGarage/Forms/FormDrivers.cs +++ b/ProjectGarage/Forms/FormDrivers.cs @@ -36,7 +36,6 @@ namespace ProjectGarage.Forms } } - private void ButtonAddDriver_Click(object sender, EventArgs e) { try diff --git a/ProjectGarage/Forms/FormTruck.cs b/ProjectGarage/Forms/FormTruck.cs index b1878a1..d6a6a03 100644 --- a/ProjectGarage/Forms/FormTruck.cs +++ b/ProjectGarage/Forms/FormTruck.cs @@ -24,6 +24,7 @@ namespace ProjectGarage.Forms textBoxTruckNumbers.Text = truck.Numbers; comboBoxTruckType.SelectedItem = truck.Type; numericUpDownMaxFuel.Value = truck.MaxFuel; + _truckId = value; } catch (Exception ex) { diff --git a/ProjectGarage/Forms/FormTrucks.cs b/ProjectGarage/Forms/FormTrucks.cs index c135a16..41a2e7f 100644 --- a/ProjectGarage/Forms/FormTrucks.cs +++ b/ProjectGarage/Forms/FormTrucks.cs @@ -32,7 +32,7 @@ namespace ProjectGarage.Forms } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при закгрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); } } @@ -56,7 +56,7 @@ namespace ProjectGarage.Forms return; } - if (MessageBox.Show("Удалить звпись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) + if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) { return; } diff --git a/ProjectGarage/ProjectGarage.csproj b/ProjectGarage/ProjectGarage.csproj index 0e8c74c..c4cc11c 100644 --- a/ProjectGarage/ProjectGarage.csproj +++ b/ProjectGarage/ProjectGarage.csproj @@ -40,7 +40,7 @@ - + PreserveNewest diff --git a/ProjectGarage/Repositories/Implementations/DriverRepository.cs b/ProjectGarage/Repositories/Implementations/DriverRepository.cs index b7d753e..047c8a5 100644 --- a/ProjectGarage/Repositories/Implementations/DriverRepository.cs +++ b/ProjectGarage/Repositories/Implementations/DriverRepository.cs @@ -79,7 +79,7 @@ WHERE id_driver=@Id"; using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryDelete = @" DELETE FROM driver -WHERE id_driver=@id"; +WHERE id_driver=@driverId"; connection.Execute(queryDelete, new { driverId }); } catch (Exception ex) @@ -98,8 +98,8 @@ WHERE id_driver=@id"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" -SELECT * FROM route_list -WHERE id=@routeListId"; +SELECT * FROM driver +WHERE id_driver=@driverId"; var driver = connection.QueryFirst(querySelect, new { driverId }); _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(driver)); @@ -119,9 +119,9 @@ WHERE id=@routeListId"; { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @"SELECT * FROM driver"; - var driver = connection.Query(querySelect); - _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(driver)); - return driver; + var drivers = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(drivers)); + return drivers; } catch (Exception ex) { diff --git a/ProjectGarage/Resources/appsettings.json b/ProjectGarage/appsettings.json similarity index 100% rename from ProjectGarage/Resources/appsettings.json rename to ProjectGarage/appsettings.json -- 2.25.1 From d243c03fc8061b45998dc97045565cc0893e3f1b Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Tue, 3 Dec 2024 23:06:20 +0400 Subject: [PATCH 5/6] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D1=82=D0=B8=20=D0=B2?= =?UTF-8?q?=D1=81=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ProjectGarage/Entities/Driver.cs | 8 +- ProjectGarage/Entities/Enums/TruckType.cs | 3 +- ProjectGarage/Entities/Fuel.cs | 8 +- ProjectGarage/Entities/Route.cs | 14 +-- ProjectGarage/Entities/Truck.cs | 4 +- ProjectGarage/Forms/FormDriver.Designer.cs | 33 +---- ProjectGarage/Forms/FormDriver.cs | 11 +- ProjectGarage/Forms/FormFuel.cs | 4 +- ProjectGarage/Forms/FormRoute.Designer.cs | 41 +++++-- ProjectGarage/Forms/FormRoute.cs | 6 +- ProjectGarage/Forms/FormTransportation.cs | 6 +- .../Forms/FormTransportations.Designer.cs | 6 +- ProjectGarage/Forms/FormTruck.Designer.cs | 1 + ProjectGarage/Forms/FormTruck.cs | 2 +- .../Repositories/ITransportationRepository.cs | 2 - .../Implementations/ConnectionString.cs | 2 +- .../Implementations/DriverRepository.cs | 29 +++-- .../Implementations/FuelRepository.cs | 113 ++++++++++++++++- .../Implementations/RouteRepository.cs | 115 ++++++++++++++++-- .../TransportationRepository.cs | 56 +++++++-- .../Implementations/TruckRepository.cs | 114 ++++++++++++++++- 21 files changed, 458 insertions(+), 120 deletions(-) diff --git a/ProjectGarage/Entities/Driver.cs b/ProjectGarage/Entities/Driver.cs index 3c4dd3c..c8d2711 100644 --- a/ProjectGarage/Entities/Driver.cs +++ b/ProjectGarage/Entities/Driver.cs @@ -11,9 +11,9 @@ public class Driver { public int Id { get;private set; } - public string First_name { get;private set; } = string.Empty; + public string Fname { get;private set; } = string.Empty; - public string Last_name { get;private set; } = string.Empty; + public string Lname { get;private set; } = string.Empty; public int TruckId { get;private set; } @@ -22,8 +22,8 @@ public class Driver return new Driver { Id = id, - First_name = fname, - Last_name = lname, + Fname = fname, + Lname = lname, TruckId = tryckid }; } diff --git a/ProjectGarage/Entities/Enums/TruckType.cs b/ProjectGarage/Entities/Enums/TruckType.cs index 9523151..b426b8c 100644 --- a/ProjectGarage/Entities/Enums/TruckType.cs +++ b/ProjectGarage/Entities/Enums/TruckType.cs @@ -13,6 +13,7 @@ namespace ProjectGarage.Entities.Enums SCANIA = 2, KAMAZ = 3, MAN = 4, - Volvo = 5 + Volvo = 5, + SITRAC = 6 } } diff --git a/ProjectGarage/Entities/Fuel.cs b/ProjectGarage/Entities/Fuel.cs index f12e164..5721b4c 100644 --- a/ProjectGarage/Entities/Fuel.cs +++ b/ProjectGarage/Entities/Fuel.cs @@ -12,9 +12,9 @@ public class Fuel { public int Id { get; set; } - public string Name { get; set; } = string.Empty; + public string FuelName { get; set; } = string.Empty; - public FuelType Type { get; set; } + public FuelType FuelType { get; set; } public int Price { get; set; } @@ -23,8 +23,8 @@ public class Fuel return new Fuel { Id = id, - Name = name, - Type = type, + FuelName = name, + FuelType = type, Price = price }; } diff --git a/ProjectGarage/Entities/Route.cs b/ProjectGarage/Entities/Route.cs index a511640..7d60fd8 100644 --- a/ProjectGarage/Entities/Route.cs +++ b/ProjectGarage/Entities/Route.cs @@ -10,21 +10,21 @@ public class Route { public int Id { get; set; } - public string Name { get; set; } = string.Empty; + public string RouteName { get; set; } = string.Empty; - public string StartPoint { get; set; } = string.Empty; + public string StartP { get; set; } = string.Empty; - public string FinalPoint { get; set; } = string.Empty; + public string FinalP { get; set; } = string.Empty; public int Length { get; set; } - public static Route CreateRoute(int id, string startp, string finalp, int len) + public static Route CreateRoute(int id,string name, string startp, string finalp, int len) { return new Route() { Id = id, - Name = startp + " - " + finalp, - StartPoint = startp, - FinalPoint = finalp, + RouteName = name, + StartP = startp, + FinalP = finalp, Length = len }; } diff --git a/ProjectGarage/Entities/Truck.cs b/ProjectGarage/Entities/Truck.cs index c416718..c412dc4 100644 --- a/ProjectGarage/Entities/Truck.cs +++ b/ProjectGarage/Entities/Truck.cs @@ -13,7 +13,7 @@ public class Truck public string Numbers { get; private set; } = string.Empty; - public TruckType Type { get; set; } + public TruckType Truck_Type { get; set; } public int MaxFuel { get; private set; } @@ -23,7 +23,7 @@ public class Truck { Id = id, Numbers = numbers, - Type = type, + Truck_Type = type, MaxFuel = maxFuel }; } diff --git a/ProjectGarage/Forms/FormDriver.Designer.cs b/ProjectGarage/Forms/FormDriver.Designer.cs index b63e004..aa439ca 100644 --- a/ProjectGarage/Forms/FormDriver.Designer.cs +++ b/ProjectGarage/Forms/FormDriver.Designer.cs @@ -32,8 +32,6 @@ textBoxFirstName = new TextBox(); textBoxLastName = new TextBox(); labelLastName = new Label(); - textBoxPhoneNum = new TextBox(); - labelPhoneNum = new Label(); labelTruckID = new Label(); buttonSaveDriver = new Button(); buttonCancelDriver = new Button(); @@ -72,27 +70,10 @@ labelLastName.TabIndex = 2; labelLastName.Text = "Фамилия"; // - // textBoxPhoneNum - // - textBoxPhoneNum.Location = new Point(120, 115); - textBoxPhoneNum.Name = "textBoxPhoneNum"; - textBoxPhoneNum.Size = new Size(183, 27); - textBoxPhoneNum.TabIndex = 5; - textBoxPhoneNum.Text = "+7"; - // - // labelPhoneNum - // - labelPhoneNum.AutoSize = true; - labelPhoneNum.Location = new Point(20, 118); - labelPhoneNum.Name = "labelPhoneNum"; - labelPhoneNum.Size = new Size(69, 20); - labelPhoneNum.TabIndex = 4; - labelPhoneNum.Text = "Телефон"; - // // labelTruckID // labelTruckID.AutoSize = true; - labelTruckID.Location = new Point(34, 164); + labelTruckID.Location = new Point(34, 121); labelTruckID.Name = "labelTruckID"; labelTruckID.Size = new Size(44, 20); labelTruckID.TabIndex = 6; @@ -100,7 +81,7 @@ // // buttonSaveDriver // - buttonSaveDriver.Location = new Point(20, 231); + buttonSaveDriver.Location = new Point(20, 158); buttonSaveDriver.Name = "buttonSaveDriver"; buttonSaveDriver.Size = new Size(128, 39); buttonSaveDriver.TabIndex = 8; @@ -110,7 +91,7 @@ // // buttonCancelDriver // - buttonCancelDriver.Location = new Point(175, 231); + buttonCancelDriver.Location = new Point(175, 158); buttonCancelDriver.Name = "buttonCancelDriver"; buttonCancelDriver.Size = new Size(128, 39); buttonCancelDriver.TabIndex = 9; @@ -122,7 +103,7 @@ // comboBoxTruckID.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxTruckID.FormattingEnabled = true; - comboBoxTruckID.Location = new Point(120, 156); + comboBoxTruckID.Location = new Point(120, 113); comboBoxTruckID.Name = "comboBoxTruckID"; comboBoxTruckID.Size = new Size(183, 28); comboBoxTruckID.TabIndex = 10; @@ -131,13 +112,11 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(333, 302); + ClientSize = new Size(333, 218); Controls.Add(comboBoxTruckID); Controls.Add(buttonCancelDriver); Controls.Add(buttonSaveDriver); Controls.Add(labelTruckID); - Controls.Add(textBoxPhoneNum); - Controls.Add(labelPhoneNum); Controls.Add(textBoxLastName); Controls.Add(labelLastName); Controls.Add(textBoxFirstName); @@ -155,8 +134,6 @@ private TextBox textBoxFirstName; private TextBox textBoxLastName; private Label labelLastName; - private TextBox textBoxPhoneNum; - private Label labelPhoneNum; private Label labelTruckID; private Button buttonSaveDriver; private Button buttonCancelDriver; diff --git a/ProjectGarage/Forms/FormDriver.cs b/ProjectGarage/Forms/FormDriver.cs index 5bdc702..6d5a6f8 100644 --- a/ProjectGarage/Forms/FormDriver.cs +++ b/ProjectGarage/Forms/FormDriver.cs @@ -24,15 +24,14 @@ namespace ProjectGarage.Forms { try { - var driver = _driverRepository.ReadDriverByID(value); if (driver == null) { throw new InvalidDataException(nameof(driver)); } - textBoxFirstName.Text = driver.First_name; - textBoxLastName.Text = driver.Last_name; + textBoxFirstName.Text = driver.Fname; + textBoxLastName.Text = driver.Lname; //comboBoxTruckID.SelectedItem = driver.TruckId; _driverId = value; } @@ -48,7 +47,7 @@ namespace ProjectGarage.Forms { InitializeComponent(); _driverRepository = driverRepository ?? throw new ArgumentNullException(nameof(driverRepository)); - comboBoxTruckID.DataSource = truckRepository.ReadTrucks();// + comboBoxTruckID.DataSource = truckRepository.ReadTrucks(); comboBoxTruckID.DisplayMember = "Numbers"; comboBoxTruckID.ValueMember = "Id"; } @@ -58,7 +57,7 @@ namespace ProjectGarage.Forms try { if (string.IsNullOrWhiteSpace(textBoxFirstName.Text) || string.IsNullOrWhiteSpace(textBoxLastName.Text) - || comboBoxTruckID.SelectedIndex < 0)// + || comboBoxTruckID.SelectedIndex < 0) { throw new Exception("Имеются незаполненные поля"); } @@ -82,6 +81,6 @@ namespace ProjectGarage.Forms private void ButtonCancelDriver_Click(object sender, EventArgs e) => Close(); private Driver CreateDriver(int id) => Driver.CreateDriver(id, textBoxFirstName.Text, - textBoxLastName.Text, (int)comboBoxTruckID.SelectedIndex!);// + textBoxLastName.Text, (int)comboBoxTruckID.SelectedIndex!); } } diff --git a/ProjectGarage/Forms/FormFuel.cs b/ProjectGarage/Forms/FormFuel.cs index dba03d4..519935b 100644 --- a/ProjectGarage/Forms/FormFuel.cs +++ b/ProjectGarage/Forms/FormFuel.cs @@ -33,12 +33,12 @@ namespace ProjectGarage.Forms } foreach (FuelType elem in Enum.GetValues(typeof(FuelType))) { - if ((elem & fuel.Type) != 0) + if ((elem & fuel.FuelType) != 0) { checkedListBoxFuel.SetItemChecked(checkedListBoxFuel.Items.IndexOf(elem), true); } } - textBoxFuelName.Text = fuel.Name; + textBoxFuelName.Text = fuel.FuelName; _fuelId = value; } catch (Exception ex) diff --git a/ProjectGarage/Forms/FormRoute.Designer.cs b/ProjectGarage/Forms/FormRoute.Designer.cs index 36649fa..deac002 100644 --- a/ProjectGarage/Forms/FormRoute.Designer.cs +++ b/ProjectGarage/Forms/FormRoute.Designer.cs @@ -36,13 +36,15 @@ buttonRouteFinal = new Button(); textBoxRouteStart = new TextBox(); textBoxRouteFinal = new TextBox(); + textBoxRouteName = new TextBox(); + labelRouteName = new Label(); ((System.ComponentModel.ISupportInitialize)numericUpDownRouteLen).BeginInit(); SuspendLayout(); // // labelRouteStart // labelRouteStart.AutoSize = true; - labelRouteStart.Location = new Point(12, 20); + labelRouteStart.Location = new Point(22, 62); labelRouteStart.Name = "labelRouteStart"; labelRouteStart.Size = new Size(135, 20); labelRouteStart.TabIndex = 0; @@ -51,7 +53,7 @@ // labelRouteFinal // labelRouteFinal.AutoSize = true; - labelRouteFinal.Location = new Point(12, 62); + labelRouteFinal.Location = new Point(22, 104); labelRouteFinal.Name = "labelRouteFinal"; labelRouteFinal.Size = new Size(127, 20); labelRouteFinal.TabIndex = 1; @@ -59,7 +61,8 @@ // // numericUpDownRouteLen // - numericUpDownRouteLen.Location = new Point(160, 103); + numericUpDownRouteLen.Location = new Point(170, 145); + numericUpDownRouteLen.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); numericUpDownRouteLen.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); numericUpDownRouteLen.Name = "numericUpDownRouteLen"; numericUpDownRouteLen.Size = new Size(150, 27); @@ -69,7 +72,7 @@ // labelRouteLen // labelRouteLen.AutoSize = true; - labelRouteLen.Location = new Point(12, 103); + labelRouteLen.Location = new Point(22, 145); labelRouteLen.Name = "labelRouteLen"; labelRouteLen.Size = new Size(127, 20); labelRouteLen.TabIndex = 3; @@ -77,7 +80,7 @@ // // buttonRouteSave // - buttonRouteSave.Location = new Point(12, 149); + buttonRouteSave.Location = new Point(22, 191); buttonRouteSave.Name = "buttonRouteSave"; buttonRouteSave.Size = new Size(135, 29); buttonRouteSave.TabIndex = 4; @@ -87,7 +90,7 @@ // // buttonRouteFinal // - buttonRouteFinal.Location = new Point(160, 149); + buttonRouteFinal.Location = new Point(170, 191); buttonRouteFinal.Name = "buttonRouteFinal"; buttonRouteFinal.Size = new Size(150, 29); buttonRouteFinal.TabIndex = 5; @@ -97,23 +100,41 @@ // // textBoxRouteStart // - textBoxRouteStart.Location = new Point(160, 20); + textBoxRouteStart.Location = new Point(170, 62); textBoxRouteStart.Name = "textBoxRouteStart"; textBoxRouteStart.Size = new Size(150, 27); textBoxRouteStart.TabIndex = 6; // // textBoxRouteFinal // - textBoxRouteFinal.Location = new Point(160, 62); + textBoxRouteFinal.Location = new Point(170, 104); textBoxRouteFinal.Name = "textBoxRouteFinal"; textBoxRouteFinal.Size = new Size(150, 27); textBoxRouteFinal.TabIndex = 7; // + // textBoxRouteName + // + textBoxRouteName.Location = new Point(179, 12); + textBoxRouteName.Name = "textBoxRouteName"; + textBoxRouteName.Size = new Size(141, 27); + textBoxRouteName.TabIndex = 9; + // + // labelRouteName + // + labelRouteName.AutoSize = true; + labelRouteName.Location = new Point(22, 19); + labelRouteName.Name = "labelRouteName"; + labelRouteName.Size = new Size(151, 20); + labelRouteName.TabIndex = 8; + labelRouteName.Text = "Название маршрута"; + // // FormRoute // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(332, 199); + ClientSize = new Size(332, 240); + Controls.Add(textBoxRouteName); + Controls.Add(labelRouteName); Controls.Add(textBoxRouteFinal); Controls.Add(textBoxRouteStart); Controls.Add(buttonRouteFinal); @@ -139,5 +160,7 @@ private Button buttonRouteFinal; private TextBox textBoxRouteStart; private TextBox textBoxRouteFinal; + private TextBox textBoxRouteName; + private Label labelRouteName; } } \ No newline at end of file diff --git a/ProjectGarage/Forms/FormRoute.cs b/ProjectGarage/Forms/FormRoute.cs index d49b465..a3207c8 100644 --- a/ProjectGarage/Forms/FormRoute.cs +++ b/ProjectGarage/Forms/FormRoute.cs @@ -31,8 +31,8 @@ namespace ProjectGarage.Forms throw new InvalidDataException(nameof(route)); } - textBoxRouteStart.Text = route.StartPoint; - textBoxRouteFinal.Text = route.FinalPoint; + textBoxRouteStart.Text = route.StartP; + textBoxRouteFinal.Text = route.FinalP; numericUpDownRouteLen.Value = route.Length; _routeId = value; } @@ -79,7 +79,7 @@ namespace ProjectGarage.Forms private void ButtonRouteFinal_Click(object sender, EventArgs e) => Close(); - private Route CreateRoute(int id) => Route.CreateRoute(id, textBoxRouteStart.Text, + private Route CreateRoute(int id) => Route.CreateRoute(id, textBoxRouteName.Text, textBoxRouteStart.Text, textBoxRouteFinal.Text, Convert.ToInt32(numericUpDownRouteLen.Value)); } } diff --git a/ProjectGarage/Forms/FormTransportation.cs b/ProjectGarage/Forms/FormTransportation.cs index a1b2448..8bb7fc5 100644 --- a/ProjectGarage/Forms/FormTransportation.cs +++ b/ProjectGarage/Forms/FormTransportation.cs @@ -25,15 +25,15 @@ namespace ProjectGarage.Forms throw new ArgumentNullException(nameof(transportationRepository)); comboBoxDriver.DataSource = driverRepository.ReadDrivers(); - comboBoxDriver.DisplayMember = "First_name"; + comboBoxDriver.DisplayMember = "Fname"; comboBoxDriver.ValueMember = "Id"; comboBoxFuel.DataSource = fuelRepository.ReadFuels(); - comboBoxFuel.DisplayMember = "Name"; + comboBoxFuel.DisplayMember = "FuelName"; comboBoxFuel.ValueMember = "Id"; comboBoxRoute.DataSource = routeRepository.ReadRoute(); - comboBoxRoute.DisplayMember = "Name"; + comboBoxRoute.DisplayMember = "RouteName"; comboBoxRoute.ValueMember = "Id"; } diff --git a/ProjectGarage/Forms/FormTransportations.Designer.cs b/ProjectGarage/Forms/FormTransportations.Designer.cs index 9a52d64..6af4fd2 100644 --- a/ProjectGarage/Forms/FormTransportations.Designer.cs +++ b/ProjectGarage/Forms/FormTransportations.Designer.cs @@ -61,14 +61,14 @@ dataGridViewTransportations.RowHeadersVisible = false; dataGridViewTransportations.RowHeadersWidth = 51; dataGridViewTransportations.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridViewTransportations.Size = new Size(639, 450); + dataGridViewTransportations.Size = new Size(847, 450); dataGridViewTransportations.TabIndex = 7; // // panelFormTransportationsButtons // panelFormTransportationsButtons.Controls.Add(buttonAddTransportation); panelFormTransportationsButtons.Dock = DockStyle.Right; - panelFormTransportationsButtons.Location = new Point(639, 0); + panelFormTransportationsButtons.Location = new Point(847, 0); panelFormTransportationsButtons.Name = "panelFormTransportationsButtons"; panelFormTransportationsButtons.Size = new Size(161, 450); panelFormTransportationsButtons.TabIndex = 6; @@ -77,7 +77,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 450); + ClientSize = new Size(1008, 450); Controls.Add(dataGridViewTransportations); Controls.Add(panelFormTransportationsButtons); Name = "FormTransportations"; diff --git a/ProjectGarage/Forms/FormTruck.Designer.cs b/ProjectGarage/Forms/FormTruck.Designer.cs index a1a9af7..54c477e 100644 --- a/ProjectGarage/Forms/FormTruck.Designer.cs +++ b/ProjectGarage/Forms/FormTruck.Designer.cs @@ -76,6 +76,7 @@ // numericUpDownMaxFuel // numericUpDownMaxFuel.Location = new Point(158, 115); + numericUpDownMaxFuel.Maximum = new decimal(new int[] { 3000, 0, 0, 0 }); numericUpDownMaxFuel.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); numericUpDownMaxFuel.Name = "numericUpDownMaxFuel"; numericUpDownMaxFuel.Size = new Size(183, 27); diff --git a/ProjectGarage/Forms/FormTruck.cs b/ProjectGarage/Forms/FormTruck.cs index d6a6a03..d5d437f 100644 --- a/ProjectGarage/Forms/FormTruck.cs +++ b/ProjectGarage/Forms/FormTruck.cs @@ -22,7 +22,7 @@ namespace ProjectGarage.Forms } textBoxTruckNumbers.Text = truck.Numbers; - comboBoxTruckType.SelectedItem = truck.Type; + comboBoxTruckType.SelectedItem = truck.Truck_Type; numericUpDownMaxFuel.Value = truck.MaxFuel; _truckId = value; } diff --git a/ProjectGarage/Repositories/ITransportationRepository.cs b/ProjectGarage/Repositories/ITransportationRepository.cs index 1e4c578..9d0a407 100644 --- a/ProjectGarage/Repositories/ITransportationRepository.cs +++ b/ProjectGarage/Repositories/ITransportationRepository.cs @@ -12,6 +12,4 @@ public interface ITransportationRepository IEnumerable ReadTransportation(DateTime? dateForm = null, DateTime? dateTo = null, int? fuelId = null, int? driverId = null, int? routeId = null); void CreateTransportation(Transportation transportation); - - void DeleteTransportation(int id); } diff --git a/ProjectGarage/Repositories/Implementations/ConnectionString.cs b/ProjectGarage/Repositories/Implementations/ConnectionString.cs index 938ce31..4fb8520 100644 --- a/ProjectGarage/Repositories/Implementations/ConnectionString.cs +++ b/ProjectGarage/Repositories/Implementations/ConnectionString.cs @@ -8,5 +8,5 @@ namespace ProjectGarage.Repositories.Implementations; public class ConnectionString : IConnectionString { - string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=postgres"; + string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=garage"; } diff --git a/ProjectGarage/Repositories/Implementations/DriverRepository.cs b/ProjectGarage/Repositories/Implementations/DriverRepository.cs index 047c8a5..034c2c4 100644 --- a/ProjectGarage/Repositories/Implementations/DriverRepository.cs +++ b/ProjectGarage/Repositories/Implementations/DriverRepository.cs @@ -32,10 +32,9 @@ public class DriverRepository : IDriverRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); var queryInsert = @" -INSERT INTO driver (driver_fname, driver_lname, id_truck) VALUES -(@First_name, @Last_name, @TruckID);"; +INSERT INTO driver (Fname, Lname, TruckId) VALUES +(@Fname, @Lname, @TruckId);"; connection.Execute(queryInsert, driver); } catch (Exception ex) @@ -56,10 +55,10 @@ INSERT INTO driver (driver_fname, driver_lname, id_truck) VALUES var queryUpdate = @" UPDATE driver SET -driver_fname=@First_name, -driver_lname=@Last_name, -id_truck=@TruckID -WHERE id_driver=@Id"; +Fname=@Fname, +Lname=@Lname, +TruckId=@TruckId +WHERE Id=@Id"; connection.Execute(queryUpdate, driver); } catch (Exception ex) @@ -69,18 +68,18 @@ WHERE id_driver=@Id"; } } - public void DeleteDriver(int driverId) + public void DeleteDriver(int id) { _logger.LogInformation("Удаление объекта"); - _logger.LogDebug("Объект: {id}", driverId); + _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryDelete = @" DELETE FROM driver -WHERE id_driver=@driverId"; - connection.Execute(queryDelete, new { driverId }); +WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); } catch (Exception ex) { @@ -89,18 +88,18 @@ WHERE id_driver=@driverId"; } } - public Driver ReadDriverByID(int driverId) + public Driver ReadDriverByID(int id) { _logger.LogInformation("Получение объекта по идентификатору"); - _logger.LogDebug("Объект: {id}", driverId); + _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @" SELECT * FROM driver -WHERE id_driver=@driverId"; - var driver = connection.QueryFirst(querySelect, new { driverId }); +WHERE Id=@id"; + var driver = connection.QueryFirst(querySelect, new { id }); _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(driver)); return driver; diff --git a/ProjectGarage/Repositories/Implementations/FuelRepository.cs b/ProjectGarage/Repositories/Implementations/FuelRepository.cs index 03d40a4..bdb6ae1 100644 --- a/ProjectGarage/Repositories/Implementations/FuelRepository.cs +++ b/ProjectGarage/Repositories/Implementations/FuelRepository.cs @@ -1,4 +1,8 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using ProjectGarage.Entities.Enums; using System; using System.Collections.Generic; @@ -10,19 +14,116 @@ namespace ProjectGarage.Repositories.Implementations; public class FuelRepository : IFuelRepository { + public 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 (FuelName, FuelType, Price) VALUES +(@FuelName, @FuelType, @Price);"; + connection.Execute(queryInsert, fuel); + } + 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 +FuelName=@FuelName, +FuelType=@Startp, +Price=@Price +WHERE Id=@Id"; + connection.Execute(queryUpdate, 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) => Fuel.CreateFuel(0, string.Empty, FuelType.None, 0); - - public IEnumerable ReadFuels() => []; - - public void UpdateFuel(Fuel fuel) + public Fuel ReadFuelByID(int id) { + _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() + { + _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; + } } } diff --git a/ProjectGarage/Repositories/Implementations/RouteRepository.cs b/ProjectGarage/Repositories/Implementations/RouteRepository.cs index 3a745ec..fdacfec 100644 --- a/ProjectGarage/Repositories/Implementations/RouteRepository.cs +++ b/ProjectGarage/Repositories/Implementations/RouteRepository.cs @@ -1,4 +1,8 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using System; using System.Collections.Generic; using System.Linq; @@ -9,26 +13,117 @@ namespace ProjectGarage.Repositories.Implementations; public class RouteRepository : IRouteRepository { - public void CreateFuelReplenishment(FuelReplenishment fuelReplenishment) - { - } + public readonly IConnectionString _connectionString; + private readonly ILogger _logger; + + public RouteRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } public void CreateRoute(Route route) { + _logger.LogInformation("Добавление объект"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(route)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO route (RouteName, Startp, Finalp, Length) VALUES +(@RouteName, @Startp, @Finalp, @Length);"; + connection.Execute(queryInsert, route); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateRoute(Route route) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(route)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" +UPDATE route +SET +RouteName=@RouteName, +Startp=@Startp, +Finalp=@Finalp, +Length=@Length +WHERE Id=@Id"; + connection.Execute(queryUpdate, route); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteRoute(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" +DELETE FROM route +WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } - public Route ReadRouteByID(int id) => Route.CreateRoute(0, string.Empty, string.Empty, 0); + public Route ReadRouteByID(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" +SELECT * FROM route +WHERE Id=@id"; + var route = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(route)); + + return route; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } public IEnumerable ReadRoute(string? startPoint = null, string? finalPoint = null) { - return []; - } - - public void UpdateRoute(Route route) - { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM route"; + var routes = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(routes)); + return routes; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } diff --git a/ProjectGarage/Repositories/Implementations/TransportationRepository.cs b/ProjectGarage/Repositories/Implementations/TransportationRepository.cs index 4cd902a..06e8a90 100644 --- a/ProjectGarage/Repositories/Implementations/TransportationRepository.cs +++ b/ProjectGarage/Repositories/Implementations/TransportationRepository.cs @@ -1,6 +1,11 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,17 +14,54 @@ namespace ProjectGarage.Repositories.Implementations; public class TransportationRepository : ITransportationRepository { + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public TransportationRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateTransportation(Transportation transportation) { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(transportation)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO transportation (DriverId, RouteId, FuelId, Amount, TransportationDate) +VALUES (@DriverId, @RouteId, @FuelId, @Amount, @TransportationDate)"; + connection.Execute(queryInsert, transportation); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } - public void DeleteTransportation(int id) + public IEnumerable ReadTransportation(DateTime? dateForm = null, DateTime? dateTo = null, + int? fuelId = null, int? driverId = null, int? routeId = null) { - throw new NotImplementedException(); - } + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = "SELECT * FROM transportation"; + var transportations = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(transportations)); + return transportations; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } - public IEnumerable ReadTransportation(DateTime? dateForm = null, DateTime? dateTo = null, int? fuelId = null, int? driverId = null, int? routeId = null) - { - return []; } } diff --git a/ProjectGarage/Repositories/Implementations/TruckRepository.cs b/ProjectGarage/Repositories/Implementations/TruckRepository.cs index ac2dbd3..465692f 100644 --- a/ProjectGarage/Repositories/Implementations/TruckRepository.cs +++ b/ProjectGarage/Repositories/Implementations/TruckRepository.cs @@ -1,4 +1,8 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using ProjectGarage.Entities.Enums; using System; using System.Collections.Generic; @@ -10,19 +14,117 @@ namespace ProjectGarage.Repositories.Implementations; public class TruckRepository : ITruckRepository { + public readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public TruckRepository(IConnectionString connectionString, ILogger logger) + { + _connectionString = connectionString; + _logger = logger; + } + public void CreateTruck(Truck truck) { + _logger.LogInformation("Добавление объект"); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(truck)); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryInsert = @" +INSERT INTO truck (Numbers, Truck_Type, MaxFuel) VALUES +(@Numbers, @Truck_Type, @MaxFuel);"; + connection.Execute(queryInsert, truck); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } + } + public void UpdateTruck(Truck truck) + { + _logger.LogInformation("Редактирование объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(truck)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryUpdate = @" +UPDATE truck +SET +Numbers=@Numbers, +Truck_Type=@Truck_Type, +MaxFuel=@MaxFuel +WHERE Id=@Id"; + connection.Execute(queryUpdate, truck); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при редактировании объекта"); + throw; + } } public void DeleteTruck(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" +DELETE FROM truck +WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } - public Truck ReadTruckByID(int id) => Truck.CreateTruck(0, string.Empty, TruckType.None, 0); - - public IEnumerable ReadTrucks() => []; - - public void UpdateTruck(Truck truck) + public Truck ReadTruckByID(int id) { + _logger.LogInformation("Получение объекта по идентификатору"); + _logger.LogDebug("Объект: {id}", id); + + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @" +SELECT * FROM truck +WHERE Id=@id"; + var truck = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(truck)); + + return truck; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; + } + } + + public IEnumerable ReadTrucks() + { + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM truck"; + var trucks = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(trucks)); + return trucks; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } -- 2.25.1 From 2ef7829897f738374df2174993027f79cb4842dc Mon Sep 17 00:00:00 2001 From: Baryshev Dmitry Date: Tue, 17 Dec 2024 19:58:30 +0400 Subject: [PATCH 6/6] done --- ProjectGarage/Entities/Driver.cs | 4 +- ProjectGarage/Entities/FuelReplenishment.cs | 4 +- ProjectGarage/Forms/FormDriver.cs | 5 +- ProjectGarage/Forms/FormDrivers.Designer.cs | 6 +- ProjectGarage/Forms/FormDrivers.cs | 3 +- ProjectGarage/Forms/FormFuel.cs | 2 + ProjectGarage/Forms/FormReplenishment.cs | 12 +-- ProjectGarage/Forms/FormRoute.cs | 1 + ProjectGarage/Forms/FormRoutes.cs | 17 +++- ProjectGarage/Program.cs | 2 +- .../Implementations/DriverRepository.cs | 10 +-- .../Implementations/FuelRepository.cs | 6 +- .../ReplenishmentRepository.cs | 87 +++++++++++++++++-- 13 files changed, 124 insertions(+), 35 deletions(-) diff --git a/ProjectGarage/Entities/Driver.cs b/ProjectGarage/Entities/Driver.cs index c8d2711..f5a5131 100644 --- a/ProjectGarage/Entities/Driver.cs +++ b/ProjectGarage/Entities/Driver.cs @@ -17,14 +17,14 @@ public class Driver public int TruckId { get;private set; } - public static Driver CreateDriver(int id, string fname, string lname, int tryckid) + public static Driver CreateDriver(int id, string fname, string lname, int truckid) { return new Driver { Id = id, Fname = fname, Lname = lname, - TruckId = tryckid + TruckId = truckid }; } } diff --git a/ProjectGarage/Entities/FuelReplenishment.cs b/ProjectGarage/Entities/FuelReplenishment.cs index ed5fdca..fbc4b34 100644 --- a/ProjectGarage/Entities/FuelReplenishment.cs +++ b/ProjectGarage/Entities/FuelReplenishment.cs @@ -10,7 +10,7 @@ public class FuelReplenishment { public int Id { get; private set; } public int DriverId { get; private set; } - public DateTime Date { get; private set; } + public DateTime ReplenishmentDate { get; private set; } public IEnumerable FuelFuelReplenishments { get; private set;} = []; public static FuelReplenishment CreateOpeartion(int id, int driverId, IEnumerable fuelFuelReplenishments) @@ -19,7 +19,7 @@ public class FuelReplenishment { Id = id, DriverId = driverId, - Date = DateTime.Now, + ReplenishmentDate = DateTime.Now, FuelFuelReplenishments = fuelFuelReplenishments }; } diff --git a/ProjectGarage/Forms/FormDriver.cs b/ProjectGarage/Forms/FormDriver.cs index 6d5a6f8..75dae1f 100644 --- a/ProjectGarage/Forms/FormDriver.cs +++ b/ProjectGarage/Forms/FormDriver.cs @@ -16,6 +16,7 @@ namespace ProjectGarage.Forms public partial class FormDriver : Form { private readonly IDriverRepository _driverRepository; + private int? _driverId; public int Id @@ -32,7 +33,7 @@ namespace ProjectGarage.Forms } textBoxFirstName.Text = driver.Fname; textBoxLastName.Text = driver.Lname; - //comboBoxTruckID.SelectedItem = driver.TruckId; + comboBoxTruckID.SelectedItem = driver.TruckId; _driverId = value; } catch (Exception ex) @@ -81,6 +82,6 @@ namespace ProjectGarage.Forms private void ButtonCancelDriver_Click(object sender, EventArgs e) => Close(); private Driver CreateDriver(int id) => Driver.CreateDriver(id, textBoxFirstName.Text, - textBoxLastName.Text, (int)comboBoxTruckID.SelectedIndex!); + textBoxLastName.Text, (int)comboBoxTruckID.SelectedIndex); } } diff --git a/ProjectGarage/Forms/FormDrivers.Designer.cs b/ProjectGarage/Forms/FormDrivers.Designer.cs index 6bc5f62..362351c 100644 --- a/ProjectGarage/Forms/FormDrivers.Designer.cs +++ b/ProjectGarage/Forms/FormDrivers.Designer.cs @@ -52,7 +52,7 @@ dataGridViewDrivers.RowHeadersVisible = false; dataGridViewDrivers.RowHeadersWidth = 51; dataGridViewDrivers.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridViewDrivers.Size = new Size(639, 367); + dataGridViewDrivers.Size = new Size(648, 367); dataGridViewDrivers.TabIndex = 3; // // panelFormDriversButtons @@ -61,7 +61,7 @@ panelFormDriversButtons.Controls.Add(buttonDeleteDriver); panelFormDriversButtons.Controls.Add(buttonAddDriver); panelFormDriversButtons.Dock = DockStyle.Right; - panelFormDriversButtons.Location = new Point(639, 0); + panelFormDriversButtons.Location = new Point(648, 0); panelFormDriversButtons.Name = "panelFormDriversButtons"; panelFormDriversButtons.Size = new Size(161, 367); panelFormDriversButtons.TabIndex = 2; @@ -103,7 +103,7 @@ // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(800, 367); + ClientSize = new Size(809, 367); Controls.Add(dataGridViewDrivers); Controls.Add(panelFormDriversButtons); Name = "FormDrivers"; diff --git a/ProjectGarage/Forms/FormDrivers.cs b/ProjectGarage/Forms/FormDrivers.cs index cf1853d..e5fdf57 100644 --- a/ProjectGarage/Forms/FormDrivers.cs +++ b/ProjectGarage/Forms/FormDrivers.cs @@ -105,8 +105,7 @@ namespace ProjectGarage.Forms MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } - id = - Convert.ToInt32(dataGridViewDrivers.SelectedRows[0].Cells["Id"].Value); + id = Convert.ToInt32(dataGridViewDrivers.SelectedRows[0].Cells["Id"].Value); return true; } } diff --git a/ProjectGarage/Forms/FormFuel.cs b/ProjectGarage/Forms/FormFuel.cs index 519935b..2442df5 100644 --- a/ProjectGarage/Forms/FormFuel.cs +++ b/ProjectGarage/Forms/FormFuel.cs @@ -18,6 +18,7 @@ namespace ProjectGarage.Forms public partial class FormFuel : Form { private readonly IFuelRepository _fuelRepository; + private int? _fuelId; public int Id @@ -39,6 +40,7 @@ namespace ProjectGarage.Forms } } textBoxFuelName.Text = fuel.FuelName; + numericUpDownFuelPrice.Value = fuel.Price; _fuelId = value; } catch (Exception ex) diff --git a/ProjectGarage/Forms/FormReplenishment.cs b/ProjectGarage/Forms/FormReplenishment.cs index 8e0ba2a..f928f0a 100644 --- a/ProjectGarage/Forms/FormReplenishment.cs +++ b/ProjectGarage/Forms/FormReplenishment.cs @@ -25,10 +25,10 @@ namespace ProjectGarage.Forms _replenishmentRepository = replenishmentRepository ?? throw new ArgumentNullException(nameof(replenishmentRepository)); comboBoxReplenishmentDriver.DataSource = driverRepository.ReadDrivers(); - comboBoxReplenishmentDriver.DisplayMember = "First_name"; + comboBoxReplenishmentDriver.DisplayMember = "Fname"; comboBoxReplenishmentDriver.ValueMember = "Id"; ColumnFuel.DataSource = fuelRepository.ReadFuels(); - ColumnFuel.DisplayMember = "Name"; + ColumnFuel.DisplayMember = "FuelName"; ColumnFuel.ValueMember = "Id"; } @@ -58,13 +58,13 @@ namespace ProjectGarage.Forms var list = new List(); foreach (DataGridViewRow row in dataGridViewReplenishment.Rows) { - if (row.Cells["ColumnFeed"].Value == null || - row.Cells["ColumnCount"].Value == null) + if (row.Cells["ColumnFuel"].Value == null || + row.Cells["ColumnAmount"].Value == null) { continue; } - list.Add(FuelFuelReplenishment.CreateElement(0, Convert.ToInt32(row.Cells["ColumnFeed"].Value), - Convert.ToInt32(row.Cells["ColumnCount"].Value))); + list.Add(FuelFuelReplenishment.CreateElement(0, Convert.ToInt32(row.Cells["ColumnFuel"].Value), + Convert.ToInt32(row.Cells["ColumnAmount"].Value))); } return list; } diff --git a/ProjectGarage/Forms/FormRoute.cs b/ProjectGarage/Forms/FormRoute.cs index a3207c8..52ea502 100644 --- a/ProjectGarage/Forms/FormRoute.cs +++ b/ProjectGarage/Forms/FormRoute.cs @@ -31,6 +31,7 @@ namespace ProjectGarage.Forms throw new InvalidDataException(nameof(route)); } + textBoxRouteName.Text = route.RouteName; textBoxRouteStart.Text = route.StartP; textBoxRouteFinal.Text = route.FinalP; numericUpDownRouteLen.Value = route.Length; diff --git a/ProjectGarage/Forms/FormRoutes.cs b/ProjectGarage/Forms/FormRoutes.cs index fb519e1..7f7a62a 100644 --- a/ProjectGarage/Forms/FormRoutes.cs +++ b/ProjectGarage/Forms/FormRoutes.cs @@ -53,21 +53,30 @@ namespace ProjectGarage.Forms } - private void ButtonUpdateRoute_Click(object sender, EventArgs e) + private void ButtonDeleteRoute_Click(object sender, EventArgs e) { + if (!TryGetIdentifierFromSelectedRow(out var findId)) + { + return; + } + if (MessageBox.Show("Удалить запись?", "Удаление", + MessageBoxButtons.YesNo) != DialogResult.Yes) + { + return; + } try { - _container.Resolve().ShowDialog(); + _routeRepository.DeleteRoute(findId); LoadList(); } catch (Exception ex) { - MessageBox.Show(ex.Message, "Ошибка при добавлении", + MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void ButtonDeleteRoute_Click(object sender, EventArgs e) + private void ButtonUpdateRoute_Click(object sender, EventArgs e) { if (!TryGetIdentifierFromSelectedRow(out var findId)) { diff --git a/ProjectGarage/Program.cs b/ProjectGarage/Program.cs index b6f110f..7d32e28 100644 --- a/ProjectGarage/Program.cs +++ b/ProjectGarage/Program.cs @@ -33,7 +33,7 @@ namespace ProjectGarage container.RegisterType(); container.RegisterType(); container.RegisterType(); - container.RegisterType(); + container.RegisterType(); container.RegisterType(); diff --git a/ProjectGarage/Repositories/Implementations/DriverRepository.cs b/ProjectGarage/Repositories/Implementations/DriverRepository.cs index 034c2c4..ac99747 100644 --- a/ProjectGarage/Repositories/Implementations/DriverRepository.cs +++ b/ProjectGarage/Repositories/Implementations/DriverRepository.cs @@ -47,17 +47,17 @@ INSERT INTO driver (Fname, Lname, TruckId) VALUES public void UpdateDriver(Driver driver) { _logger.LogInformation("Редактирование объекта"); - _logger.LogDebug("Объект: {json}", - JsonConvert.SerializeObject(driver)); + _logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(driver)); + try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryUpdate = @" UPDATE driver SET -Fname=@Fname, -Lname=@Lname, -TruckId=@TruckId + Fname=@Fname, + Lname=@Lname, + TruckId=@TruckId WHERE Id=@Id"; connection.Execute(queryUpdate, driver); } diff --git a/ProjectGarage/Repositories/Implementations/FuelRepository.cs b/ProjectGarage/Repositories/Implementations/FuelRepository.cs index bdb6ae1..5dedbee 100644 --- a/ProjectGarage/Repositories/Implementations/FuelRepository.cs +++ b/ProjectGarage/Repositories/Implementations/FuelRepository.cs @@ -53,9 +53,9 @@ INSERT INTO fuel (FuelName, FuelType, Price) VALUES var queryUpdate = @" UPDATE fuel SET -FuelName=@FuelName, -FuelType=@Startp, -Price=@Price + FuelName=@FuelName, + FuelType=@FuelType, + Price=@Price WHERE Id=@Id"; connection.Execute(queryUpdate, fuel); } diff --git a/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs b/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs index 09a74d5..6bd66ab 100644 --- a/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs +++ b/ProjectGarage/Repositories/Implementations/ReplenishmentRepository.cs @@ -1,24 +1,101 @@ -using ProjectGarage.Entities; +using Dapper; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json; +using Npgsql; +using ProjectGarage.Entities; using System; using System.Collections.Generic; +using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectGarage.Repositories.Implementations; -public class FuelReplishmentRepository : IReplenishmentRepository +public class ReplenishmentRepository : IReplenishmentRepository { - public void CreateFuelReplenishment(FuelReplenishment fuelReplenishment) + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public ReplenishmentRepository(IConnectionString connectionString, ILogger logger) { + _connectionString = connectionString; + _logger = logger; + } + public void CreateFuelReplenishment(FuelReplenishment replenishment) + { + _logger.LogInformation("Добавление объекта"); + _logger.LogDebug("Объект: {json}", + JsonConvert.SerializeObject(replenishment)); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + using var transaction = connection.BeginTransaction(); + var queryInsert = @" +INSERT INTO fuelreplenishment (DriverId, ReplenishmentDate) +VALUES (@DriverId, @ReplenishmentDate); +SELECT MAX(Id) FROM fuelreplenishment"; + var ReplenishmentId = connection.QueryFirst(queryInsert, replenishment, transaction); + var querySubInsert = @" +INSERT INTO fuel_fuelreplenishment (ReplenishmentId, FuelId, Amount) +VALUES (@ReplenishmentId, @FuelId, @Amount)"; + foreach (var elem in replenishment.FuelFuelReplenishments) + { + connection.Execute(querySubInsert, new + { + ReplenishmentId, + elem.FuelId, + elem.Amount + }, transaction); + } + transaction.Commit(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при добавлении объекта"); + throw; + } } public void DeleteFuelReplenishment(int id) { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект: {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var queryDelete = @" + DELETE FROM fuelreplenishment + WHERE Id=@id"; + connection.Execute(queryDelete, new { id }); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } } - public IEnumerable ReadFuelReplenishment(DateTime? dateForm = null, DateTime? dateTo = null, int? fuelId = null, int? driverId = null, int? routeId = null) +public IEnumerable ReadFuelReplenishment(DateTime? dateForm = null, + DateTime? dateTo = null, int? fuelId = null, int? driverId = null, int? routeId = null) { - return []; + _logger.LogInformation("Получение всех объектов"); + try + { + using var connection = new + NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @"SELECT * FROM fuelreplenishment"; + var replenishments = connection.Query(querySelect); + _logger.LogDebug("Полученные объекты: {json}", + JsonConvert.SerializeObject(replenishments)); + return replenishments; + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при чтении объектов"); + throw; + } } } -- 2.25.1