120 lines
4.9 KiB
C#
120 lines
4.9 KiB
C#
using Dapper;
|
||
using Microsoft.Extensions.Logging;
|
||
using Newtonsoft.Json;
|
||
using Npgsql;
|
||
using ProjectAtelier.Entities;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
|
||
namespace ProjectAtelier.Repositories.Implementations;
|
||
|
||
public class OrderRepository : IOrderRepository
|
||
{
|
||
private readonly IConnectionString _connectionString;
|
||
private readonly ILogger<ProductRepository> _logger;
|
||
public OrderRepository(IConnectionString connectionString, ILogger<ProductRepository> logger)
|
||
{
|
||
_connectionString = connectionString;
|
||
_logger = logger;
|
||
}
|
||
public void CreateOrder(Order order)
|
||
{
|
||
_logger.LogInformation("Добавление объекта");
|
||
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(order));
|
||
try
|
||
{
|
||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); ///Создается объект NpgsqlConnection с использованием строки подключения из _connectionString.
|
||
connection.Open(); ////открытие соединения
|
||
using var transaction = connection.BeginTransaction(); ///начинаем транзакцию
|
||
///Выполнение запросов в рамках транзакции:
|
||
var queryInsert = @"
|
||
INSERT INTO Orders (DataTime, Status, Characteristic, IdClient)
|
||
VALUES (@DataTime, @Status, @Characteristic, @IdClient);
|
||
SELECT MAX(Id) FROM Orders";
|
||
var orderId = connection.QueryFirst<int>(queryInsert, order, transaction);
|
||
var querySubInsert = @"
|
||
INSERT INTO Order_Products (OrderId, ProductId, Count)
|
||
VALUES (@OrderId, @ProductId, @Count)";
|
||
foreach (var elem in order.OrderProduct)
|
||
{
|
||
connection.Execute(querySubInsert, new
|
||
{
|
||
orderId,
|
||
elem.ProductId,
|
||
elem.Count
|
||
}, transaction);///добавляем в транзакцию зпросы
|
||
}
|
||
transaction.Commit(); ///Если все запросы выполнены успешно, транзакция фиксируется с помощью метода
|
||
}
|
||
catch (Exception ex)/// исключение логируется.
|
||
{
|
||
_logger.LogError(ex, "Ошибка при добавлении объекта");
|
||
throw;
|
||
}
|
||
}
|
||
|
||
public void DeleteOrder(int id)
|
||
{
|
||
_logger.LogInformation("Удаление объекта");
|
||
_logger.LogDebug("Объект: {id}", id);
|
||
try
|
||
{
|
||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||
var queryDelete = @"
|
||
DELETE FROM Orders
|
||
WHERE Id=@id";
|
||
connection.Execute(queryDelete, new { id });
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Ошибка при удалении объекта");
|
||
throw;
|
||
}
|
||
}
|
||
|
||
public IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderStatus = null, int? orderId = null)
|
||
{
|
||
_logger.LogInformation("Получение всех объектов");
|
||
try
|
||
{
|
||
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
|
||
var querySelect = @"
|
||
SELECT orders.*, products.id AS productid, products.name AS productname, op.count AS count
|
||
FROM orders
|
||
INNER JOIN order_products AS op ON orders.id = op.orderid
|
||
INNER JOIN products ON op.productid = products.id";
|
||
|
||
var productsDict = new Dictionary<int, List<OrderProduct>>();
|
||
|
||
var products =
|
||
connection.Query<Order, OrderProduct, Order>(querySelect, (order, orderProducts) =>
|
||
{
|
||
if (!productsDict.TryGetValue(order.Id, out var frr))
|
||
{
|
||
frr = [];
|
||
productsDict.Add(order.Id, frr);
|
||
}
|
||
frr.Add(orderProducts);
|
||
return order;
|
||
}, splitOn: "productid", param: new { dateForm, dateTo, orderStatus, orderId });
|
||
|
||
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
|
||
|
||
return productsDict.Select(x =>
|
||
{
|
||
var fr = products.First(y => y.Id == x.Key);
|
||
fr.SetProductMaterial(x.Value);
|
||
return fr;
|
||
}).ToArray();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_logger.LogError(ex, "Ошибка при чтении объектов");
|
||
throw;
|
||
}
|
||
}
|
||
}
|