using System.Data.SqlClient; using System.Text.Json; using Dapper; using Microsoft.Extensions.Logging; using Npgsql; using ProjectGSM.Entities; using ProjectGSM.Query; namespace ProjectGSM.Repositories.Implementations; public class StatusHistoryRepository : IStatusHistoryRepository { private readonly IConnectionString _connectionString; private readonly ILogger _logger; public StatusHistoryRepository(IConnectionString connectionString, ILogger logger) { _connectionString = connectionString; _logger = logger; } public IEnumerable ReadStatusHistories(DateTime? dateForm = null, DateTime? dateTo = null, int? caseId = null) { _logger.LogInformation("Получение всех объектов"); try { var builder = new QueryBuilder(); if (dateForm.HasValue) { builder.AddCondition("sh.CreatedAt >= @dateForm"); } if (dateTo.HasValue) { builder.AddCondition("sh.CreatedAt <= @dateTo"); } if (caseId.HasValue) { builder.AddCondition("sh.caseid = @caseId"); } using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @$"SELECT sh.*, c.description as CaseDescription FROM status_histories as sh LEFT JOIN cases as c ON c.id = sh.caseid{builder.Build()}"; var statusHistories = connection.Query(querySelect, new { dateForm, dateTo, caseId }); _logger.LogDebug("Полученные объекты: {json}", JsonSerializer.Serialize(statusHistories)); return statusHistories; } catch (Exception ex) { _logger.LogError(ex, "Ошибка при чтении объектов"); throw; } } public void CreateStatusHistory(StatusHistory statusHistory) { _logger.LogInformation("Добавление объекта"); _logger.LogDebug("Объект: {json}", JsonSerializer.Serialize(statusHistory)); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryInsert = @" INSERT INTO status_histories (caseid, status, price, createdat) VALUES (@CaseId, @Status, @Price, @CreatedAt)"; connection.Execute(queryInsert, statusHistory); } catch (Exception ex) { _logger.LogError(ex, "Ошибка при добавлении объекта"); throw; } } public void DeleteStatusHistory(int statusId, int caseId) { _logger.LogInformation("Удаление объекта"); _logger.LogDebug("Идентификаторы: {statusId}, {caseId}", statusId, caseId); try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var queryDelete = @"DELETE FROM status_histories WHERE status = @Status AND caseid = @CaseId"; connection.Execute(queryDelete, new { StatusId = statusId, CaseId = caseId }); } catch (Exception ex) { _logger.LogError(ex, "Ошибка при удалении объекта"); throw; } } }