ПИбд-21. Штыркин Е.Д. Лабораторная работа №4 #4

Closed
Shtyrkin_Egor wants to merge 3 commits from LabWork_4 into LabWork_3
20 changed files with 235 additions and 66 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,12 +11,18 @@ public class Client
{
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 string Info => $"{Name} {Address}";
[DisplayName("Возраст")]
public int Age { get; private set; }
[DisplayName("Заработок")]
public double Earnings { get; private set; }
public static Client CreateEntity(int id, string name, string address, int age, double earnings)

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,10 +11,20 @@ public class Delivery
{
public int Id { get; private set; }
[Browsable(false)]
public int WorkerId { get; private set; }
[DisplayName("Работник")]
public string WorkerName { get; private set; } = string.Empty;
[DisplayName("Дата доставки")]
public DateTime DateDelivery { get; private set; }
public string Product => DeliveryProducts != null ?
string.Join(",", DeliveryProducts.Select(x => $"{x.ProductName} {x.Count}")) :
string.Empty;
[Browsable(false)]
public IEnumerable<DeliveryProduct> DeliveryProducts { get; private set; } = [];
public static Delivery CreateOperation(int id, int workerId, IEnumerable<DeliveryProduct> deliveryProducts)
@ -27,15 +38,11 @@ public class Delivery
};
}
public static Delivery CreateOperation(TempDeliveryProduct tempDeliveryProduct,
IEnumerable<DeliveryProduct> deliveryProducts)
public void SetDeliveryProducts(IEnumerable<DeliveryProduct> deliveryProducts)
{
return new Delivery
if(deliveryProducts != null && deliveryProducts.Any())
{
Id = tempDeliveryProduct.Id,
WorkerId = tempDeliveryProduct.WorkerId,
DateDelivery = tempDeliveryProduct.DateDelivery,
DeliveryProducts = deliveryProducts
};
DeliveryProducts = deliveryProducts;
}
}
}

View File

