Лабораторная работа №4

This commit is contained in:
ENDORFIT 2024-12-18 23:59:13 +04:00
parent 79ed7aa78b
commit 527491a7e7
17 changed files with 202 additions and 37 deletions

View File

@ -1,4 +1,5 @@
using ProjectOptika.Scripts.Entities.Enums; using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities namespace ProjectOptika.Scripts.Entities
{ {
@ -6,18 +7,25 @@ namespace ProjectOptika.Scripts.Entities
{ {
public int ID { get; private set; } public int ID { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } public string Name { get; private set; }
[DisplayName("Название бренда")]
public string Brand { get; private set; } public string Brand { get; private set; }
[DisplayName("Стоимость")]
public int Cost { get; private set; } public int Cost { get; private set; }
[DisplayName("Количество на складе")]
public int StockAvailability { get; private set; } public int StockAvailability { get; private set; }
[DisplayName("Количество в магазине")]
public int AvailabilityStore { get; private set; } public int AvailabilityStore { get; private set; }
[DisplayName("Дата поставки")]
public DateTime DeliveryDate { get; private set; } public DateTime DeliveryDate { get; private set; }
[DisplayName("Категория")]
public CategoryType CategoryName { get; private set; } public CategoryType CategoryName { get; private set; }
public static Accessories CreateEntity(int id, string name, string brand, int cost, int stockAvailability, int availabilityStore, DateTime deliveryDate, CategoryType categoryName) public static Accessories CreateEntity(int id, string name, string brand, int cost, int stockAvailability, int availabilityStore, DateTime deliveryDate, CategoryType categoryName)

View File

@ -8,13 +8,16 @@
public int Count { get; private set; } public int Count { get; private set; }
public static AccessoriesOrder CreateElement(int id, int accesoryId, int count) public string AccessoryName { get; private set; } = string.Empty;
public static AccessoriesOrder CreateElement(int id, int accesoryId, int count, string? accessoryName = null)
{ {
return new AccessoriesOrder return new AccessoriesOrder
{ {
ID = id, ID = id,
AccesoryId = accesoryId, AccesoryId = accesoryId,
Count = count Count = count,
AccessoryName = accessoryName
}; };
} }
} }

View File

@ -1,4 +1,5 @@
using ProjectOptika.Scripts.Entities.Enums; using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities namespace ProjectOptika.Scripts.Entities
{ {
@ -6,16 +7,23 @@ namespace ProjectOptika.Scripts.Entities
{ {
public int ID { get; private set; } public int ID { get; private set; }
[DisplayName("Тип клиента")]
public ClientType ClientType { get; private set; } public ClientType ClientType { get; private set; }
[DisplayName("Имя")]
public string FirstName { get; private set; } public string FirstName { get; private set; }
[DisplayName("Отчество")]
public string SecondName { get; private set; } public string SecondName { get; private set; }
[DisplayName("Фамилия")]
public string Surname { get; private set; } public string Surname { get; private set; }
[DisplayName("Номер телефона")]
public string PhoneNumber { get; private set; } public string PhoneNumber { get; private set; }
public string FullName => $"{FirstName} {SecondName} {Surname}";
public static Client CreateEntity(int id, ClientType clientType, string firstName, string secondName, string surname, string phoneNumber) public static Client CreateEntity(int id, ClientType clientType, string firstName, string secondName, string surname, string phoneNumber)
{ {
return new Client return new Client

View File

@ -1,4 +1,5 @@
using ProjectOptika.Scripts.Entities.Enums; using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities namespace ProjectOptika.Scripts.Entities
{ {
@ -6,14 +7,20 @@ namespace ProjectOptika.Scripts.Entities
{ {
public int ID { get; private set; } public int ID { get; private set; }
[DisplayName("Тип сотрудника")]
public PositionEmployee PositionEmployee { get; private set; } public PositionEmployee PositionEmployee { get; private set; }
[DisplayName("Имя")]
public string FirstName { get; private set; } public string FirstName { get; private set; }
[DisplayName("Отчество")]
public string SecondName { get; private set; } public string SecondName { get; private set; }
[DisplayName("Фамилия")]
public string Surname { get; private set; } public string Surname { get; private set; }
public string FullName => $"{FirstName} {SecondName} {Surname}";
public static Employee CreateEntity(int id, PositionEmployee positionEmployee, string firstName, string secondName, string surname) { public static Employee CreateEntity(int id, PositionEmployee positionEmployee, string firstName, string secondName, string surname) {
return new Employee return new Employee
{ {

View File

@ -1,19 +1,45 @@
namespace ProjectOptika.Scripts.Entities using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{ {
public class Order public class Order
{ {
public int ID { get; private set; } public int ID { get; private set; }
[Browsable(false)]
public int EmployeeID { get; private set; } public int EmployeeID { get; private set; }
[Browsable(false)]
public int ClientID { get; private set; } public int ClientID { get; private set; }
[DisplayName("Дата заказа")]
public DateTime OrderDate { get; private set; } public DateTime OrderDate { get; private set; }
[DisplayName("Общая стоимость")]
public double TotalCost { get; private set; } public double TotalCost { get; private set; }
[DisplayName("Клиент")]
public string ClientFullName { get; private set; }
[DisplayName("Работник")]
public string EmployeeFullName { get; private set; }
[DisplayName("Заказ")]
public string AccessoryOrder => AccesoriesOrders != null ?
string.Join(", ", AccesoriesOrders.Select(x => x != null ? $"{x.AccessoryName} {x.Count}" : string.Empty)) :
string.Empty;
[Browsable(false)]
public IEnumerable<AccessoriesOrder> AccesoriesOrders { get; private set; } = []; public IEnumerable<AccessoriesOrder> AccesoriesOrders { get; private set; } = [];
public void SetAccessriesOrderReplenishment(IEnumerable<AccessoriesOrder> accesoriesOrders)
{
if (accesoriesOrders != null && accesoriesOrders.Any())
{
AccesoriesOrders = accesoriesOrders;
}
}
public static Order CreateOperation(int id, int employeeID, int clientID, double totalCost, IEnumerable<AccessoriesOrder> accesoriesOrders) public static Order CreateOperation(int id, int employeeID, int clientID, double totalCost, IEnumerable<AccessoriesOrder> accesoriesOrders)
{ {
return new Order { return new Order {

View File

@ -1,19 +1,30 @@
namespace ProjectOptika.Scripts.Entities using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{ {
public class Specifications public class Specifications
{ {
public int ID { get; private set; } public int ID { get; private set; }
[Browsable(false)]
public int AccessoriesID { get; private set; } public int AccessoriesID { get; private set; }
[DisplayName("Наименование аксессуара")]
public string AccessoriesName { get; private set; }
[DisplayName("Материал")]
public string Material { get; private set; } public string Material { get; private set; }
[DisplayName("Астигматизм")]
public string Astigmatism { get; private set; } public string Astigmatism { get; private set; }
[DisplayName("Диоптрийность")]
public string Dioptericity { get; private set; } public string Dioptericity { get; private set; }
[DisplayName("Страна изготовителя")]
public string OriginCountry { get; private set; } public string OriginCountry { get; private set; }
[DisplayName("Время производства")]
public double TimeProduction { get; private set; } public double TimeProduction { get; private set; }
public static Specifications CreateEntity(int id, int accessoriesID, string material, string astigmatism, string dioptericity, string originCountry, double timeProduction) public static Specifications CreateEntity(int id, int accessoriesID, string material, string astigmatism, string dioptericity, string originCountry, double timeProduction)

View File

@ -79,7 +79,11 @@ namespace ProjectOptika.Scripts.Forms
} }
} }
private void LoadList() => dataGridView.DataSource = _accessoriesRepositories.GetAccessories(); private void LoadList()
{
dataGridView.DataSource = _accessoriesRepositories.GetAccessories();
dataGridView.Columns["ID"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id) private bool TryGetIdentifierFromSelectedRows(out int id)
{ {

View File

@ -79,7 +79,12 @@ namespace ProjectOptika.Scripts.Forms
} }
} }
private void LoadList() => dataGridView.DataSource = _clientRepositories.GetClients(); private void LoadList()
{
dataGridView.DataSource = _clientRepositories.GetClients();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id) private bool TryGetIdentifierFromSelectedRows(out int id)
{ {

View File

@ -79,7 +79,12 @@ namespace ProjectOptika.Scripts.Forms
} }
} }
private void LoadList() => dataGridView.DataSource = _employeeRepositories.GetEmployees(); private void LoadList()
{
dataGridView.DataSource = _employeeRepositories.GetEmployees();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id) private bool TryGetIdentifierFromSelectedRows(out int id)
{ {

View File

@ -15,11 +15,11 @@ namespace ProjectOptika.Scripts.Forms
throw new ArgumentNullException(nameof(orderRepository)); throw new ArgumentNullException(nameof(orderRepository));
comboBoxEmployee.DataSource = employeeRepository.GetEmployees(); comboBoxEmployee.DataSource = employeeRepository.GetEmployees();
comboBoxEmployee.DisplayMember = "Surname"; comboBoxEmployee.DisplayMember = "FullName";
comboBoxEmployee.ValueMember = "ID"; comboBoxEmployee.ValueMember = "ID";
comboBoxClient.DataSource = clientRepositiory.GetClients(); comboBoxClient.DataSource = clientRepositiory.GetClients();
comboBoxClient.DisplayMember = "Surname"; comboBoxClient.DisplayMember = "FullName";
comboBoxClient.ValueMember = "ID"; comboBoxClient.ValueMember = "ID";
ColumnAccessory.DataSource = accessoriesRepository.GetAccessories(); ColumnAccessory.DataSource = accessoriesRepository.GetAccessories();

View File

@ -76,7 +76,7 @@
dataGridView.AllowUserToResizeRows = false; dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill; dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0); dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false; dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView"; dataGridView.Name = "dataGridView";
@ -84,7 +84,7 @@
dataGridView.RowHeadersVisible = false; dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51; dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(800, 450); dataGridView.Size = new Size(693, 450);
dataGridView.TabIndex = 9; dataGridView.TabIndex = 9;
// //
// FormItemOrders // FormItemOrders

View File

@ -30,8 +30,12 @@ namespace ProjectOptika.Scripts.Forms
} }
} }
private void LoadList() => dataGridView.DataSource = private void LoadList()
_orderRepository.GetOrders(); {
dataGridView.DataSource = _orderRepository.GetOrders();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["OrderDate"].DefaultCellStyle.Format = "dd MM yyyy";
}
private bool TryGetIdentifierFromSelectedRow(out int id) private bool TryGetIdentifierFromSelectedRow(out int id)
{ {

View File

@ -79,7 +79,11 @@ namespace ProjectOptika.Scripts.Forms
} }
} }
private void LoadList() => dataGridView.DataSource = _specificationRepositories.GetSpecifications(); private void LoadList()
{
dataGridView.DataSource = _specificationRepositories.GetSpecifications();
dataGridView.Columns["ID"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id) private bool TryGetIdentifierFromSelectedRows(out int id)
{ {

View File

@ -21,7 +21,7 @@ namespace ProjectOptika.Scripts.Reports
{ {
new PdfBuilder(filePath) new PdfBuilder(filePath)
.AddHeader("Учет оплат клиентов") .AddHeader("Учет оплат клиентов")
.AddPieChart($"Оплаты клиентов", GetData(dateTime)) .AddPieChart($"Оплаты клиентов за {dateTime: dd MMMM yyyy}", GetData(dateTime))
.Build(); .Build();
return true; return true;
} }
@ -33,18 +33,12 @@ namespace ProjectOptika.Scripts.Reports
} }
private List<(string Caption, double Value)> GetData(DateTime dateTime) private List<(string Caption, double Value)> GetData(DateTime dateTime)
{ {
var orders = _orderRepository.GetOrders() return _orderRepository.GetOrders(startDate: dateTime.Date, endDate: dateTime.Date.AddDays(1))
.Where(x => x.OrderDate.Date == dateTime.Date) .GroupBy(x => x.ClientFullName, (key, group) => new {
.ToList(); Client = key,
var totalCosts = orders.Count;
return orders
.GroupBy(x => x.ClientID, (key, group) => new {
ClientID = key,
Count = group.Sum(x => x.TotalCost) Count = group.Sum(x => x.TotalCost)
}) })
.Select(x => (x.ClientID.ToString(), (double)x.Count / totalCosts * 100)) .Select(x => (x.Client, (double)x.Count))
.ToList(); .ToList();
} }
} }

View File

@ -27,7 +27,7 @@ namespace ProjectOptika.Scripts.Reports
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader("Сводка по заказам", 0, 4) .AddHeader("Сводка по заказам", 0, 4)
.AddParagraph("за период", 0) .AddParagraph($"за период c {startDate: dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable([15, 20, 25], GetData(emplyeeID, startDate, endDate)) .AddTable([15, 20, 25], GetData(emplyeeID, startDate, endDate))
.Build(); .Build();
return true; return true;
@ -39,11 +39,11 @@ namespace ProjectOptika.Scripts.Reports
} }
} }
private List<string[]> GetData(int emplyeeID, DateTime startDate, DateTime endDate) private List<string[]> GetData(int employeeID, DateTime startDate, DateTime endDate)
{ {
var orders = _orderRepository.GetOrders(startDate, endDate); var orders = _orderRepository.GetOrders(startDate: startDate, endDate: endDate, employeeID: employeeID);
var employees = _employeeRepository.GetEmployees(); var employees = _employeeRepository.GetEmployees();
var employeesNames = _employeeRepository.GetEmployees().ToDictionary(d => d.ID, d => d.Surname); var employeesNames = _employeeRepository.GetEmployees().ToDictionary(d => d.ID, d => d.FullName);
var clientsNames = _clientRepositiory.GetClients().ToList(); var clientsNames = _clientRepositiory.GetClients().ToList();
var data = orders var data = orders
@ -54,7 +54,6 @@ namespace ProjectOptika.Scripts.Reports
ClientID = r.ClientID, ClientID = r.ClientID,
TotalCost = r.TotalCost TotalCost = r.TotalCost
}) })
.Where(x => x.EmployeeID == emplyeeID)
.OrderBy(x => x.Date) .OrderBy(x => x.Date)
.GroupBy(x => x.Date) .GroupBy(x => x.Date)
.Select(g => new .Select(g => new
@ -70,7 +69,7 @@ namespace ProjectOptika.Scripts.Reports
result.Add(new string[] result.Add(new string[]
{ {
entry.Date.ToString("dd.MM.yyyy"), entry.Date.ToString("dd.MM.yyyy"),
employeesNames.ContainsKey(emplyeeID) ? employeesNames[emplyeeID] : string.Empty, employeesNames.ContainsKey(employeeID) ? employeesNames[employeeID] : string.Empty,
entry.Totals.ToString(), entry.Totals.ToString(),
}); });
} }

View File

@ -85,13 +85,73 @@ namespace ProjectOptika.Scripts.Repositories.Implementations
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
var builder = new QueryBuilder();
if (startDate.HasValue)
{
builder.AddCondition("z.OrderDate >= @startDate");
}
if (endDate.HasValue)
{
builder.AddCondition("z.OrderDate <= @endDate");
}
if (id.HasValue)
{
builder.AddCondition("z.ID = @id");
}
if (employeeID.HasValue)
{
builder.AddCondition("z.EmployeeID = @employeeID");
}
if (clientID.HasValue)
{
builder.AddCondition("z.ClientID = @clientID");
}
if (totalCost.HasValue)
{
builder.AddCondition("z.TotalCost = @totalCost");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Zakaz"; var querySelect = @$"
var orders = SELECT
connection.Query<Order>(querySelect); z.*,
_logger.LogDebug("Полученные объекты: {json}", CONCAT(c.Surname, ' ', c.FirstName) as ClientFullName,
JsonConvert.SerializeObject(orders)); CONCAT(e.Surname, ' ', e.FirstName) as EmployeeFullName,
return orders;
a.Name as AccessoryName,
ao.AccessoriesID,
ao.Count
FROM Zakaz z
LEFT JOIN Client c ON c.ID = z.ClientID
LEFT JOIN Employee e ON e.ID = z.EmployeeID
INNER JOIN AccessoriesOrder ao ON ao.ZakazID = z.ID
LEFT JOIN Accessories a ON a.ID = ao.AccessoriesID
{builder.Build()}";
var orderHelperDict = new Dictionary<int, List<AccessoriesOrder>>();
var orderes = new Dictionary<int, List<Order>>();
var orders = connection.Query<Order, AccessoriesOrder, Order>(querySelect,
(order, accessoriesOrders) =>
{
if (!orderHelperDict.TryGetValue(order.ID, out var z))
{
z = new List<AccessoriesOrder>();
orderHelperDict.Add(order.ID, z);
}
z.Add(accessoriesOrders);
return order;
}, splitOn: "AccessoryName", param: new { startDate, endDate, totalCost, id, employeeID, clientID });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orderHelperDict.Select(x =>
{
var r = orders.First(y => y.ID == x.Key);
r.SetAccessriesOrderReplenishment(x.Value);
return r;
}).ToArray();
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -0,0 +1,27 @@
using System.Text;
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}";
}
}