diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/AccessoiresOrder.cs b/ProjectCompRepair/ProjectCompRepair/Entities/AccessoiresOrder.cs index bac8c0c..358c18a 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/AccessoiresOrder.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/AccessoiresOrder.cs @@ -1,23 +1,24 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectCompRepair.Entities.Enums; namespace ProjectCompRepair.Entities; public class AccessoiresOrder { + public int OrderId { get; private set; } - public int AccessoriesId { get; private set; } - public int Count { get; private set; } public static AccessoiresOrder CreateElement(int orderId, int count, int accessoriesId) { - return new AccessoiresOrder { OrderId = orderId, Count = count, AccessoriesId = accessoriesId }; + return new AccessoiresOrder { OrderId = orderId, Count = count, AccessoriesId = accessoriesId}; } } diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs index 382ccc8..49d5c27 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Accessories.cs @@ -1,6 +1,7 @@ using ProjectCompRepair.Entities.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -11,12 +12,16 @@ public class Accessories { public int Id { get; private set; } + [DisplayName("Тип комплектующих")] public AccessoriesType AccessoriesType { get; private set; } - + + [DisplayName("Количество комплектующих")] public int Count { get; private set; } + [DisplayName("Цена")] public float Price { get; private set; } + [DisplayName("Дата")] public DateTime Date { get; private set; } public static Accessories CreateEntity(int id, AccessoriesType accessoriesType, int count, float price, DateTime date) diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Master.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Master.cs index 10df4ab..37f2682 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Master.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Master.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,6 +10,7 @@ namespace ProjectCompRepair.Entities; public class Master { public int Id { get; private set; } + [DisplayName("Имя")] public string Name { get; private set; } public static Master CreateEntity(int id, string name) diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs index 629c590..5c94855 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Order.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; +using ProjectCompRepair.Entities.Enums; namespace ProjectCompRepair.Entities; @@ -10,24 +12,41 @@ public class Order { public int Id { get; private set; } + [DisplayName("Имя")] public string Name { get; private set; } + [DisplayName("Комментарий")] public string Coment { get; private set; } + [DisplayName("Дата")] + public DateTime Date { get; private set; } - public DateTime Date { get; private set; } - + [Browsable(false)] public int MasterID { get; private set; } + [DisplayName("Имя мастера")] + public string MasterName { get; private set; } = string.Empty; + [Browsable(false)] + public AccessoriesType AccessoriesType { get; private set; } + [Browsable(false)] + public ServiceType ServiceType { get; private set; } + [DisplayName("Комплектующие")] + public string Accessories => AccessoiresOrders != null ? + string.Join(", ", AccessoiresOrders.Select(x => $"{AccessoriesType} {x.Count}")) : + string.Empty; + [Browsable(false)] public IEnumerable AccessoiresOrders { get; private set; } = []; - + [DisplayName("Услуги")] + + public string Services => ServicesOrders != null ? + string.Join(", ", ServicesOrders.Select(x => $"{ServiceType} {x.Count}")) : + string.Empty; + [Browsable(false)] public IEnumerable ServicesOrders { get; private set; } = []; - - public static Order CreateElement(int id, string name,DateTime date, string coment, int masterId, IEnumerable accessoiresOrders, IEnumerable servicesOrder) { return new Order() { - Id = id, + Id = id, Name = name, Coment = coment, Date = date, @@ -37,18 +56,21 @@ public class Order }; } - public static Order CreateElement(TempAccessoriesOrder tempAccessoriesOrder, IEnumerable accessoiresOrder) + + public void SetOrder(IEnumerable +accessoiresOrder) { - return new Order + if (accessoiresOrder != null && accessoiresOrder.Any()) { - Id = tempAccessoriesOrder.Id, - Name = tempAccessoriesOrder.Name, - Coment = tempAccessoriesOrder.Coment, - Date = tempAccessoriesOrder.Date, - MasterID = tempAccessoriesOrder.MasterID, - AccessoiresOrders = accessoiresOrder, - ServicesOrders = tempAccessoriesOrder.ServicesOrders - - }; + AccessoiresOrders = accessoiresOrder; + } + } + public void SetOrder(IEnumerable +servicesOrder) + { + if (servicesOrder != null && servicesOrder.Any()) + { + ServicesOrders = servicesOrder; + } } } diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs b/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs index c622af7..bd3d323 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/Service.cs @@ -1,6 +1,7 @@ using ProjectCompRepair.Entities.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,9 +11,9 @@ namespace ProjectCompRepair.Entities; public class Service { public int Id { get; private set; } - + [DisplayName("Тип услуги")] public ServiceType ServiceType { get; private set; } - + [DisplayName("Цена")] public float Price { get; private set; } public static Service CreateEntity(int id, ServiceType serviceType, float price) diff --git a/ProjectCompRepair/ProjectCompRepair/Entities/ServicesOrder.cs b/ProjectCompRepair/ProjectCompRepair/Entities/ServicesOrder.cs index d284ead..29402fe 100644 --- a/ProjectCompRepair/ProjectCompRepair/Entities/ServicesOrder.cs +++ b/ProjectCompRepair/ProjectCompRepair/Entities/ServicesOrder.cs @@ -8,14 +8,17 @@ namespace ProjectCompRepair.Entities; public class ServicesOrder { - public int Id { get; private set; } + public int ServiceId { get; private set; } public int OrderId { get; private set; } + + + public string ServiceName { get; private set; } = string.Empty; public int Count { get; private set; } - public static ServicesOrder CreateElement(int id, int orderId, int count) + public static ServicesOrder CreateElement(int serviceId, int orderId, int count) { - return new ServicesOrder { Id = id, OrderId = orderId, Count = count }; + return new ServicesOrder { ServiceId = serviceId, OrderId = orderId, Count = count }; } } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessories.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessories.cs index 0827de5..f54a1a1 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessories.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessories.cs @@ -96,7 +96,12 @@ namespace ProjectCompRepair.Forms } } - private void LoadList() => dataGridView.DataSource = _accessoriesRepository.ReadAccessories(); + private void LoadList() + { + dataGridView.DataSource = _accessoriesRepository.ReadAccessories(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["Date"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesOrderReport.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesOrderReport.cs index ccebd9f..371e900 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesOrderReport.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesOrderReport.cs @@ -1,14 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using ProjectCompRepair.Entities; -using ProjectCompRepair.Reports; +using ProjectCompRepair.Reports; using ProjectCompRepair.Repositories; using Unity; @@ -23,11 +13,10 @@ namespace ProjectCompRepair.Forms public FormAccessoriesOrderReport(IUnityContainer container, IAccessoriesRepository accessoriesRepository) { InitializeComponent(); - _container = container ?? - throw new ArgumentNullException(nameof(container)); + _container = container ?? throw new ArgumentNullException(nameof(container)); comboBoxAccessories.DataSource = accessoriesRepository.ReadAccessories(); - comboBoxAccessories.ValueMember = "Id"; comboBoxAccessories.DisplayMember = "AccessoriesType"; + comboBoxAccessories.ValueMember = "Id"; } @@ -51,11 +40,11 @@ namespace ProjectCompRepair.Forms { if (string.IsNullOrWhiteSpace(_fileName)) { - throw new Exception("Отсутствует имя файла для отчета"); + throw new Exception("Отсутствует имя файла для отчета"); } - if - (_container.Resolve().CreateChart(_fileName, dateTimePicker.Value, (int)comboBoxAccessories.SelectedValue!)) + if (_container.Resolve().CreateChart(_fileName, dateTimePicker.Value, + (int)comboBoxAccessories.SelectedValue!, comboBoxAccessories.Text)) { MessageBox.Show("Документ сформирован", "Формирование документа", @@ -64,8 +53,8 @@ namespace ProjectCompRepair.Forms } else { - MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", - + MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", + "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesReport.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesReport.cs index 89e8a50..5010ba7 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesReport.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormAccessoriesReport.cs @@ -21,7 +21,7 @@ public partial class FormAccessoriesReport : Form InitializeComponent(); _container = container ?? throw new ArgumentNullException(nameof(container)); comboBoxAccessories.DataSource = accessoriesRepository.ReadAccessories(); - comboBoxAccessories.DisplayMember = "Name"; + comboBoxAccessories.DisplayMember = "AccessoriesType"; comboBoxAccessories.ValueMember = "Id"; } @@ -59,7 +59,7 @@ public partial class FormAccessoriesReport : Form throw new Exception("Дата начала должна быть раньше даты окончания"); } - if (_container.Resolve().CreateTable(textBoxFilePath.Text, (int)comboBoxAccessories.SelectedValue!, dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value)) + if (_container.Resolve().CreateTable(textBoxFilePath.Text, (int)comboBoxAccessories.SelectedValue!, dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value, comboBoxAccessories.Text)) { MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information); } diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormMasters.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormMasters.cs index be8f989..22f6e7e 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormMasters.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormMasters.cs @@ -92,7 +92,11 @@ namespace ProjectCompRepair.Forms } } - private void LoadList() => dataGridView.DataSource = _masterRepository.ReadMaster(); + private void LoadList() + { + dataGridView.DataSource = _masterRepository.ReadMaster(); + dataGridView.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs index a0eef5a..6bf39c6 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrder.cs @@ -109,8 +109,8 @@ public partial class FormOrder : Form { continue; } - list.Add(ServicesOrder.CreateElement(0, - Convert.ToInt32(row.Cells["ColumnService"].Value), + list.Add(ServicesOrder.CreateElement(Convert.ToInt32(row.Cells["ColumnService"].Value), + 0, Convert.ToInt32(row.Cells["ColumnCountServ"].Value))); } return list; diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.cs index 589bda8..871102d 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormOrders.cs @@ -93,7 +93,13 @@ public partial class FormOrders : Form } } - private void LoadList() => dataGridView.DataSource = _orderRepository.ReadOrder(); + private void LoadList() + { + dataGridView.DataSource = _orderRepository.ReadOrder(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["Date"].DefaultCellStyle.Format = +"dd.MM.yy"; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs b/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs index afdd8aa..7a2a43b 100644 --- a/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs +++ b/ProjectCompRepair/ProjectCompRepair/Forms/FormServices.cs @@ -92,7 +92,11 @@ namespace ProjectCompRepair.Forms } } - private void LoadList() => dataGridView.DataSource = _serviceRepository.ReadService(); + private void LoadList() + { + dataGridView.DataSource = _serviceRepository.ReadService(); + dataGridView.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectCompRepair/ProjectCompRepair/Reports/ChartReport.cs b/ProjectCompRepair/ProjectCompRepair/Reports/ChartReport.cs index fdb7d9a..62b9935 100644 --- a/ProjectCompRepair/ProjectCompRepair/Reports/ChartReport.cs +++ b/ProjectCompRepair/ProjectCompRepair/Reports/ChartReport.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Logging; using ProjectCompRepair.Entities; +using ProjectCompRepair.Entities.Enums; using ProjectCompRepair.Repositories; using ProjectCompRepair.Repositories.Implemantations; using RegistrationOfPatients.Reports; @@ -22,13 +23,13 @@ internal class ChartReport _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } - public bool CreateChart(string filePath, DateTime dateTime, int accessoriesId) + public bool CreateChart(string filePath, DateTime dateTime, int accessoriesId, string accessoriesType) { try { new PdfBuilder(filePath) .AddHeader("Комплектующие") - .AddPieChart("потраченные комплектующие", GetData(dateTime, accessoriesId)) + .AddPieChart($"потраченные комплектующие типа {accessoriesType.ToString()} за {dateTime : dd.MM.yyyy}", GetData(dateTime, accessoriesId)) .Build(); return true; } @@ -42,14 +43,14 @@ internal class ChartReport private List<(string Caption, double Value)> GetData(DateTime dateTime, int accessoriesId) { return _orderRepository - .ReadOrder() - .Where(x => x.Date.Date == dateTime.Date && x.AccessoiresOrders.Any(y => y.AccessoriesId == accessoriesId)) - .GroupBy(x => x.Id, (key, group) => new + .ReadOrder(dateTo: dateTime.Date.AddDays(1), accessoriesId: accessoriesId) + .GroupBy(x => x.Name, (key, group) => new { - Id = key, + Name = key, Count = group.Sum(x => x.AccessoiresOrders.FirstOrDefault(y => y.AccessoriesId == accessoriesId)?.Count ?? 0) }) - .Select(x => (x.Id.ToString(), (double)x.Count)) + .Select(x => (x.Name.ToString(), (double)x.Count)) .ToList(); } + } \ No newline at end of file diff --git a/ProjectCompRepair/ProjectCompRepair/Reports/TableReport.cs b/ProjectCompRepair/ProjectCompRepair/Reports/TableReport.cs index a155dd6..cb8ec53 100644 --- a/ProjectCompRepair/ProjectCompRepair/Reports/TableReport.cs +++ b/ProjectCompRepair/ProjectCompRepair/Reports/TableReport.cs @@ -25,13 +25,13 @@ internal class TableReport _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } - public bool CreateTable(string filePath, int accessoriesId, DateTime startDate, DateTime endDate) + public bool CreateTable(string filePath, int accessoriesId, DateTime startDate, DateTime endDate, string accessoriesType) { try { new ExcelBuilder(filePath) - .AddHeader("Поставка комплектующих", 0, 3) - .AddParagraph("за период", 0) + .AddHeader($"Поставка комплектующих {accessoriesType}", 0, 3) + .AddParagraph($"за период {startDate: dd.MM.yyyy} по {endDate: dd.MM.yyyy}", 0) .AddTable([10, 15, 15], GetData(accessoriesId, startDate, endDate)) .Build(); return true; @@ -45,8 +45,7 @@ internal class TableReport private List GetData(int accessoriesId, DateTime startDate, DateTime endDate) { - var data = _orderRepository.ReadOrder() - .Where(x => x.Date >= startDate && x.Date <= endDate && x.AccessoiresOrders.Any(y => y.AccessoriesId == accessoriesId)) + var data = _orderRepository.ReadOrder(dateForm: startDate, dateTo : endDate, accessoriesId : accessoriesId) .Select(x => new {Date = x.Date, CountIn = (int?)null, CountOut = x.AccessoiresOrders.FirstOrDefault(y => y.AccessoriesId == accessoriesId)?.Count, }) .Union( _accessoriesRepository @@ -58,9 +57,9 @@ internal class TableReport return new List() { item } .Union( data - .Select(x => new string[] { x.Date.ToString("yyyy-MM-dd"), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty })) + .Select(x => new string[] { x.Date.ToString("yyyy-MM-dd"), x.CountIn?.ToString("N0") ?? string.Empty, x.CountOut?.ToString("N0") ?? string.Empty })) .Union( - [["Всего", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]]) + [["Всего", data.Sum(x => x.CountIn ?? 0).ToString("N0"), data.Sum(x => x.CountOut ?? 0).ToString("N0")]]) .ToList(); } } diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs index e058770..3269656 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/IOrderRepository.cs @@ -11,7 +11,7 @@ namespace ProjectCompRepair.Repositories; public interface IOrderRepository { - IEnumerable ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null, int? serviceId = null); + IEnumerable ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null); Order ReadOrderById(int id); diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs index be49c08..e49d9ad 100644 --- a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/OrderRepository.cs @@ -11,17 +11,17 @@ namespace ProjectCompRepair.Repositories.Implemantations; - public class OrderRepository : IOrderRepository +public class OrderRepository : IOrderRepository +{ + private readonly IConnectionString _connectionString; + + private readonly ILogger _logger; + + public OrderRepository(IConnectionString connectionString, ILogger logger) { - private readonly IConnectionString _connectionString; - - private readonly ILogger _logger; - - public OrderRepository(IConnectionString connectionString, ILogger logger) - { - _connectionString = connectionString; - _logger = logger; - } + _connectionString = connectionString; + _logger = logger; + } public void CreateOrder(Order order) { _logger.LogInformation("Добавление объекта"); @@ -37,7 +37,7 @@ VALUES (@Name, @Coment, @Date, @MasterId); SELECT MAX(ID) FROM Orderl"; - + var orderId = connection.QueryFirst(queryInsert, order, transaction); var querySubInsertAccessories = @" @@ -47,7 +47,7 @@ foreach (var elem in order.AccessoiresOrders) { connection.Execute(querySubInsertAccessories, new - { + { elem.AccessoriesId, orderId, elem.Count @@ -55,13 +55,14 @@ } var querySubInsertServices = @" - INSERT INTO ServicesOrder (OrderId, Count) - VALUES (@OrderId, @Count)"; + INSERT INTO ServicesOrder (ServiceId, OrderId, Count) + VALUES (@ServiceId, @OrderId, @Count)"; foreach (var elem in order.ServicesOrders) { connection.Execute(querySubInsertServices, new { + elem.ServiceId, OrderId = orderId, elem.Count }, transaction); @@ -75,80 +76,145 @@ throw; } } - - public void DeleteOrder(int id) - { - _logger.LogInformation("Удаление объекта"); - _logger.LogDebug("Объект : {id}", id); - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); - var queryDelete = @" + public void DeleteOrder(int id) + { + _logger.LogInformation("Удаление объекта"); + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var queryDelete = @" DELETE FROM Orderl WHERE ID = @id " - ; - connection.Execute(queryDelete, new { id }); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при удалении объекта"); - throw; - } +; + connection.Execute(queryDelete, new { id }); } - public Order ReadOrderById(int id) + catch (Exception ex) { - _logger.LogInformation("Получение объекта по идентификатору"); - _logger.LogDebug("Объект : {id}", id); - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); + _logger.LogError(ex, "Ошибка при удалении объекта"); + throw; + } + } + public Order ReadOrderById(int id) + { + _logger.LogInformation("Получение объекта по идентификатору"); - var querySelect = @" + + _logger.LogDebug("Объект : {id}", id); + try + { + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @" SELECT * FROM Orderl WHERE ID = @id "; - var order = connection.QueryFirst(querySelect, new { id }); - _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(order)); - return order; - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка при поиске объекта"); - throw; - } + var order = connection.QueryFirst(querySelect, new { id }); + _logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(order)); + return order; } - - public IEnumerable ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null, int? serviceId = null) + catch (Exception ex) { - _logger.LogInformation("Получение всех объектов"); - try - { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - connection.Open(); - - var querySelect = @"SELECT o.*, ao.AccessoriesId, ao.Count -FROM Orderl o -INNER JOIN AccessoriesOrder ao ON ao.OrderId = o.ID;"; - var order = connection.Query(querySelect); - _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(order)); - return order.GroupBy(x => x.Id, y => y, - (key, value) => Order.CreateElement(value.First(), - value.Select(z => AccessoiresOrder.CreateElement(0, z.Count, z.AccessoriesId)))).ToList(); + _logger.LogError(ex, "Ошибка при поиске объекта"); + throw; } - catch (Exception ex) + } + + public IEnumerable ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null) + { + + + + _logger.LogInformation("Получение всех объектов"); + try + { + var builder = new QueryBuilder(); + if (dateForm.HasValue) { - _logger.LogError(ex, "Ошибка при чтении объектов"); - throw; + builder.AddCondition("a.Date >= @dateForm"); } + if (dateTo.HasValue) + { + builder.AddCondition("o.Date <= @dateTo"); + } + if (masterId.HasValue) + { + builder.AddCondition("m.masterId = @masterId"); + } + if (accessoriesId.HasValue) + { + builder.AddCondition("ao.AccessoriesId = @accessoriesId"); + } + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + connection.Open(); + + var querySelect = @$" +SELECT + o.*, + m.Name as MasterName, + a.AccessoriesType as AccessoriesType, + s.ServiceType as ServiceType, + ao.AccessoriesId, + ao.Count as Count, + so.ServiceId, + so.Count as Count +FROM Orderl o +INNER JOIN AccessoriesOrder ao ON ao.OrderId = o.ID +INNER JOIN ServicesOrder so ON so.OrderId = o.ID +LEFT JOIN Master m ON m.Id = o.MasterId +LEFT JOIN Accessories a ON a.Id = ao.AccessoriesId +LEFT JOIN Service s ON s.Id = so.ServiceId +{builder.Build()};"; + + var accessoriesDict = new Dictionary>(); + var servicesDict = new Dictionary>(); + + var orders = connection.Query(querySelect, + (order, accessoriesOrder, servicesOrder) => + { + + if (!accessoriesDict.TryGetValue(order.Id, out var aoList)) + { + aoList = new List(); + accessoriesDict.Add(order.Id, aoList); + } + aoList.Add(accessoriesOrder); + + + if (!servicesDict.TryGetValue(order.Id, out var soList)) + { + soList = new List(); + servicesDict.Add(order.Id, soList); + } + soList.Add(servicesOrder); + + return order; + }, splitOn: "AccessoriesId,ServiceId", param :new { dateForm, dateTo, masterId, accessoriesId }); + + _logger.LogDebug("Полученные объекты : {json}", JsonConvert.SerializeObject(orders)); + + return orders.Select(order => + { + if (accessoriesDict.TryGetValue(order.Id, out var aoList)) + { + order.SetOrder(aoList); + } + if (servicesDict.TryGetValue(order.Id, out var soList)) + { + order.SetOrder(soList); + } + return order; + }).ToArray(); } - - - - - - + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка при получении объектов"); + throw; + } + } } diff --git a/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/QueryBuilder.cs b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/QueryBuilder.cs new file mode 100644 index 0000000..323717f --- /dev/null +++ b/ProjectCompRepair/ProjectCompRepair/Repositories/Implemantations/QueryBuilder.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectCompRepair.Repositories.Implemantations; + +internal class QueryBuilder +{ + private readonly StringBuilder _builder; + + public QueryBuilder() + { + _builder = new(); + } + + public QueryBuilder AddCondition(string condition) + { + if (_builder.Length > 0) + { + _builder.Append(" AND "); + } + + _builder.Append(condition); + + return this; + } + + public string Build() + { + if (_builder.Length == 0) + { + return string.Empty; + } + + return $"WHERE {_builder}"; + } +}