@ -12,6 +12,8 @@ public class DeliveryProduct
public int ProductId { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public int Count { get; private set; }
public static DeliveryProduct CreateElement(int id, int productId, int count)

View File

@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
@ -10,14 +12,28 @@ public class Invoice
{
public int Id { get; private set; }
[Browsable(false)]
public int WorkerId { get; private set; }
[Browsable(false)]
public int ClientId { get; private set; }
[Browsable(false)]
public int ProductId { get; private set; }
[DisplayName("Изделие")]
public string ProductName { get; private set; } = string.Empty;
[DisplayName("Работник")]
public string WorkerName { get; private set; } = string.Empty;
[DisplayName("Клиент")]
public string ClientName { get; private set; } = string.Empty;
[DisplayName("Дата оформления заказа")]
public DateTime Date { get; private set; }
[DisplayName("Количество купленных изделий")]
public int CountProduct { get; private set; }
public static Invoice CreateOperation(int id, int workerId, int clientId, int productId, int countProduct)

View File

@ -1,6 +1,7 @@
using FurnitureCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -11,10 +12,13 @@ public class Product
{
public int Id { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Метариал изделия")]
public Material Material { get; private set; }
[DisplayName("Цена")]
public double Price { get; private set; }
public static Product CreateEntity(int id, Material material, string name, double price)

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureCompany.Entities;
public class TempDeliveryProduct
{
public int Id { get; private set; }
public int WorkerId { get; private set; }
public DateTime DateDelivery { get; private set; }
public int ProductId { get; private set; }
public int Count { get; private set; }
}

View File

@ -1,6 +1,9 @@
using FurnitureCompany.Entities.Enums;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using DocumentFormat.OpenXml.Wordprocessing;
using FurnitureCompany.Entities.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -11,10 +14,15 @@ public class Worker
{
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 => $"{FirstName} {LastName}";
[DisplayName("Уровень опыта")]
public WorkerPost WorkerPost { get; private set; }
public static Worker CreateEntity(int id, string firstName, string lastName, WorkerPost workerPost)

View File

@ -95,8 +95,12 @@ namespace FurnitureCompany.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _clientRepository.ReadClients();
private void LoadList()
{
dataGridViewData.DataSource = _clientRepository.ReadClients();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["Info"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -26,7 +26,7 @@ namespace FurnitureCompany.Forms
throw new ArgumentNullException(nameof(deliveryRepository));
comboBoxWorker.DataSource = workerRepository.ReadWorkers();
comboBoxWorker.DisplayMember = "FirstName";
comboBoxWorker.DisplayMember = "FullName";
comboBoxWorker.ValueMember = "Id";
ColumnProduct.DataSource = productRepository.ReadProducts();
@ -38,12 +38,27 @@ namespace FurnitureCompany.Forms
{
try
{
if (dataGridViewProducts.RowCount < 1 ||
if (dataGridViewProducts.RowCount < 1 || dataGridViewProducts.ColumnCount == null ||
comboBoxWorker.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
for (int i = 0; i < dataGridViewProducts.Rows.Count - 1; i++)
{
var row = dataGridViewProducts.Rows[i];
var countCell = row.Cells["ColumnCount"];
if (countCell.Value == null || string.IsNullOrWhiteSpace(countCell.Value.ToString()))
{
Console.WriteLine($"Пустая ячейка в строке {row.Index}, столбце {countCell.ColumnIndex}");
throw new Exception("Имеются незаполненные поля");
}
else
{
Console.WriteLine($"Значение в строке {row.Index}, столбце {countCell.ColumnIndex}: {countCell.Value}");
}
}
_deliveryRepository.CreateDelivery(Delivery.CreateOperation(0,
(int)comboBoxWorker.SelectedValue!, CreateListDeliveryProductFromDataGrid()));

View File

@ -77,8 +77,12 @@ namespace FurnitureCompany.Forms
}
}
private void LoadList() => dataGridView.DataSource = _deliveryRepository.ReadDeliverys();
private void LoadList()
{
dataGridView.DataSource = _deliveryRepository.ReadDeliverys();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["DateDelivery"].DefaultCellStyle.Format = "dd.MM.yyyy";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -84,7 +84,7 @@
Controls.Add(checkBoxWorkers);
Controls.Add(checkBoxClients);
Name = "FormDirectoryReport";
Text = "FormDirectoryReport";
Text = "Отчёт о компании";
ResumeLayout(false);
PerformLayout();
}

View File

@ -27,7 +27,7 @@ namespace FurnitureCompany.Forms
throw new ArgumentNullException(nameof(invoiceRepository));
comboBoxWorker.DataSource = workerRepository.ReadWorkers();
comboBoxWorker.DisplayMember = "FirstName";
comboBoxWorker.DisplayMember = "FullName";
comboBoxWorker.ValueMember = "Id";
comboBoxProduct.DataSource = productRepository.ReadProducts();
@ -35,7 +35,7 @@ namespace FurnitureCompany.Forms
comboBoxProduct.ValueMember = "Id";
comboBoxClient.DataSource = clientRepository.ReadClients();
comboBoxClient.DisplayMember = "Name";
comboBoxClient.DisplayMember = "Info";
comboBoxClient.ValueMember = "Id";
}

View File

@ -54,6 +54,11 @@ namespace FurnitureCompany.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _invoiceRepository.ReadInvoices();
private void LoadList()
{
dataGridViewData.DataSource = _invoiceRepository.ReadInvoices();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["Date"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
}
}

View File

@ -95,8 +95,11 @@ namespace FurnitureCompany.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _productRepository.ReadProducts();
private void LoadList()
{
dataGridViewData.DataSource = _productRepository.ReadProducts();
dataGridViewData.Columns["Id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -95,8 +95,12 @@ namespace FurnitureCompany.Forms
}
}
private void LoadList() => dataGridViewData.DataSource = _workerRepository.ReadWorkers();
private void LoadList()
{
dataGridViewData.DataSource = _workerRepository.ReadWorkers();
dataGridViewData.Columns["Id"].Visible = false;
dataGridViewData.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -28,7 +28,7 @@ internal class ChartReport
{
new PdfBuilder(filePath)
.AddHeader("Оформление заказа")
.AddPieChart("Проданные изделия", GetData(dateTime))
.AddPieChart($"Проданные изделия за {dateTime: dd MMMM yyyy}", GetData(dateTime))
.Build();
return true;
}
@ -41,10 +41,9 @@ internal class ChartReport
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _invoiceRepository
.ReadInvoices()
.Where(x => x.Date.Date == dateTime.Date)
.GroupBy(x => x.ClientId, (key, group) => new { Id = key, Count = group.Sum(x => x.CountProduct) })
.Select(x => (x.Id.ToString(), (double)x.Count))
.ReadInvoices(dateFrom: dateTime.Date, dateTo: dateTime.Date.AddDays(1))
.GroupBy(x => x.ClientName, (key, group) => new { ClientName = key, Count = group.Sum(x => x.CountProduct) })
.Select(x => (x.ClientName, (double)x.Count))
.ToList();
}
}

View File

@ -35,7 +35,7 @@ internal class TableReport
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по доставке изделий", 0, 4)
.AddParagraph("за период", 0)
.AddParagraph($"за период c {startDate:dd.MM.yyyy} пo {endDate: dd.MM.yyyy}", 0)
.AddTable([10, 10, 15, 15], GetData(productId, startDate, endDate))
.Build();
@ -51,20 +51,18 @@ internal class TableReport
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate)
{
var data = _deliveryRepository
.ReadDeliverys()
.Where(x => x.DateDelivery >= startDate && x.DateDelivery <= endDate && x.DeliveryProducts.Any(y => y.ProductId == productId))
.Select(x => new { x.WorkerId, Date = x.DateDelivery, CountIn = x.DeliveryProducts.FirstOrDefault(y => y.ProductId == productId)?.Count, CountOut = (int?)null })
.ReadDeliverys(dateFrom: startDate, dateTo: endDate, productId: productId)
.Select(x => new { x.WorkerName, Date = x.DateDelivery, CountIn = x.DeliveryProducts.FirstOrDefault(y => y.ProductId == productId)?.Count, CountOut = (int?)null })
.Union(
_invoiceRepository
.ReadInvoices()
.Where(x => x.Date >= startDate && x.Date <= endDate)
.Select(x => new { x.WorkerId, Date = x.Date, CountIn = (int?)null, CountOut = (int?)x.CountProduct }))
.ReadInvoices(dateFrom: startDate, dateTo: endDate, productId: productId)
.Select(x => new { x.WorkerName, Date = x.Date, CountIn = (int?)null, CountOut = (int?)x.CountProduct }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.WorkerId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Select(x => new string[] { x.WorkerName.ToString(), x.Date.ToString("dd.MM.yyyy"), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty }))
.Union(
[["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
.ToList();

View File

@ -83,15 +83,59 @@ public class DeliveryRepository : IDeliveryRepository
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("d.DateDelivery >= @dateFrom");
}
if (dateTo.HasValue)
{
builder.AddCondition("d.DateDelivery <= @dateTo");
}
if (productId.HasValue)
{
builder.AddCondition("dp.ProductId = @productId");
}
if (workerId.HasValue)
{
builder.AddCondition("d.WorkerId = @workerId");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT fr.*, ffr.ProductId, ffr.Count FROM Deliverys fr
INNER JOIN DeliveryProducts ffr ON ffr.DeliveryId = fr.Id";
var deliverys = connection.Query<TempDeliveryProduct>(querySelect);
var querySelect = $@"
SELECT
d.*,
CONCAT(w.LastName, ' ', w.FirstName) as WorkerName,
dp.ProductID,
dp.Count,
p.Name as ProductName
FROM Deliverys d
LEFT JOIN Workers w on w.Id = d.WorkerId
INNER JOIN DeliveryProducts dp ON dp.DeliveryId = d.Id
LEFT JOIN Products p on p.Id = dp.ProductId
{builder.Build()}";
var deliveryDict = new Dictionary<int, List<DeliveryProduct>>();
var deliverys = connection.Query<Delivery, DeliveryProduct, Delivery>(querySelect,
(deliver, deliveryy) =>
{
if(!deliveryDict.TryGetValue(deliver.Id, out var dyp))
{
dyp = [];
deliveryDict.Add(deliver.Id, dyp);
}
dyp.Add(deliveryy);
return deliver;
}, splitOn: "ProductId", param: new { dateFrom, dateTo, productId, workerId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(deliverys));
return deliverys.GroupBy(x => x.Id, y => y,
(key, value) => Delivery.CreateOperation(value.First(),
value.Select(z => DeliveryProduct.CreateElement(0, z.ProductId, z.Count)))).ToList();
return deliveryDict.Select(x =>
{
var d = deliverys.First(y => y.Id == x.Key);
d.SetDeliveryProducts(x.Value);
return d;
}).ToArray();
}
catch (Exception ex)
{

View File

@ -49,10 +49,40 @@ public class InvoiceRepository : IInvoiceRepository
try
{
var builder =new QueryBuilder();
if (dateFrom.HasValue)
{
builder.AddCondition("i.Date >= @dateFrom");
}
if (dateTo.HasValue)
{
builder.AddCondition("i.Date <= @dateTo");
}
if (productId.HasValue)
{
builder.AddCondition("i.ProductId = @productId");
}
if (workerId.HasValue)
{
builder.AddCondition("i.WorkerId = @workerId");
}
if (clientId.HasValue)
{
builder.AddCondition("i.ClientId = @clientId");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Invoices";
var invoices = connection.Query<Invoice>(querySelect);
var querySelect = $@"SELECT
i.*,
p.Name as ProductName,
CONCAT(w.LastName, ' ', w.FirstName) as WorkerName,
CONCAT(c.Address, ' ', c.Name) as ClientName
FROM Invoices i
LEFT JOIN Products p on p.Id = i.ProductId
LEFT JOIN Workers w on w.Id = i.WorkerId
LEFT JOIN Clients c on c.Id = i.ClientId
{builder.Build()}";
var invoices = connection.Query<Invoice>(querySelect, new { dateFrom, dateTo, productId, workerId, clientId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(invoices));
return invoices;
}

View File

@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureCompany.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}";
}
}