using System.Data.SqlClient; using System.Text.Json; using Dapper; using Microsoft.Extensions.Logging; using Npgsql; using ProjectGSM.Entities; namespace ProjectGSM.Repositories.Implementations; public class CaseRepository : ICaseRepository { private readonly IConnectionString _connectionString; private readonly ILogger _logger; public CaseRepository(IConnectionString connectionString, ILogger logger) { _connectionString = connectionString; _logger = logger; } public IEnumerable ReadCases() { _logger.LogInformation("Получение всех объектов"); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = "SELECT * FROM cases"; var cases = connection.Query(querySelect); _logger.LogDebug("Полученные объекты: {json}", JsonSerializer.Serialize(cases)); return cases; } catch (Exception ex) { _logger.LogError(ex, "Ошибка при чтении объектов"); throw; } } public Case ReadCaseById(int id) { _logger.LogInformation("Получение объекта по идентификатору"); _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @"SELECT * FROM cases WHERE Id=@id"; var caseE = connection.QueryFirst(querySelect, new { id }); _logger.LogDebug("Найденный объект: {json}", JsonSerializer.Serialize(caseE)); return caseE; } catch (Exception ex) { _logger.LogError(ex, "Ошибка при поиске объекта"); throw; } } public void CreateCase(Case caseEntity) { _logger.LogInformation("Добавление объекта"); _logger.LogDebug("Объект: {json}", JsonSerializer.Serialize(caseEntity)); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); connection.Open(); using var transaction = connection.BeginTransaction(); var queryInsert = @"INSERT INTO Cases (typeappeal, Payment, Price, victoryprice, Verdict, courtid, clientid, Description, createdat) VALUES (@TypeAppeal, @Payment, @Price, @VictoryPrice, @Verdict, @CourtId, @ClientId, @Description, @CreatedAt); SELECT MAX(Id) FROM cases;"; var caseId = connection.QueryFirst(queryInsert, caseEntity, transaction); var querySubInsert = @" INSERT INTO case_advocates (caseid, advocateid, post, createdat) VALUES (@CaseId, @AdvocateId, @Post, @CreatedAt)"; foreach (var elem in caseEntity.Advocates) { connection.Execute(querySubInsert, new { caseId, elem.AdvocateId, elem.Post, elem.CreatedAt }, transaction); } transaction.Commit(); } catch (Exception ex) { _logger.LogError(ex, "Ошибка при добавлении объекта"); throw; } } public void DeleteCase(int id) { _logger.LogInformation("Удаление объекта"); _logger.LogDebug("Объект: {id}", id); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryDelete = @"DELETE FROM cases WHERE id = @Id;"; connection.Execute(queryDelete, new { Id = id }); } catch (Exception ex) { _logger.LogError(ex, "Ошибка при удалении объекта"); throw; } } }