ПИбд-21. Шипилов Н.С. Лабораторная работа №2 #2

Open
NikitaShipilov wants to merge 2 commits from LabWork_2 into LabWork_1
19 changed files with 14560 additions and 12304 deletions

View File

@ -6,5 +6,6 @@ public enum ContractorFuelType
None = 0,
GasolineAI92 = 1,
GasolineAI95 = 2,
Diesel = 4
Diesel = 4,
MotorOIL = 8,
}

View File

@ -5,5 +5,6 @@ public enum FuelType
None,
GasolineAI92,
GasolineAI95,
Diesel
Diesel,
MotorOIL,
}

View File

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

View File

@ -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> FuelFuelSale { get; private set; } = [];
public static FuelSale CreateFuelSale(int id, int salesPersonId, int shiftId, DateTime saleDate, decimal totalPrice, IEnumerable<FuelFuelSale> fuelFuelSale)
public static FuelSale CreateFuelSale(int id, int salesPersonId, int shiftId, DateTime saleDate, IEnumerable<FuelFuelSale> fuelFuelSale)
{
return new FuelSale
{
@ -17,7 +16,6 @@ public class FuelSale
SalespersonId = salesPersonId,
ShiftId = shiftId,
SaleDate = saleDate,
TotalPrice = totalPrice,
FuelFuelSale = fuelFuelSale
};
}

View File

@ -61,28 +61,28 @@
// toolStripMenuItemSalepersons
//
toolStripMenuItemSalepersons.Name = "toolStripMenuItemSalepersons";
toolStripMenuItemSalepersons.Size = new Size(180, 22);
toolStripMenuItemSalepersons.Size = new Size(144, 22);
toolStripMenuItemSalepersons.Text = "Сотрудники";
toolStripMenuItemSalepersons.Click += toolStripMenuItemSalepersons_Click;
//
// toolStripMenuItemShifts
//
toolStripMenuItemShifts.Name = "toolStripMenuItemShifts";
toolStripMenuItemShifts.Size = new Size(180, 22);
toolStripMenuItemShifts.Size = new Size(144, 22);
toolStripMenuItemShifts.Text = "Смены";
toolStripMenuItemShifts.Click += toolStripMenuItemShifts_Click;
//
// toolStripMenuItemContractors
//
toolStripMenuItemContractors.Name = "toolStripMenuItemContractors";
toolStripMenuItemContractors.Size = new Size(180, 22);
toolStripMenuItemContractors.Size = new Size(144, 22);
toolStripMenuItemContractors.Text = "Поставщики";
toolStripMenuItemContractors.Click += toolStripMenuItemContractors_Click;
//
// toolStripMenuItemFuels
//
toolStripMenuItemFuels.Name = "toolStripMenuItemFuels";
toolStripMenuItemFuels.Size = new Size(180, 22);
toolStripMenuItemFuels.Size = new Size(144, 22);
toolStripMenuItemFuels.Text = "Топливо";
toolStripMenuItemFuels.Click += toolStripMenuItemFuels_Click;
//
@ -96,14 +96,14 @@
// toolStripMenuItemFuelSale
//
toolStripMenuItemFuelSale.Name = "toolStripMenuItemFuelSale";
toolStripMenuItemFuelSale.Size = new Size(180, 22);
toolStripMenuItemFuelSale.Text = "Новая проадажа";
toolStripMenuItemFuelSale.Size = new Size(160, 22);
toolStripMenuItemFuelSale.Text = "Новая продажа";
toolStripMenuItemFuelSale.Click += toolStripMenuItemFuelSale_Click;
//
// toolStripMenuItemContractorFuel
//
toolStripMenuItemContractorFuel.Name = "toolStripMenuItemContractorFuel";
toolStripMenuItemContractorFuel.Size = new Size(180, 22);
toolStripMenuItemContractorFuel.Size = new Size(160, 22);
toolStripMenuItemContractorFuel.Text = "Новая поставка";
toolStripMenuItemContractorFuel.Click += toolStripMenuItemContractorFuel_Click;
//

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -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<IContractorFuelRepository, ContractorFuelRepository>();
container.RegisterType<IContractorRepository, ContractorRepository>();
@ -29,7 +34,21 @@ namespace ProjectGasStation
container.RegisterType<ISalespersonRepository, SalespersonRepository>();
container.RegisterType<IShiftRepository, ShiftRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
}
}

View File

@ -9,7 +9,19 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="8.0.5" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
@ -42,4 +54,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

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

View File

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

View File

@ -1,20 +1,106 @@
using ProjectGasStation.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectGasStation.Entities;
using System.Transactions;
namespace ProjectGasStation.Repositories.Implementations;
public class ContractorFuelRepository : IContractorFuelRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<FuelRepository> _logger;
public ContractorFuelRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<int>(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);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM ContractorFuelFuel
WHERE ContractorFuelId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM ContractorFuel
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<ContractorFuel> 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<ContractorFuel>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(contractorFuels));
return contractorFuels;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

@ -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<FuelRepository> _logger;
public ContractorRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<Contractor>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(contractor));
return contractor;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Contractor> ReadContractors()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Contractor";
var contractors = connection.Query<Contractor>(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;
}
}
}

View File

@ -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<FuelRepository> _logger;
public FuelRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<Fuel>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(fuel));
return fuel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Fuel> ReadFuels()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Fuel";
var fuels = connection.Query<Fuel>(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;
}
}
}

View File

@ -1,19 +1,105 @@
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<FuelRepository> _logger;
public FuelSaleRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<int>(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<FuelSale> 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<FuelSale>(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);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDeleteSub = @"
DELETE FROM FuelFuelSale
WHERE FuelSaleId = @id";
connection.Execute(queryDeleteSub, new { id }, transaction);
var queryDelete = @"
DELETE FROM FuelSale
WHERE Id = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -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<FuelRepository> _logger;
public SalespersonRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<Salesperson>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(salesperson));
return salesperson;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Salesperson> ReadSalespersons()
{
return [];
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Salesperson";
var salespersons = connection.Query<Salesperson>(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;
}
}
}

View File

@ -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<FuelRepository> _logger;
public ShiftRepository(IConnectionString connectionString, ILogger<FuelRepository> 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<Shift>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}",
JsonConvert.SerializeObject(shift));
return shift;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Shift> 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<Shift>(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;
}
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/gas_log.txt",
"rollingInterval": "Day"
}
}
]
}
}