PIbd-21 Valiulov I.A. LabWork04 #5

Closed
Ilyas wants to merge 2 commits from LabWork04 into LabWork03
20 changed files with 221 additions and 38 deletions

View File

@ -1,10 +1,18 @@
namespace CarpentryWorkshop.Entities;
using System.ComponentModel;
namespace CarpentryWorkshop.Entities;
public class Material
{
public int Id { get; private set; }
[DisplayName("Название материала")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Количество на складе")]
public int Count { get; private set; }
[DisplayName("Зарезервировано")]
public int ReservInWarehouse { get; private set; }
public static Material CreateEntity(int id, string name, int count, int reserveInWarehouse)
{

View File

@ -1,10 +1,18 @@
namespace CarpentryWorkshop.Entities;
using System.ComponentModel;
namespace CarpentryWorkshop.Entities;
public class MaterialReplenishment
{
public int Id { get; private set; }
[DisplayName("Дата пополнения")]
public DateTime DateReplenishment { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; private set; }
public static MaterialReplenishment CreateOperation(int id, string name, int count)
{

View File

@ -1,13 +1,26 @@
using CarpentryWorkshop.Entities.Enums;
using System.ComponentModel;
namespace CarpentryWorkshop.Entities;
public class Order
{
public int Id { get; private set; }
[DisplayName("Дата заказа")]
public DateTime DataOrder { get; private set; }
[DisplayName("Статус")]
public OrderStatus Status { get; private set; }
[DisplayName("Описание")]
public string Description { get; private set; } = string.Empty;
[DisplayName("Изделия")]
public string Products => OrderProduct != null ?
string.Join(", ", OrderProduct.Select(x => $"{x.ProductName} {x.Count}")) : string.Empty;
[Browsable(false)]
public IEnumerable<OrderProduct> OrderProduct { get; private set; } = [];
public static Order CreateOperation(int id, OrderStatus status, string description, IEnumerable<OrderProduct> orderProduct)
{
@ -20,4 +33,11 @@ public class Order
OrderProduct = orderProduct
};
}
public void SetProductMaterial(IEnumerable<OrderProduct> orderProduct)
{
if (orderProduct != null && orderProduct.Any())
{
OrderProduct = orderProduct;
}
}
}

View File

@ -5,6 +5,8 @@ public class OrderProduct
public int Id { get; private set; }
public int ProductId { get; private set; }
public int Count { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public static OrderProduct CreateOperation(int id, int productId, int count)
{
return new OrderProduct

View File

@ -1,13 +1,27 @@
using CarpentryWorkshop.Entities.Enums;
using System.ComponentModel;
namespace CarpentryWorkshop.Entities;
public class Product
{
public int Id { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Тип")]
public ProductType Type { get; private set; }
public string FullProductName => $"{Name} {Type}";
[DisplayName("Материалы")]
public string Products => ProductMaterial != null ?
string.Join(", ", ProductMaterial.Select(x => $"{x.MaterialName} {x.Count}")) : string.Empty;
[DisplayName("Количество на складе")]
public int CountInWarehouse { get; private set; }
[Browsable(false)]
public IEnumerable<ProductMaterial> ProductMaterial { get; set; } = [];
public static Product CreateEntity(int id, string name, ProductType type, int countInWarehouse, IEnumerable<ProductMaterial> productMaterial)
{
@ -20,4 +34,11 @@ public class Product
ProductMaterial = productMaterial
};
}
public void SetProductMaterial(IEnumerable<ProductMaterial> productMaterial)
{
if (productMaterial != null && productMaterial.Any())
{
ProductMaterial = productMaterial;
}
}
}

View File

@ -5,6 +5,7 @@ public class ProductMaterial
public int Id { get; private set; }
public int MaterialId { get; set; }
public int Count { get; set; }
public string MaterialName { get; private set; } = string.Empty;
public static ProductMaterial CreateOperation(int id, int materialId, int count)
{
return new ProductMaterial

View File

@ -76,7 +76,11 @@ namespace CarpentryWorkshop.Forms
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _materialRepository.ReadMaterials();
private void LoadList()
{
dataGridView.DataSource = _materialRepository.ReadMaterials();
dataGridView.Columns["Id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -55,7 +55,12 @@ namespace CarpentryWorkshop.Forms
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _materialSpentRepository.ReadMaterialsSpent();
private void LoadList()
{
dataGridView.DataSource = _materialSpentRepository.ReadMaterialsSpent();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["DateReplenishment"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -15,7 +15,7 @@ namespace CarpentryWorkshop.Forms
comboBoxStatus.DataSource = Enum.GetValues(typeof(OrderStatus));
ColumnProducts.DataSource = productRepository.ReadProducts();
ColumnProducts.DisplayMember = "Name";
ColumnProducts.DisplayMember = "FullProductName";
ColumnProducts.ValueMember = "Id";
}
private void ButtonAdd_Click(object sender, EventArgs e)

View File

@ -56,7 +56,12 @@ namespace CarpentryWorkshop.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["DataOrder"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -74,7 +74,12 @@ namespace CarpentryWorkshop.Forms
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridView.DataSource = _productRepository.ReadProducts();
private void LoadList()
{
dataGridView.DataSource = _productRepository.ReadProducts();
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["FullProductName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -20,7 +20,7 @@ internal class ChartReport
{
new PdfBuilder(filePath)
.AddHeader("Пополенение материала")
.AddPieChart("Виды материалов", GetData(dateTime))
.AddPieChart($"Пополнение материала на {dateTime:dd MMMM yyyy}", GetData(dateTime))
.Build();
return true;
}
@ -33,10 +33,9 @@ internal class ChartReport
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _materialReplenishmentRepository
.ReadMaterialsSpent()
.Where(x => x.DateReplenishment.Date == dateTime.Date)
.GroupBy(x => x.Name, (key, group) => new { Id = key, Count = group.Sum(x => x.Count) })
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
.ReadMaterialsSpent(dateForm: dateTime.Date, dateTo: dateTime.Date.AddDays(1))
.GroupBy(x => x.Name, (key, group) => new { Id = key, Count = group.Sum(x => x.Count) })
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
}
}

View File

@ -1,6 +1,5 @@
using CarpentryWorkshop.Repositories;
using Microsoft.Extensions.Logging;
using System.Linq;
namespace CarpentryWorkshop.Reports;
@ -27,7 +26,7 @@ internal class TableReport
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению материала", 0, 3)
.AddParagraph("за период", 0)
.AddParagraph($"за период c {startDate:dd.MM.yyyy} по { endDate: dd.MM.yyyy}", 0)
.AddTable([10, 15, 15], GetData(materialId, startDate, endDate))
.Build();
return true;
@ -42,21 +41,19 @@ internal class TableReport
private List<string[]> GetData(int materialId, DateTime startDate, DateTime endDate)
{
var data = _materialReplenishmentRepository
.ReadMaterialsSpent()
.Where(x => x.DateReplenishment >= startDate && x.DateReplenishment <= endDate && x.Name == _materialRepository.ReadMaterialById(materialId).Name)
.ReadMaterialsSpent(dateForm: startDate, dateTo: endDate, materialName: _materialRepository.ReadMaterialById(materialId).Name)
.Select(x => new { Date = x.DateReplenishment, CountIn = (int?)x.Count, CountOut = (int?)null })
.Union(
_orderMaterialsRepository
.ReadOrders(materialId)
.Where(x => x.DataOrder >= startDate && x.DataOrder <= endDate)
.ReadOrders(dateForm: startDate, dateTo: endDate, matid: materialId)
.Select(x => new { Date = x.DataOrder, CountIn = (int?)null, CountOut = (int?)x.Count }))
.OrderBy(x => x.Date);
return new List<string[]>() { item }
.Union(
data
.Select(x => new string[] {x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty}))
.Select(x => new string[] {x.Date.ToString("dd.MM.yyyy"), x.CountIn?.ToString("N0") ?? string.Empty, x.CountOut?.ToString("N0") ?? string.Empty}))
.Union(
[["Всего", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]])
[["Всего", data.Sum(x => x.CountIn ?? 0).ToString("N0"), data.Sum(x => x.CountOut ?? 0).ToString("N0")]])
.ToList();
}
}

View File

@ -4,7 +4,7 @@ namespace CarpentryWorkshop.Repositories;
public interface IMaterialReplenishmentRepository
{
IEnumerable<MaterialReplenishment> ReadMaterialsSpent();
IEnumerable<MaterialReplenishment> ReadMaterialsSpent(DateTime? dateForm = null, DateTime? dateTo = null, string? materialName = null);
MaterialReplenishment ReadMaterialSpentById(int id);
void CreateMaterialSpent(MaterialReplenishment material);
void UpdateMaterialSpent(MaterialReplenishment material);

View File

@ -4,5 +4,5 @@ namespace CarpentryWorkshop.Repositories;
public interface IOrderMaterialsRepository
{
IEnumerable<TempOrder> ReadOrders(int id);
IEnumerable<TempOrder> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? matid = null);
}

View File

@ -80,14 +80,30 @@ public class MaterialReplenishmentRepository : IMaterialReplenishmentRepository
}
}
public IEnumerable<MaterialReplenishment> ReadMaterialsSpent()
public IEnumerable<MaterialReplenishment> ReadMaterialsSpent(DateTime? dateForm = null, DateTime? dateTo = null, string? materialName = null)
{
var builder = new QueryBuilder();
if (dateForm.HasValue)
{
builder.AddCondition("datereplenishment >= @dateForm");
}
if (dateTo.HasValue)
{
builder.AddCondition("datereplenishment <= @dateTo");
}
if (materialName != null)
{
builder.AddCondition("Name = @materialName");
}
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM MaterialReplenishment";
var materials = connection.Query<MaterialReplenishment>(querySelect);
var querySelect = @$"
SELECT * FROM MaterialReplenishment
{builder.Build()}";
var materials = connection.Query<MaterialReplenishment>(querySelect, new {dateForm, dateTo, materialName });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials));
return materials;
}

View File

@ -17,18 +17,32 @@ public class OrderMaterialsRepository : IOrderMaterialsRepository
_logger = logger;
}
public IEnumerable<TempOrder> ReadOrders(int matid)
public IEnumerable<TempOrder> ReadOrders(DateTime? dateForm = null, DateTime? dateTo = null, int? matid = null)
{
var builder = new QueryBuilder();
if (dateForm.HasValue)
{
builder.AddCondition("orders.dataorder >= @dateForm");
}
if (dateTo.HasValue)
{
builder.AddCondition("orders.dataorder <= @dateTo");
}
if (matid.HasValue)
{
builder.AddCondition("materialid = @matid");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
var querySelect = @$"
SELECT orders.*, materials.id AS materialid, pm.count*op.count AS count
FROM orders
INNER JOIN orders_products AS op ON orders.id = op.orderid
INNER JOIN products ON op.productid = products.id
INNER JOIN products_materials AS pm ON products.id = pm.productid
INNER JOIN materials ON pm.materialid = materials.id
Where materials.id = @matid";
var orderMaterials = connection.Query<TempOrder>(querySelect, new { matid });
{builder.Build()}";
var orderMaterials = connection.Query<TempOrder>(querySelect, new { dateForm, dateTo, matid });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orderMaterials));
return orderMaterials;
}

View File

@ -75,10 +75,34 @@ public class OrderRepository : IOrderRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Orders";
var order = connection.Query<Order>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(order));
return order;
var querySelect = @"
SELECT orders.*, products.id AS productid, products.name AS productname, op.count AS count
FROM orders
INNER JOIN orders_products AS op ON orders.id = op.orderid
INNER JOIN products ON op.productid = products.id";
var productsDict = new Dictionary<int, List<OrderProduct>>();
var products =
connection.Query<Order, OrderProduct, Order>(querySelect, (order, orderProducts) =>
{
if (!productsDict.TryGetValue(order.Id, out var frr))
{
frr = [];
productsDict.Add(order.Id, frr);
}
frr.Add(orderProducts);
return order;
}, splitOn: "productid", param: new { dateForm, dateTo, orderStatus, orderId});
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(products));
return productsDict.Select(x =>
{
var fr = products.First(y => y.Id == x.Key);
fr.SetProductMaterial(x.Value);
return fr;
}).ToArray();
}
catch (Exception ex)
{

View File

@ -75,10 +75,35 @@ public class ProductRepository : IProductRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Products";
var product = connection.Query<Product>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(product));
return product;
var querySelect = @"
SELECT products.*, materials.id AS materialid, materials.name AS materialname, pm.count AS count
FROM products
INNER JOIN products_materials AS pm ON products.id = pm.productid
INNER JOIN materials ON pm.materialid = materials.id";
var materialsDict = new Dictionary<int, List<ProductMaterial>>();
var materials =
connection.Query<Product, ProductMaterial, Product>(querySelect, (product, productsMaterials) =>
{
if (!materialsDict.TryGetValue(product.Id, out var frr))
{
frr = [];
materialsDict.Add(product.Id, frr);
}
frr.Add(productsMaterials);
return product;
}, splitOn: "materialid");
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(materials));
return materialsDict.Select(x =>
{
var fr = materials.First(y => y.Id == x.Key);
fr.SetProductMaterial(x.Value);
return fr;
}).ToArray();
}
catch (Exception ex)
{

View File

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