PIbd-22 Pyzhov E.A. LabWork04 #4

Closed
pyzhov.egor wants to merge 7 commits from LabWork_4 into LabWork_3
21 changed files with 418 additions and 248 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -1,14 +1,37 @@
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> OrderService { get; private set; } = [];
public void SetServices(IEnumerable<OrderService> orderServices)
{
if (orderServices != null && orderServices.Any())
{
OrderService = orderServices;
}
}
public static Order CreateOperation(int id, int companyId, decimal orderPrice, IEnumerable<OrderService> orderService)
{
return new Order
@ -20,17 +43,4 @@ public class Order
OrderService = orderService
};
}
public static Order CreateOperation(TempOrder tempOrder, IEnumerable<OrderService> orderService)
{
return new Order
{
Id = tempOrder.Id,
CompanyId = tempOrder.CompanyId,
Date = tempOrder.Date,
Price = tempOrder.Price,
OrderService = orderService
};
}
}

View File

@ -5,10 +5,11 @@ 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; }
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
{

View File

@ -1,12 +1,19 @@
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 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)

View File

@ -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; }
}

View File

@ -37,12 +37,12 @@ public partial class FormAppointment : Form
_appointmentRepository = appointmentRepository ??
throw new ArgumentNullException(nameof(appointmentRepository));
comboBoxOrder.DataSource = orderRepository.ReadOrders();
comboBoxOrder.DisplayMember = "Name";
comboBoxOrder.ValueMember = "Id";
comboBoxOrder.DataSource = orderRepository.ReadOrders();
comboBoxOrder.DisplayMember = "FullName";
comboBoxOrder.ValueMember = "Id";
comboBoxEmployee.DataSource = employeeRepository.ReadEmployees();
comboBoxEmployee.DisplayMember = "Name";
comboBoxEmployee.DisplayMember = "FullName";
comboBoxEmployee.ValueMember = "Id";
dateTimePickerEnd.Format = DateTimePickerFormat.Custom;

View File

@ -55,7 +55,28 @@ public partial class FormAppointments : Form
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.MM.yyyy HH:mm";
dataGridView.CellFormatting += (sender, e) =>
{
if (dataGridView.Columns[e.ColumnIndex].Name == "EndDate")
{
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;
@ -67,5 +88,26 @@ public partial class FormAppointments : Form
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);
}
}
}

View File

