2024-12-17 19:58:30 +04:00

102 lines
3.5 KiB
C#

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 ReplenishmentRepository : IReplenishmentRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ReplenishmentRepository> _logger;
public ReplenishmentRepository(IConnectionString connectionString, ILogger<ReplenishmentRepository> 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<int>(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<FuelReplenishment> ReadFuelReplenishment(DateTime? dateForm = null,
DateTime? dateTo = null, int? fuelId = null, int? driverId = null, int? routeId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new
NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM fuelreplenishment";
var replenishments = connection.Query<FuelReplenishment>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(replenishments));
return replenishments;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}