162 lines
6.8 KiB
C#
Raw Normal View History

2024-12-08 13:24:07 +04:00
using ProjectLibrary.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System.Collections.Generic;
using ProjectLibrary.Repositories;
using System.Transactions;
using System.Data.Common;
using ProjectLibrary.Entites;
using ProjectLibrary.Repositores;
2024-12-20 01:07:20 +04:00
using Unity;
2024-11-12 23:13:20 +04:00
namespace ProjectLibrary.Repositories.Implementations
{
public class OrderRepository : IOrderRepository
{
2024-12-08 13:24:07 +04:00
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
2024-11-12 23:13:20 +04:00
{
2024-12-08 13:24:07 +04:00
_connectionString = connectionString;
_logger = logger;
2024-11-20 19:31:06 +04:00
}
2024-12-08 13:24:07 +04:00
// Добавление нового заказа
public void CreateOrder(Orders order)
2024-11-20 19:31:06 +04:00
{
2024-12-08 13:24:07 +04:00
_logger.LogInformation("Добавление нового заказа");
_logger.LogDebug("Заказ: {json}", JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
// Вставляем сам заказ в таблицу Orders
var queryInsertOrder = @"
INSERT INTO Orders (OrderDate, ReturnDate, ReaderID)
VALUES (@OrderDate, @ReturnDate, @ReaderID);
SELECT MAX(Id) FROM Orders"; // Возвращаем ID вставленного заказа
var orderId = connection.QueryFirst<int>(queryInsertOrder, order, transaction);
2024-11-20 19:31:06 +04:00
2024-12-08 13:24:07 +04:00
// Вставляем ассоциации книг с заказом в таблицу Book_Orders
foreach (var bookId in order.BookOrders) // Предполагается, что Order.BookOrders содержит список ID книг
{
var queryInsertBookOrder = @"
2024-12-20 01:07:20 +04:00
INSERT INTO Book_Orders (BookID, OrderID, Count)
VALUES (@BookID, @OrderID, @Count)";
connection.Execute(queryInsertBookOrder, new { bookId.BookID, orderId, bookId.Count }, transaction);
2024-12-08 13:24:07 +04:00
}
transaction.Commit();
_logger.LogInformation("Заказ успешно добавлен с ID={OrderId}", orderId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении заказа");
throw;
}
2024-11-12 23:13:20 +04:00
}
2024-12-08 13:24:07 +04:00
// Удаление заказа
2024-11-12 23:13:20 +04:00
public void DeleteOrder(int id)
{
2024-12-08 13:24:07 +04:00
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var querySubDelete = @"
DELETE FROM Book_Orders
WHERE OrderId=@id";
connection.Execute(querySubDelete, new { id }, transaction);
var queryDelete = @"
DELETE FROM Orders
WHERE Id=@id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
2024-11-12 23:13:20 +04:00
}
2024-12-08 13:24:07 +04:00
// Получение заказа по ID
2024-11-12 23:13:20 +04:00
public Orders ReadOrderById(int id)
{
2024-12-08 13:24:07 +04:00
_logger.LogInformation("Получение заказа по ID={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelectOrder = "SELECT * FROM Orders WHERE ID = @id";
var order = connection.QueryFirstOrDefault<Orders>(querySelectOrder, new { id });
_logger.LogDebug("Найден заказ: {json}", JsonConvert.SerializeObject(order));
return order;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении заказа с ID={id}", id);
throw;
}
2024-11-12 23:13:20 +04:00
}
2024-12-08 13:24:07 +04:00
// Получение всех заказов
2024-12-20 11:52:29 +04:00
public IEnumerable<Orders> ReadOrders(DateTime? StartDate = null, DateTime? EndDate = null)
2024-11-12 23:13:20 +04:00
{
2024-12-08 13:24:07 +04:00
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
2024-12-20 11:52:29 +04:00
var builder = new QueryBuilder();
if(StartDate.HasValue)
{
builder.AddCollerction("ord.OrderDate >= @StartDate");
2024-12-20 15:49:09 +04:00
}
2024-12-20 11:52:29 +04:00
var querySelect = $@"SELECT ord.*,
2024-12-20 15:49:09 +04:00
bk.Name as BookName,
Obo.bookid as bookid
2024-12-20 01:07:20 +04:00
FROM Orders ord
2024-12-20 11:52:29 +04:00
INNER JOIN Book_Orders Obo ON Obo.orderId = ord.Id
Inner join book bk on bk.ID = obo.Bookid
{builder.Build()}";
var OrderBookDict = new Dictionary<int, List<Book_Orders>>();
var order = connection
.Query<Orders, Book_Orders, Orders>(querySelect, (orders, books_orders) =>
{
if (!OrderBookDict.TryGetValue(orders.Id, out var Book_Orders))
{
Book_Orders = [];
OrderBookDict.Add(orders.Id, Book_Orders);
}
Book_Orders.Add(books_orders);
return orders;
},
splitOn: "bookid", param: new { StartDate, EndDate });
2024-12-20 01:07:20 +04:00
_logger.LogDebug("Получ енные объекты: {json}", JsonConvert.SerializeObject(order));
2024-12-20 11:52:29 +04:00
return OrderBookDict.Select(x =>
{
var or = order.First(y => y.Id == x.Key);
or.SetOrdersOfBooks(x.Value);
return or;
}).ToArray();
2024-12-08 13:24:07 +04:00
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
2024-11-12 23:13:20 +04:00
}
}
}