@ -8,85 +8,89 @@ public partial class FormCompanies : Form
private readonly IUnityContainer _container;
private readonly ICompanyRepository _companyRepository;
public FormCompanies(IUnityContainer container, ICompanyRepository companyRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));
}
private void FormCompanies_Load(object sender, EventArgs e)
{
try
public FormCompanies(IUnityContainer container, ICompanyRepository companyRepository)
{
LoadList();
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_companyRepository = companyRepository ?? throw new ArgumentNullException(nameof(companyRepository));
}
catch (Exception ex)
private void FormCompanies_Load(object sender, EventArgs e)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
private void ButtonAdd_Click(object sender, EventArgs e)
{
_container.Resolve<FormCompany>().ShowDialog();
LoadList();
try
{
_container.Resolve<FormCompany>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
private void ButtonRemove_Click(object sender, EventArgs e)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_companyRepository.DeleteCompany(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
private void ButtonUpdate_Click(object sender, EventArgs e)
{
return;
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormCompany>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
private void LoadList()
{
return;
dataGridView.DataSource = _companyRepository.ReadCompanies();
dataGridView.Columns["Id"].Visible = false;
}
try
private bool TryGetIdentifierFromSelectedRow(out int id)
{
_companyRepository.DeleteCompany(findId);
LoadList();
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;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormCompany>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _companyRepository.ReadCompanies();
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;
}
}

View File

@ -64,42 +64,47 @@ public partial class FormEmployees : Form
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
private void ButtonDel_Click(object sender, EventArgs e)
{
return;
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_employeeRepository.DeleteEmployee(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
private void LoadList()
{
return;
dataGridView.DataSource =_employeeRepository.ReadEmployees();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
try
private bool TryGetIdentifierFromSelectedRow(out int id)
{
_employeeRepository.DeleteEmployee(findId);
LoadList();
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;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource =
_employeeRepository.ReadEmployees();
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;
}
}

View File

@ -46,9 +46,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();
}
}

View File

@ -1,71 +1,77 @@
using ITServiceManager.Repositories;
using Unity;
namespace ITServiceManager.Forms;
public partial class FormOrders : Form
namespace ITServiceManager.Forms
{
private readonly IUnityContainer _container;
private readonly IOrderRepository _orderRepository;
public FormOrders(IUnityContainer container, IOrderRepository orderRepository)
public partial class FormOrders : Form
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
private void FormOrders_Load(object sender, EventArgs e)
{
try
private readonly IUnityContainer _container;
private readonly IOrderRepository _orderRepository;
public FormOrders(IUnityContainer container, IOrderRepository orderRepository)
{
LoadList();
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
catch (Exception ex)
private void FormOrders_Load(object sender, EventArgs e)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
private void ButtonAdd_Click(object sender, EventArgs e)
{
_container.Resolve<FormOrder>().ShowDialog();
LoadList();
try
{
_container.Resolve<FormOrder>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
private void ButtonRemove_Click(object sender, EventArgs e)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_orderRepository.DeleteOrder(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
private void LoadList()
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
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)
{
return;
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;
}
try
{
_orderRepository.DeleteOrder(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _orderRepository.ReadOrders();
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;
}
}

View File

@ -64,43 +64,46 @@ public partial class FormServices : Form
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
private void ButtonDel_Click(object sender, EventArgs e)
{
return;
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_serviceRepository.DeleteService(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
private void LoadList()
{
return;
}
try
dataGridView.DataSource = _serviceRepository.ReadServices();
dataGridView.Columns["Id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
_serviceRepository.DeleteService(findId);
LoadList();
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;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource =
_serviceRepository.ReadServices();
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;
}
}

View File

@ -36,8 +36,7 @@ public class ChartReport
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();
var groupedOrders = orders

View File

@ -23,9 +23,10 @@ public class TableReport
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по выбору услуг", 0, 3)
.AddParagraph("за период", 0)
.AddTable([10, 30, 30], GetData(employeeId, startDate, endDate))
.AddHeader("Сводка по обслуживанию услуг", 0, 3)
.AddParagraph($"за период c {startDate:dd.MM.yyyy} по {endDate: dd.MM.yyyy}", 0)
.AddTable([10, 10, 15], GetData(employeeId, startDate, endDate))
.Build();
return true;
}
@ -40,18 +41,13 @@ 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
EmployeeName = _appointmentRepository
.ReadAppointments()
.FirstOrDefault(app => app.OrderId == order.Id)?.EmployeeId,
.FirstOrDefault(app => app.OrderId == order.Id)?.EmployeeName,
Date = order.Date,
Quantity = service.Quantity
}))
@ -59,7 +55,8 @@ public class TableReport
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.EmployeeId?.ToString() ?? "Не назначен", x.Date.ToString(), 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();

View File

@ -4,7 +4,7 @@ namespace ITServiceManager.Repositories;
public interface IAppointmentRepository
{
IEnumerable<Appointment> ReadAppointments();
IEnumerable<Appointment> ReadAppointments(int? employeeId = null, DateTime? dateFrom = null, DateTime? dateTo = null);
Appointment ReadAppointmentById(int id);
void CreateAppointment(Appointment appointment);
void UpdateAppointment(Appointment appointment);

View File

@ -4,7 +4,7 @@ namespace ITServiceManager.Repositories;
public interface IOrderRepository
{
IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? orderId = null, int? companyId = null);
IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null);
void CreateOrder(Order order);
void DeleteOrder(int id);
}

View File

@ -15,14 +15,37 @@ public class AppointmentRepository : IAppointmentRepository
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Appointment> ReadAppointments()
public IEnumerable<Appointment> 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<Appointment>(querySelect);
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<Appointment>(querySelect, new { employeeId, dateFrom, dateTo});
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(appointment));
return appointment;
}

View File

@ -16,24 +16,53 @@ public class OrderRepository : IOrderRepository
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Order> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null)
public IEnumerable<Order> ReadOrders(DateTime? dateFrom = null, DateTime? dateTo = null, int? serviceId = null, int? companyId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT o.*, os.serviceId, os.quantity
var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("o.Date >= @dateFrom");
}
if (dateTo.HasValue)
{
builder.AddCondition("o.Date <= @dateTo");
}
if (serviceId.HasValue)
{
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.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
Where os.serviceId = @serviceId";
var orders = connection.Query<TempOrder>(querySelect);
LEFT JOIN Services s on s.Id = os.ServiceId
{builder.Build()}";
var orderDict = new Dictionary<int, List<OrderService>>();
var orders = connection.Query<Order, OrderService, Order>(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)
{

View File

@ -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}";
}
}