From 5dbc07fdc5b19ca9bd47c3a4914cd8bc1266e64e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B3=D0=BE=D1=80=20=D0=9F=D1=8B=D0=B6=D0=BE=D0=B2?= Date: Mon, 9 Dec 2024 13:27:29 +0400 Subject: [PATCH 1/5] =?UTF-8?q?=D0=BD=D0=B0=D1=87=D0=B0=D0=BB=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ITServiceManager/Entities/Appointment.cs | 15 +++++++++- .../ITServiceManager/Entities/Company.cs | 7 ++++- .../ITServiceManager/Entities/Employee.cs | 9 ++++++ .../ITServiceManager/Entities/Order.cs | 18 +++++++++++- .../ITServiceManager/Entities/OrderService.cs | 1 + .../ITServiceManager/Entities/Service.cs | 5 ++++ .../ITServiceManager/Forms/FormAppointment.cs | 2 +- .../Forms/FormAppointments.cs | 8 ++++- .../ITServiceManager/Forms/FormCompanies.cs | 6 +++- .../ITServiceManager/Forms/FormEmployees.cs | 9 ++++-- .../ITServiceManager/Forms/FormOrders.cs | 7 ++++- .../Implementations/OrderRepository.cs | 22 ++++++++++++++ .../Implementations/QueryBuilder.cs | 29 +++++++++++++++++++ 13 files changed, 129 insertions(+), 9 deletions(-) create mode 100644 ITServiceManager/ITServiceManager/Repositories/Implementations/QueryBuilder.cs diff --git a/ITServiceManager/ITServiceManager/Entities/Appointment.cs b/ITServiceManager/ITServiceManager/Entities/Appointment.cs index af30c6e..e00f740 100644 --- a/ITServiceManager/ITServiceManager/Entities/Appointment.cs +++ b/ITServiceManager/ITServiceManager/Entities/Appointment.cs @@ -1,11 +1,24 @@ -namespace ITServiceManager.Entities; +using System.ComponentModel; + +namespace ITServiceManager.Entities; public class Appointment { public int Id { get; private set; } + + [Browsable(false)] public int EmployeeId { get; private set; } + + [Browsable(false)] public int OrderId { get; private set; } + + [DisplayName("Сотрудник")] + public string EmployeeName { get; private set; } = string.Empty; + + [DisplayName("Дата назначения")] public DateTime StartDate { get; private set; } + + [DisplayName("Дата окончания")] public DateTime? EndDate { get; private set; } public static Appointment CreateOperation(int id, int orderId, int employeeId, DateTime appointmentStartDate, DateTime? appointmentEndDate) diff --git a/ITServiceManager/ITServiceManager/Entities/Company.cs b/ITServiceManager/ITServiceManager/Entities/Company.cs index 0ed7118..cdec373 100644 --- a/ITServiceManager/ITServiceManager/Entities/Company.cs +++ b/ITServiceManager/ITServiceManager/Entities/Company.cs @@ -1,10 +1,15 @@ -namespace ITServiceManager.Entities; +using System.ComponentModel; + +namespace ITServiceManager.Entities; public class Company { public int Id { get; private set; } + + [DisplayName("Название")] public string Name { get; private set; } = string.Empty; + [DisplayName("Адресс")] public string Address { get; private set; } = string.Empty; public static Company CreateEntity(int id, string companyName, string addres) diff --git a/ITServiceManager/ITServiceManager/Entities/Employee.cs b/ITServiceManager/ITServiceManager/Entities/Employee.cs index 98290e6..ae19b64 100644 --- a/ITServiceManager/ITServiceManager/Entities/Employee.cs +++ b/ITServiceManager/ITServiceManager/Entities/Employee.cs @@ -1,12 +1,21 @@ using ITServiceManager.Entities.Enums; +using System.ComponentModel; namespace ITServiceManager.Entities; public class Employee { public int Id { get; private set; } + + [DisplayName("Имя")] public string FirstName { get; private set; } = string.Empty; + + [DisplayName("Фамилия")] public string LastName { get; private set; } = string.Empty; + public string FullName => $"{LastName} {FirstName}"; + + + [DisplayName("Должность")] public EmployeePost? Position { get; private set; } public static Employee CreateEntity(int id, string employeeFirstName, string employeeLastName, EmployeePost employeePosition) diff --git a/ITServiceManager/ITServiceManager/Entities/Order.cs b/ITServiceManager/ITServiceManager/Entities/Order.cs index 65ccd77..18c66db 100644 --- a/ITServiceManager/ITServiceManager/Entities/Order.cs +++ b/ITServiceManager/ITServiceManager/Entities/Order.cs @@ -1,12 +1,28 @@ -namespace ITServiceManager.Entities; +using System.ComponentModel; + +namespace ITServiceManager.Entities; public class Order { public int Id { get; private set; } + + [Browsable(false)] public int CompanyId { get; private set; } + + [DisplayName("Дата")] public DateTime Date { get; private set; } + + [DisplayName("Сумма")] public decimal Price { get; private set; } + [DisplayName("Название компании")] + public string CompanyName { get; private set; } = string.Empty; + + [DisplayName("Услуги")] + public string Services => OrderService != null ? + string.Join(", ", OrderService.Select(x => $"{x.ServiceName} {x.Quantity}")) : string.Empty; + + [Browsable(false)] public IEnumerable OrderService { get; private set; } = []; public static Order CreateOperation(int id, int companyId, decimal orderPrice, IEnumerable orderService) diff --git a/ITServiceManager/ITServiceManager/Entities/OrderService.cs b/ITServiceManager/ITServiceManager/Entities/OrderService.cs index e6434d5..533c56a 100644 --- a/ITServiceManager/ITServiceManager/Entities/OrderService.cs +++ b/ITServiceManager/ITServiceManager/Entities/OrderService.cs @@ -5,6 +5,7 @@ public class OrderService public int Id { get; private set; } public int OrderId { get; private set; } public int ServiceId { get; private set; } + public string ServiceName { get; private set; } = string.Empty; public int Quantity { get; private set; } public DateTime ExecutionDate { get; private set; } diff --git a/ITServiceManager/ITServiceManager/Entities/Service.cs b/ITServiceManager/ITServiceManager/Entities/Service.cs index d907ddb..bad03b2 100644 --- a/ITServiceManager/ITServiceManager/Entities/Service.cs +++ b/ITServiceManager/ITServiceManager/Entities/Service.cs @@ -1,11 +1,16 @@ using ITServiceManager.Entities.Enums; +using System.ComponentModel; namespace ITServiceManager.Entities; public class Service { public int Id { get; private set; } + + [DisplayName("Тип услуги")] public ServiceType ServiceType { get; private set; } + + [DisplayName("Описание")] public string Description { get; private set; } = string.Empty; public static Service CreateEntity(int id, ServiceType type, string description) diff --git a/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs b/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs index 66f1548..e157b6d 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs @@ -38,7 +38,7 @@ namespace ITServiceManager.Forms throw new ArgumentNullException(nameof(appointmentRepository)); comboBoxOrder.DataSource = orderRepository.ReadOrders(); - comboBoxOrder.DisplayMember = "Name"; + comboBoxOrder.DisplayMember = "FullName"; comboBoxOrder.ValueMember = "Id"; comboBoxEmployee.DataSource = employeeRepository.ReadEmployees(); diff --git a/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs b/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs index c0ea03f..9af548e 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs @@ -65,7 +65,13 @@ namespace ITServiceManager.Forms MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = _appointmentRepository.ReadAppointments(); + private void LoadList() + { + dataGridView.DataSource = _appointmentRepository.ReadAppointments(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["StartDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; + dataGridView.Columns["EndDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; + } private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ITServiceManager/ITServiceManager/Forms/FormCompanies.cs b/ITServiceManager/ITServiceManager/Forms/FormCompanies.cs index 5c45845..00f390c 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormCompanies.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormCompanies.cs @@ -85,7 +85,11 @@ namespace ITServiceManager.Forms MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = _companyRepository.ReadCompanies(); + private void LoadList() + { + dataGridView.DataSource = _companyRepository.ReadCompanies(); + dataGridView.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ITServiceManager/ITServiceManager/Forms/FormEmployees.cs b/ITServiceManager/ITServiceManager/Forms/FormEmployees.cs index 8f42ba2..d66366d 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormEmployees.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormEmployees.cs @@ -95,8 +95,13 @@ namespace ITServiceManager.Forms MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = - _employeeRepository.ReadEmployees(); + private void LoadList() + { + dataGridView.DataSource =_employeeRepository.ReadEmployees(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["FullName"].Visible = false; + } + private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ITServiceManager/ITServiceManager/Forms/FormOrders.cs b/ITServiceManager/ITServiceManager/Forms/FormOrders.cs index 16300b5..ba55abf 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormOrders.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormOrders.cs @@ -65,7 +65,12 @@ namespace ITServiceManager.Forms MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = _orderRepository.ReadOrders(); + private void LoadList() + { + dataGridView.DataSource = _orderRepository.ReadOrders(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["Date"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; + } private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs index 8dc78d1..98332d7 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs @@ -22,6 +22,28 @@ public class OrderRepository : IOrderRepository try { using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var builder = new QueryBuilder(); + if (dateForm.HasValue) + { + builder.AddCondition("fa.FeedingDate >= @dateForm"); + } + if (dateTo.HasValue) + { + builder.AddCondition("fa.FeedingDate <= @dateTo"); + } + if (feedId.HasValue) + { + builder.AddCondition("fa.FeedId = @feedId"); + } + if (employeeId.HasValue) + { + builder.AddCondition("fa.EmployeeId = @employeeId"); + } + if (animalId.HasValue) + { + builder.AddCondition("fa.AnimalId = @animalId"); + } + var querySelect = @" SELECT o.*, os.serviceId, os.quantity FROM Orders AS o diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/QueryBuilder.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/QueryBuilder.cs new file mode 100644 index 0000000..134ef14 --- /dev/null +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/QueryBuilder.cs @@ -0,0 +1,29 @@ +using System.Text; + +namespace ITServiceManager.Repositories.Implementations; + +public 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}"; + } +} -- 2.25.1 From 2a5fb215e36bdadab8e0a4c606b5c3a6ec69f75e Mon Sep 17 00:00:00 2001 From: user Date: Mon, 9 Dec 2024 14:56:29 +0400 Subject: [PATCH 2/5] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D1=82=D0=B8=20=D0=B3?= =?UTF-8?q?=D0=BE=D1=82=D0=BE=D0=B2=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ITServiceManager/Entities/Order.cs | 7 +++ .../ITServiceManager/Reports/ChartReport.cs | 25 +------- .../ITServiceManager/Reports/TableReport.cs | 14 ++--- .../Repositories/IAppointmentRepository.cs | 2 +- .../Repositories/IOrderRepository.cs | 2 +- .../Implementations/AppointmentRepository.cs | 28 ++++++++- .../Implementations/OrderRepository.cs | 58 +++++++++++-------- 7 files changed, 75 insertions(+), 61 deletions(-) diff --git a/ITServiceManager/ITServiceManager/Entities/Order.cs b/ITServiceManager/ITServiceManager/Entities/Order.cs index 18c66db..e6ee342 100644 --- a/ITServiceManager/ITServiceManager/Entities/Order.cs +++ b/ITServiceManager/ITServiceManager/Entities/Order.cs @@ -25,6 +25,13 @@ public class Order [Browsable(false)] public IEnumerable OrderService { get; private set; } = []; + public void SetServices(IEnumerable orderServices) + { + if (orderServices != null && orderServices.Any()) + { + OrderService = orderServices; + } + } public static Order CreateOperation(int id, int companyId, decimal orderPrice, IEnumerable orderService) { return new Order diff --git a/ITServiceManager/ITServiceManager/Reports/ChartReport.cs b/ITServiceManager/ITServiceManager/Reports/ChartReport.cs index 132b6b4..8bc033f 100644 --- a/ITServiceManager/ITServiceManager/Reports/ChartReport.cs +++ b/ITServiceManager/ITServiceManager/Reports/ChartReport.cs @@ -35,43 +35,24 @@ public class ChartReport } } - //private List<(string Caption, double Value)> GetData(DateTime dateTime) - //{ - // return _orderRepository - // .ReadOrders() // Получаем все заказы - // .Where(order => order.Date.Date == dateTime.Date) // Фильтруем по дате заказа - // .SelectMany(order => order.OrderService) // Разворачиваем список услуг в заказах - // .GroupBy(service => service.ServiceId, (key, group) => new { ServiceId = key, Count = group.Sum(service => service.Quantity) }) // Группируем по ID услуги и суммируем количество - // .Select(group => - // { - // var service = _serviceRepository.ReadServiceById(group.ServiceId); // Получаем информацию о услуге по ID - // return (service.ServiceType.ToString(), (double)group.Count); // Возвращаем название услуги и ее количество - // }) - // .ToList(); - //} - private List<(string Caption, double Value)> GetData(DateTime dateTime) { - // Получаем заказы за указанную дату var orders = _orderRepository - .ReadOrders() - .Where(order => order.Date.Date == dateTime.Date) // Фильтруем заказы по дате + .ReadOrders(dateForm: dateTime.Date, dateTo:dateTime.Date.AddDays(1)) .ToList(); - // Группируем заказы по CompanyId и вычисляем общую сумму затрат var groupedOrders = orders .GroupBy(order => order.CompanyId) .Select(group => new { CompanyId = group.Key, - TotalSpent = group.Sum(order => (double)order.Price) // Суммируем стоимость заказов + TotalSpent = group.Sum(order => (double)order.Price) }); - // Получаем названия компаний и формируем данные для диаграммы return groupedOrders .Select(group => { - var company = _companyRepository.ReadCompanyById(group.CompanyId); // Получаем информацию о компании + var company = _companyRepository.ReadCompanyById(group.CompanyId); return (Caption: company.Name, Value: group.TotalSpent); }) .ToList(); diff --git a/ITServiceManager/ITServiceManager/Reports/TableReport.cs b/ITServiceManager/ITServiceManager/Reports/TableReport.cs index 1bb920c..4fe09cb 100644 --- a/ITServiceManager/ITServiceManager/Reports/TableReport.cs +++ b/ITServiceManager/ITServiceManager/Reports/TableReport.cs @@ -27,8 +27,9 @@ public class TableReport { new ExcelBuilder(filePath) .AddHeader("Сводка по обслуживанию услуг", 0, 3) - .AddParagraph("за период", 0) - .AddTable([10, 30, 30], GetData(employeeId, startDate, endDate)) + .AddParagraph($"за период c {startDate:dd.MM.yyyy} по {endDate: dd.MM.yyyy}", 0) + + .AddTable([10, 10, 15, 15], GetData(employeeId, startDate, endDate)) .Build(); return true; } @@ -43,13 +44,8 @@ public class TableReport { var data = _orderRepository - .ReadOrders() - .Where(order => - order.Date >= startDate && - order.Date <= endDate && - order.OrderService.Any(service => service.ServiceId == serviceId)) + .ReadOrders(dateForm: startDate, dateTo: endDate, serviceId: serviceId) .SelectMany(order => order.OrderService - .Where(service => service.ServiceId == serviceId) .Select(service => new { EmployeeId = _appointmentRepository @@ -62,7 +58,7 @@ public class TableReport return new List() { item } .Union( data - .Select(x => new string[] { x.EmployeeId?.ToString() ?? "Не назначен", x.Date.ToString(), x.Quantity.ToString()})) + .Select(x => new string[] { x.EmployeeId?.ToString() ?? "Не назначен", x.Date.ToString("dd.MM.yyyy"), x.Quantity.ToString()})) .Union( [["Всего", string.Empty, data.Sum(x => x.Quantity).ToString()]]) .ToList(); diff --git a/ITServiceManager/ITServiceManager/Repositories/IAppointmentRepository.cs b/ITServiceManager/ITServiceManager/Repositories/IAppointmentRepository.cs index 04feabc..b4f667d 100644 --- a/ITServiceManager/ITServiceManager/Repositories/IAppointmentRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/IAppointmentRepository.cs @@ -4,7 +4,7 @@ namespace ITServiceManager.Repositories; public interface IAppointmentRepository { - IEnumerable ReadAppointments(); + IEnumerable ReadAppointments(int? employeeId = null, DateTime? dateFrom = null, DateTime? dateTo = null); Appointment ReadAppointmentById(int id); void CreateAppointment(Appointment appointment); void UpdateAppointment(Appointment appointment); diff --git a/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs index 3f126af..f61aaa6 100644 --- a/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs @@ -4,7 +4,7 @@ namespace ITServiceManager.Repositories; public interface IOrderRepository { - IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? companyId = null); + IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? serviceId = null, int? companyId = null); void CreateOrder(Order order); void DeleteOrder(int id); } diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs index 7fefee4..df2f045 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs @@ -15,14 +15,36 @@ public class AppointmentRepository : IAppointmentRepository _connectionString = connectionString; _logger = logger; } - public IEnumerable ReadAppointments() + public IEnumerable ReadAppointments(int? employeeId = null, DateTime? dateFrom = null, DateTime? dateTo = null) { _logger.LogInformation("Получение всех объектов"); try { + if (dateFrom.HasValue && dateTo.HasValue) + { + if (dateFrom.Value >= dateTo.Value) + { + throw new Exception("Дата начала должна быть раньше даты окончания"); + } + } + var builder = new QueryBuilder(); + if (employeeId.HasValue) + { + builder.AddCondition("ap.EmployeeId = @employeeId"); + } + if (dateFrom.HasValue) + { + builder.AddCondition("ap.dateStart >= @dateFrom"); + } + if (dateTo.HasValue) + { + builder.AddCondition("ap.dateEnd >= @dateTo"); + } using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @"SELECT * FROM Appointments"; - var appointment = connection.Query(querySelect); + var querySelect = @$"SELECT ap.*, e.Name as 'EmployeeName' + FROM Employees ap JOIN Employees e ON e.id = ap.EmployeeId + {builder.Build()}"; + var appointment = connection.Query(querySelect, new { employeeId, dateFrom, dateTo}); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(appointment)); return appointment; } diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs index 98332d7..4cbc9f1 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs @@ -16,46 +16,54 @@ public class OrderRepository : IOrderRepository _connectionString = connectionString; _logger = logger; } - public IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null) + public IEnumerable ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null) { _logger.LogInformation("Получение всех объектов"); try { - using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var builder = new QueryBuilder(); - if (dateForm.HasValue) + if (dateFrom.HasValue) { - builder.AddCondition("fa.FeedingDate >= @dateForm"); + builder.AddCondition("Orders.Date >= @dateForm"); } if (dateTo.HasValue) { - builder.AddCondition("fa.FeedingDate <= @dateTo"); + builder.AddCondition("Orders.Date <= @dateTo"); } - if (feedId.HasValue) + if (companyId.HasValue) { - builder.AddCondition("fa.FeedId = @feedId"); + builder.AddCondition("Orders.CompanyId = @companyId"); } - if (employeeId.HasValue) - { - builder.AddCondition("fa.EmployeeId = @employeeId"); - } - if (animalId.HasValue) - { - builder.AddCondition("fa.AnimalId = @animalId"); - } - - var querySelect = @" - SELECT o.*, os.serviceId, os.quantity + using var connection = new NpgsqlConnection(_connectionString.ConnectionString); + var querySelect = @$" + SELECT o.*, c.Name as CompanyName, os.serviceId, os.quantity, s.ServiceType FROM Orders AS o + LEFT JOIN Companies c on c.Id = o.CompanyId INNER JOIN Order_Service AS os ON o.id = os.orderId - Where os.serviceId = @serviceId"; - var orders = connection.Query(querySelect); + LEFT JOIN Services s on s.Id = os.ServiceId + Where os.serviceId = @serviceId + {builder.Build}"; + var orderDict = new Dictionary>(); + + var orders = connection.Query(querySelect, + (order, orderServices) => + { + if (!orderDict.TryGetValue(order.Id, out var frr)) + { + frr = []; + orderDict.Add(order.Id, frr); + } + frr.Add(orderServices); + return order; + }, splitOn: "ServiceId", param: new { dateFrom, dateTo, serviceId, companyId }); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders)); - return orders.GroupBy(x => x.Id, y => y, - (key, value) => - Order.CreateOperation(value.First(), - value.Select(z => - OrderService.CreateOperation(0, z.ServiceId, z.Quantity, z.ExecutionTime)))).ToList(); + + return orderDict.Select(x => + { + var or = orders.First(y => y.Id == x.Key); + or.SetServices(x.Value); + return or; + }).ToArray(); } catch (Exception ex) { -- 2.25.1 From 8bd98a45257bc0cdfb6f3bf46fa94a613c90cd1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B3=D0=BE=D1=80=20=D0=9F=D1=8B=D0=B6=D0=BE=D0=B2?= Date: Tue, 10 Dec 2024 11:27:20 +0400 Subject: [PATCH 3/5] =?UTF-8?q?=D0=A1=D0=B4=D0=B5=D0=BB=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D0=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ITServiceManager/Entities/Appointment.cs | 2 +- .../ITServiceManager/Entities/Order.cs | 13 -- .../ITServiceManager/Entities/OrderService.cs | 2 +- .../ITServiceManager/Entities/TempOrder.cs | 12 -- .../ITServiceManager/Forms/FormAppointment.cs | 2 +- .../Forms/FormAppointments.cs | 200 +++++++++--------- .../ITServiceManager/Forms/FormOrder.cs | 4 +- .../ITServiceManager/Forms/FormServices.cs | 7 +- .../ITServiceManager/Reports/TableReport.cs | 9 +- .../Repositories/IOrderRepository.cs | 2 +- .../Implementations/AppointmentRepository.cs | 5 +- .../Implementations/OrderRepository.cs | 13 +- 12 files changed, 127 insertions(+), 144 deletions(-) delete mode 100644 ITServiceManager/ITServiceManager/Entities/TempOrder.cs diff --git a/ITServiceManager/ITServiceManager/Entities/Appointment.cs b/ITServiceManager/ITServiceManager/Entities/Appointment.cs index e00f740..27bbd2d 100644 --- a/ITServiceManager/ITServiceManager/Entities/Appointment.cs +++ b/ITServiceManager/ITServiceManager/Entities/Appointment.cs @@ -9,7 +9,7 @@ public class Appointment [Browsable(false)] public int EmployeeId { get; private set; } - [Browsable(false)] + [DisplayName("Номер заказа")] public int OrderId { get; private set; } [DisplayName("Сотрудник")] diff --git a/ITServiceManager/ITServiceManager/Entities/Order.cs b/ITServiceManager/ITServiceManager/Entities/Order.cs index e6ee342..0c5c9d8 100644 --- a/ITServiceManager/ITServiceManager/Entities/Order.cs +++ b/ITServiceManager/ITServiceManager/Entities/Order.cs @@ -43,17 +43,4 @@ public class Order OrderService = orderService }; } - - public static Order CreateOperation(TempOrder tempOrder, IEnumerable orderService) - { - return new Order - { - Id = tempOrder.Id, - CompanyId = tempOrder.CompanyId, - Date = tempOrder.Date, - Price = tempOrder.Price, - OrderService = orderService - }; - } - } diff --git a/ITServiceManager/ITServiceManager/Entities/OrderService.cs b/ITServiceManager/ITServiceManager/Entities/OrderService.cs index 533c56a..4091607 100644 --- a/ITServiceManager/ITServiceManager/Entities/OrderService.cs +++ b/ITServiceManager/ITServiceManager/Entities/OrderService.cs @@ -9,7 +9,7 @@ public class OrderService public int Quantity { get; private set; } public DateTime ExecutionDate { get; private set; } - public static OrderService CreateOperation(int id, int serviceId, int serviceQuantity, DateTime executionDate) + public static OrderService CreateElement(int id, int serviceId, int serviceQuantity, DateTime executionDate) { return new OrderService { diff --git a/ITServiceManager/ITServiceManager/Entities/TempOrder.cs b/ITServiceManager/ITServiceManager/Entities/TempOrder.cs deleted file mode 100644 index 761b835..0000000 --- a/ITServiceManager/ITServiceManager/Entities/TempOrder.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace ITServiceManager.Entities; - -public class TempOrder -{ - public int Id { get; private set; } - public int CompanyId { get; private set; } - public int ServiceId { get; private set; } - public DateTime Date { get; private set; } - public decimal Price { get; private set; } - public int Quantity { get; private set; } - public DateTime ExecutionTime { get; private set; } -} diff --git a/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs b/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs index e157b6d..b09929b 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormAppointment.cs @@ -42,7 +42,7 @@ namespace ITServiceManager.Forms comboBoxOrder.ValueMember = "Id"; comboBoxEmployee.DataSource = employeeRepository.ReadEmployees(); - comboBoxEmployee.DisplayMember = "Name"; + comboBoxEmployee.DisplayMember = "FullName"; comboBoxEmployee.ValueMember = "Id"; dateTimePickerEnd.Format = DateTimePickerFormat.Custom; diff --git a/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs b/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs index 9af548e..ff77694 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormAppointments.cs @@ -1,108 +1,112 @@ using ITServiceManager.Repositories; -using ITServiceManager.Repositories.Implementations; -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 Unity; -namespace ITServiceManager.Forms -{ - public partial class FormAppointments : Form - { - private readonly IUnityContainer _container; - private readonly IAppointmentRepository _appointmentRepository; - public FormAppointments(IUnityContainer container, IAppointmentRepository appointmentRepository) - { - InitializeComponent(); - _container = container ?? throw new ArgumentNullException(nameof(container)); - _appointmentRepository = appointmentRepository ?? throw new ArgumentNullException(nameof(appointmentRepository)); - } - private void FormAppointments_Load(object sender, EventArgs e) - { - try - { - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void ButtonAdd_Click(object sender, EventArgs e) - { - try - { - _container.Resolve().ShowDialog(); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void ButtonUpd_Click(object sender, EventArgs e) - { - if (!TryGetIdentifierFromSelectedRow(out var findId)) - { - return; - } - try - { - var form = _container.Resolve(); - form.Id = findId; - form.ShowDialog(); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при изменении", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - private void LoadList() - { - dataGridView.DataSource = _appointmentRepository.ReadAppointments(); - dataGridView.Columns["Id"].Visible = false; - dataGridView.Columns["StartDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; - dataGridView.Columns["EndDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm"; - } - private bool TryGetIdentifierFromSelectedRow(out int id) - { - id = 0; - if (dataGridView.SelectedRows.Count < 1) - { - MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - return false; - } - id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - return true; - } +namespace ITServiceManager.Forms; - private void buttonRemove_Click(object sender, EventArgs e) +public partial class FormAppointments : Form +{ + private readonly IUnityContainer _container; + private readonly IAppointmentRepository _appointmentRepository; + public FormAppointments(IUnityContainer container, IAppointmentRepository appointmentRepository) + { + InitializeComponent(); + _container = container ?? throw new ArgumentNullException(nameof(container)); + _appointmentRepository = appointmentRepository ?? throw new ArgumentNullException(nameof(appointmentRepository)); + } + private void FormAppointments_Load(object sender, EventArgs e) + { + try { - if (!TryGetIdentifierFromSelectedRow(out var findId)) + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void ButtonAdd_Click(object sender, EventArgs e) + { + try + { + _container.Resolve().ShowDialog(); + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (!TryGetIdentifierFromSelectedRow(out var findId)) + { + return; + } + try + { + var form = _container.Resolve(); + form.Id = findId; + form.ShowDialog(); + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при изменении", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void LoadList() + { + dataGridView.DataSource = _appointmentRepository.ReadAppointments(); + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["StartDate"].DefaultCellStyle.Format = "dd.MM.yyyy HH:mm"; + dataGridView.CellFormatting += (sender, e) => + { + if (dataGridView.Columns[e.ColumnIndex].Name == "EndDate") { - return; - } - if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) - { - return; - } - try - { - _appointmentRepository.DeleteAppointment(findId); - LoadList(); - } - catch (Exception ex) - { - MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); + if (e.Value == null || e.Value == DBNull.Value) + { + e.Value = "В процессе"; + e.FormattingApplied = true; + } + else if (e.Value is DateTime endDate) + { + e.Value = endDate.ToString("dd.MM.yyyy HH:mm"); + e.FormattingApplied = true; + } } + }; + } + private bool TryGetIdentifierFromSelectedRow(out int id) + { + id = 0; + if (dataGridView.SelectedRows.Count < 1) + { + MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + return true; + } + + private void buttonRemove_Click(object sender, EventArgs e) + { + if (!TryGetIdentifierFromSelectedRow(out var findId)) + { + return; + } + if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes) + { + return; + } + try + { + _appointmentRepository.DeleteAppointment(findId); + LoadList(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/ITServiceManager/ITServiceManager/Forms/FormOrder.cs b/ITServiceManager/ITServiceManager/Forms/FormOrder.cs index 0a39fa6..24d54a7 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormOrder.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormOrder.cs @@ -45,9 +45,9 @@ public partial class FormOrder : Form { continue; } - list.Add(OrderService.CreateOperation(0, Convert.ToInt32(row.Cells["ColumnService"].Value), Convert.ToInt32(row.Cells["ColumnQuantity"].Value), Convert.ToDateTime(row.Cells["ColumnExecutionDate"].Value))); + list.Add(OrderService.CreateElement(0, Convert.ToInt32(row.Cells["ColumnService"].Value), Convert.ToInt32(row.Cells["ColumnQuantity"].Value), Convert.ToDateTime(row.Cells["ColumnExecutionDate"].Value))); } - return list; + return list.GroupBy(x => x.ServiceId, x => x.Quantity, (id, quantities) => OrderService.CreateElement(0, id, quantities.Sum(), list.First(x => x.ServiceId == id).ExecutionDate)).ToList(); } } diff --git a/ITServiceManager/ITServiceManager/Forms/FormServices.cs b/ITServiceManager/ITServiceManager/Forms/FormServices.cs index 4c5694b..9bfbf91 100644 --- a/ITServiceManager/ITServiceManager/Forms/FormServices.cs +++ b/ITServiceManager/ITServiceManager/Forms/FormServices.cs @@ -95,8 +95,11 @@ namespace ITServiceManager.Forms MessageBoxButtons.OK, MessageBoxIcon.Error); } } - private void LoadList() => dataGridView.DataSource = - _serviceRepository.ReadServices(); + private void LoadList() + { + dataGridView.DataSource = _serviceRepository.ReadServices(); + dataGridView.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectedRow(out int id) { id = 0; diff --git a/ITServiceManager/ITServiceManager/Reports/TableReport.cs b/ITServiceManager/ITServiceManager/Reports/TableReport.cs index 4fe09cb..4b9855a 100644 --- a/ITServiceManager/ITServiceManager/Reports/TableReport.cs +++ b/ITServiceManager/ITServiceManager/Reports/TableReport.cs @@ -29,7 +29,7 @@ public class TableReport .AddHeader("Сводка по обслуживанию услуг", 0, 3) .AddParagraph($"за период c {startDate:dd.MM.yyyy} по {endDate: dd.MM.yyyy}", 0) - .AddTable([10, 10, 15, 15], GetData(employeeId, startDate, endDate)) + .AddTable([10, 10, 15], GetData(employeeId, startDate, endDate)) .Build(); return true; } @@ -48,9 +48,9 @@ public class TableReport .SelectMany(order => order.OrderService .Select(service => new { - EmployeeId = _appointmentRepository + EmployeeName = _appointmentRepository .ReadAppointments() - .FirstOrDefault(app => app.OrderId == order.Id)?.EmployeeId, + .FirstOrDefault(app => app.OrderId == order.Id)?.EmployeeName, Date = order.Date, Quantity = service.Quantity })) @@ -58,7 +58,8 @@ public class TableReport return new List() { item } .Union( data - .Select(x => new string[] { x.EmployeeId?.ToString() ?? "Не назначен", x.Date.ToString("dd.MM.yyyy"), x.Quantity.ToString()})) + .Select( + x => new string[] { x.EmployeeName ?? "Не назначен", x.Date.ToString("dd.MM.yyyy"), x.Quantity.ToString()})) .Union( [["Всего", string.Empty, data.Sum(x => x.Quantity).ToString()]]) .ToList(); diff --git a/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs index f61aaa6..3a7a5c1 100644 --- a/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/IOrderRepository.cs @@ -4,7 +4,7 @@ namespace ITServiceManager.Repositories; public interface IOrderRepository { - IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? serviceId = null, int? companyId = null); + IEnumerable ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null); void CreateOrder(Order order); void DeleteOrder(int id); } diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs index df2f045..9c9aadc 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/AppointmentRepository.cs @@ -41,8 +41,9 @@ public class AppointmentRepository : IAppointmentRepository builder.AddCondition("ap.dateEnd >= @dateTo"); } using var connection = new NpgsqlConnection(_connectionString.ConnectionString); - var querySelect = @$"SELECT ap.*, e.Name as 'EmployeeName' - FROM Employees ap JOIN Employees e ON e.id = ap.EmployeeId + var querySelect = @$" + SELECT ap.*, CONCAT(e.LastName, ' ', e.FirstName) as EmployeeName + FROM Appointments ap LEFT JOIN Employees e ON e.id = ap.EmployeeId; {builder.Build()}"; var appointment = connection.Query(querySelect, new { employeeId, dateFrom, dateTo}); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(appointment)); diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs index 4cbc9f1..ab99d84 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs @@ -24,25 +24,24 @@ public class OrderRepository : IOrderRepository var builder = new QueryBuilder(); if (dateFrom.HasValue) { - builder.AddCondition("Orders.Date >= @dateForm"); + builder.AddCondition("o.Date >= @dateFrom"); } if (dateTo.HasValue) { - builder.AddCondition("Orders.Date <= @dateTo"); + builder.AddCondition("o.Date <= @dateTo"); } - if (companyId.HasValue) + if (serviceId.HasValue) { - builder.AddCondition("Orders.CompanyId = @companyId"); + builder.AddCondition("os.ServiceId = @serviceId"); } using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @$" - SELECT o.*, c.Name as CompanyName, os.serviceId, os.quantity, s.ServiceType + SELECT o.*, c.Name as CompanyName, os.serviceId, os.quantity, s.ServiceType as ServiceName FROM Orders AS o LEFT JOIN Companies c on c.Id = o.CompanyId INNER JOIN Order_Service AS os ON o.id = os.orderId LEFT JOIN Services s on s.Id = os.ServiceId - Where os.serviceId = @serviceId - {builder.Build}"; + {builder.Build()}"; var orderDict = new Dictionary>(); var orders = connection.Query(querySelect, -- 2.25.1 From 7a1b7fb72a57824da8d4abe7335354c01f55a7ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B3=D0=BE=D1=80=20=D0=9F=D1=8B=D0=B6=D0=BE=D0=B2?= Date: Sun, 15 Dec 2024 02:49:07 +0400 Subject: [PATCH 4/5] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D0=BA=D0=BE=D1=80=D0=B5?= =?UTF-8?q?=D0=BA=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BB=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ITServiceManager/ITServiceManager/Entities/Service.cs | 4 +++- .../Repositories/Implementations/OrderRepository.cs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ITServiceManager/ITServiceManager/Entities/Service.cs b/ITServiceManager/ITServiceManager/Entities/Service.cs index bab84a6..d69cd25 100644 --- a/ITServiceManager/ITServiceManager/Entities/Service.cs +++ b/ITServiceManager/ITServiceManager/Entities/Service.cs @@ -10,8 +10,10 @@ public class Service [DisplayName("Тип услуги")] public ServiceType ServiceType { get; private set; } - [DisplayName("Описание")] + [DisplayName("Название услуги")] public string ServiceName { get; private set; } = string.Empty; + + [DisplayName("Описание")] public string Description { get; private set; } = string.Empty; public static Service CreateEntity(int id, ServiceType type, string name, string description) diff --git a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs index ab99d84..b322bc9 100644 --- a/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs +++ b/ITServiceManager/ITServiceManager/Repositories/Implementations/OrderRepository.cs @@ -36,7 +36,7 @@ public class OrderRepository : IOrderRepository } using var connection = new NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @$" - SELECT o.*, c.Name as CompanyName, os.serviceId, os.quantity, s.ServiceType as ServiceName + SELECT o.*, c.Name as CompanyName, os.serviceId, os.quantity, s.ServiceName as ServiceName FROM Orders AS o LEFT JOIN Companies c on c.Id = o.CompanyId INNER JOIN Order_Service AS os ON o.id = os.orderId -- 2.25.1 From f715f86cd433dd31e1a466a3a9874ff2e6273390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=95=D0=B3=D0=BE=D1=80=20=D0=9F=D1=8B=D0=B6=D0=BE=D0=B2?= Date: Sun, 15 Dec 2024 02:54:21 +0400 Subject: [PATCH 5/5] =?UTF-8?q?=D0=A1=D0=BF=D1=80=D1=8F=D1=82=D0=B0=D0=BB?= =?UTF-8?q?=20OrderId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ITServiceManager/ITServiceManager/Entities/Appointment.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ITServiceManager/ITServiceManager/Entities/Appointment.cs b/ITServiceManager/ITServiceManager/Entities/Appointment.cs index 27bbd2d..e00f740 100644 --- a/ITServiceManager/ITServiceManager/Entities/Appointment.cs +++ b/ITServiceManager/ITServiceManager/Entities/Appointment.cs @@ -9,7 +9,7 @@ public class Appointment [Browsable(false)] public int EmployeeId { get; private set; } - [DisplayName("Номер заказа")] + [Browsable(false)] public int OrderId { get; private set; } [DisplayName("Сотрудник")] -- 2.25.1