ПИбд-23. Кадышев М.И. Лабораторная работа 4 #4
@ -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};
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -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<AccessoiresOrder> AccessoiresOrders { get; private set; } = [];
|
||||
|
||||
[DisplayName("Услуги")]
|
||||
|
||||
public string Services => ServicesOrders != null ?
|
||||
string.Join(", ", ServicesOrders.Select(x => $"{ServiceType} {x.Count}")) :
|
||||
string.Empty;
|
||||
[Browsable(false)]
|
||||
public IEnumerable<ServicesOrder> ServicesOrders { get; private set; } = [];
|
||||
|
||||
|
||||
public static Order CreateElement(int id, string name,DateTime date, string coment, int masterId, IEnumerable<AccessoiresOrder> accessoiresOrders, IEnumerable<ServicesOrder> 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> accessoiresOrder)
|
||||
|
||||
public void SetOrder(IEnumerable<AccessoiresOrder>
|
||||
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>
|
||||
servicesOrder)
|
||||
{
|
||||
if (servicesOrder != null && servicesOrder.Any())
|
||||
{
|
||||
ServicesOrders = servicesOrder;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
|
@ -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 };
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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<ChartReport>().CreateChart(_fileName, dateTimePicker.Value, (int)comboBoxAccessories.SelectedValue!))
|
||||
if (_container.Resolve<ChartReport>().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);
|
||||
}
|
||||
|
@ -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<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxAccessories.SelectedValue!, dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value))
|
||||
if (_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text, (int)comboBoxAccessories.SelectedValue!, dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value, comboBoxAccessories.Text))
|
||||
{
|
||||
MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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;
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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();
|
||||
}
|
||||
|
||||
}
|
@ -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<string[]> 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<string[]>() { 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();
|
||||
}
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ namespace ProjectCompRepair.Repositories;
|
||||
|
||||
public interface IOrderRepository
|
||||
{
|
||||
IEnumerable<Order> ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null, int? serviceId = null);
|
||||
IEnumerable<Order> ReadOrder(DateTime? dateForm = null, DateTime? dateTo = null, int? masterId = null, int? accessoriesId = null);
|
||||
|
||||
Order ReadOrderById(int id);
|
||||
|
||||
|
@ -11,17 +11,17 @@
|
||||
|
||||
namespace ProjectCompRepair.Repositories.Implemantations;
|
||||
|
||||
public class OrderRepository : IOrderRepository
|
||||
public class OrderRepository : IOrderRepository
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<AccessoriesRepository> _logger;
|
||||
|
||||
public OrderRepository(IConnectionString connectionString, ILogger<AccessoriesRepository> logger)
|
||||
{
|
||||
private readonly IConnectionString _connectionString;
|
||||
|
||||
private readonly ILogger<AccessoriesRepository> _logger;
|
||||
|
||||
public OrderRepository(IConnectionString connectionString, ILogger<AccessoriesRepository> 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<int>(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<Order>(querySelect, new { id });
|
||||
_logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(order));
|
||||
return order;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Ошибка при поиске объекта");
|
||||
throw;
|
||||
}
|
||||
var order = connection.QueryFirst<Order>(querySelect, new { id });
|
||||
_logger.LogDebug("Найденный объект {json}", JsonConvert.SerializeObject(order));
|
||||
return order;
|
||||
}
|
||||
|
||||
public IEnumerable<Order> 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<TempAccessoriesOrder>(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<Order> 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<int, List<AccessoiresOrder>>();
|
||||
var servicesDict = new Dictionary<int, List<ServicesOrder>>();
|
||||
|
||||
var orders = connection.Query<Order, AccessoiresOrder, ServicesOrder, Order>(querySelect,
|
||||
(order, accessoriesOrder, servicesOrder) =>
|
||||
{
|
||||
|
||||
if (!accessoriesDict.TryGetValue(order.Id, out var aoList))
|
||||
{
|
||||
aoList = new List<AccessoiresOrder>();
|
||||
accessoriesDict.Add(order.Id, aoList);
|
||||
}
|
||||
aoList.Add(accessoriesOrder);
|
||||
|
||||
|
||||
if (!servicesDict.TryGetValue(order.Id, out var soList))
|
||||
{
|
||||
soList = new List<ServicesOrder>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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}";
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user