PIbd-22 ZagidulinG.A. LabWork04 #4

Closed
Grigorii_Zagidulin wants to merge 5 commits from Lab4 into Lab3
22 changed files with 173 additions and 43 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
@ -10,8 +11,13 @@ namespace Workshop.Entities;
public class Cheque
{
public int Id { get; private set; }
[DisplayName("Дата")]
public DateTime Date { get; private set; }
[DisplayName("Итоговая сумма")]
public double Sum { get; private set; }
public string Product => ChequeProduct != null ?
string.Join(", ", ChequeProduct.Select(x => $"{x.ProductName} {x.Amount}")) : string.Empty;
[Browsable(false)]
public IEnumerable<ChequeProduct> ChequeProduct { get; private set; } = [];
public static Cheque CreateOperation(int id, int sum, IEnumerable<ChequeProduct> products)
@ -33,4 +39,11 @@ public class Cheque
ChequeProduct = chequeProducts
};
}
public void SetChequeProduct(IEnumerable<ChequeProduct> chequeProducts)
{
if (chequeProducts != null && chequeProducts.Any())
{
ChequeProduct = chequeProducts;
}
}
}

View File

@ -10,6 +10,7 @@ public class ChequeProduct
public int ProductId { get; private set; }
public int ChequeId { get; private set; }
public int Amount { get; private set; }
public string ProductName { get; private set; } = string.Empty;
public static ChequeProduct CreateEntity(int productid, int chequeid, int amount)
{
return new ChequeProduct

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,15 @@ namespace Workshop.Entities;
public class Master
{
public int Id { get; private set; }
[DisplayName("Имя")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Фамилия")]
public string LastName { get; private set; } = string.Empty;
[DisplayName("Возраст")]
public int Age { get; private set; }
[DisplayName("Должность")]
public MasterPosition Position { get; private set; }
public string FullName => $"{Name} {LastName}";
public static Master CreateEntity(int id, string name, string lastName, int age, MasterPosition position)
{

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;
@ -9,8 +10,11 @@ namespace Workshop.Entities;
public class Material
{
public int Id { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Количество на складе")]
public int WarehouseAmount { get; private set; }
[DisplayName("Цена")]
public double Price { get; private set; }
public static Material CreateEntity(int id, string name, int warehouseAmount, double price)
{

View File

@ -1,14 +1,20 @@
using System;
using System.ComponentModel;
using Workshop.Entities;
using Workshop.Entities.Enums;
public class Product
{
public int Id { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; private set; }
[DisplayName("Количество на складе")]
public int WarehouseAmount { get; private set; }
[DisplayName("Категория")]
public ProductCategory Category { get; private set; }
[DisplayName("Материалы")]
public IEnumerable<ProductMaterial> Materials { get; private set; } = [];
public static Product CreateEntity(int id, string name, double price, int warehouseAmount,
ProductCategory category, IEnumerable<ProductMaterial> materials)

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,9 +11,17 @@ namespace Workshop.Entities;
public class ProductCreate
{
public int Id { get; private set; }
[Browsable(false)]
public int ProductId { get; private set; }
[Browsable(false)]
public int MasterId { get; private set; }
[DisplayName("Дата создания")]
public DateTime CreatingDate { get; private set; }
[DisplayName("Изделие")]
public string ProductName { get; private set; } = string.Empty;
[DisplayName("Сотрудник")]
public string MasterName { get; private set; } = string.Empty;
public static ProductCreate CreateOperation(int id, int productid, int masterid)
{
return new ProductCreate

View File

@ -58,7 +58,7 @@ namespace Workshop.Forms
return list.GroupBy(
x => x.ProductId,
x => x.Amount,
(id, counts) => ChequeProduct.CreateEntity(0, id, counts.Sum())).ToList();
(id, counts) => ChequeProduct.CreateEntity(id, 0, counts.Sum())).ToList();
}
}
}

View File

@ -50,6 +50,12 @@ namespace Workshop.Forms
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridProductCreatings.DataSource = _chequeRepository.ReadCheques();
private void LoadList()
{
dataGridProductCreatings.DataSource = _chequeRepository.ReadCheques();
dataGridProductCreatings.Columns["Id"].Visible = false;
//dataGridProductCreatings.Columns["ChequeProduct"].Visible = false;
Review

Закомментированного кода быть не должно

Закомментированного кода быть не должно
dataGridProductCreatings.Columns["Date"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
}
}

View File

@ -102,8 +102,11 @@ namespace Workshop.Forms
id = Convert.ToInt32(dataGridViewMasters.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void LoadList() => dataGridViewMasters.DataSource = _masterRepository.ReadMasters();
private void LoadList()
{
dataGridViewMasters.DataSource = _masterRepository.ReadMasters();
dataGridViewMasters.Columns["Id"].Visible = false;
dataGridViewMasters.Columns["FullName"].Visible = false;
}
}
}

View File

@ -101,7 +101,10 @@ namespace Workshop.Forms
id = Convert.ToInt32(dataGridViewMaterials.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void LoadList() => dataGridViewMaterials.DataSource = _materialRepository.ReadMaterials();
private void LoadList()
{
dataGridViewMaterials.DataSource = _materialRepository.ReadMaterials();
dataGridViewMaterials.Columns["Id"].Visible = false;
}
}
}

View File

@ -26,7 +26,7 @@ namespace Workshop.Forms
comboBoxProduct.ValueMember = "Id";
comboBoxMaster.DataSource = masterRepository.ReadMasters();
comboBoxMaster.DisplayMember = "LastName";
comboBoxMaster.DisplayMember = "FullName";
comboBoxMaster.ValueMember = "Id";
}

View File

@ -68,7 +68,12 @@ namespace Workshop.Forms
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridProductCreatings.DataSource = _productCreateRepository.ReadProductCreates();
private void LoadList()
{
dataGridProductCreatings.DataSource = _productCreateRepository.ReadProductCreates();
dataGridProductCreatings.Columns["Id"].Visible = false;
dataGridProductCreatings.Columns["CreatingDate"].DefaultCellStyle.Format = "dd MMMM yyyy hh:mm";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;

View File

@ -100,6 +100,11 @@ namespace Workshop.Forms
id = Convert.ToInt32(dataGridViewProducts.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void LoadList() => dataGridViewProducts.DataSource = _productRepository.ReadProducts();
private void LoadList()
{
dataGridViewProducts.DataSource = _productRepository.ReadProducts();
dataGridViewProducts.Columns["Id"].Visible = false;
dataGridViewProducts.Columns["Materials"].Visible = false;
}
}
}

View File

@ -10,9 +10,6 @@ namespace Workshop
{
internal static class Program
{
//TODO: 1. Update со связью МкМ.
//TODO: Спросить про заполнение связей МкМ в FormProduct
//TODO: Спросить про заполнение колонки materials в таблице
/// <summary>
/// The main entry point for the application.
/// </summary>

View File

@ -24,7 +24,7 @@ internal class ChartReport
{
new PDFBuilder(filePath)
.AddHeader("Создание изделий")
.AddPieChart("Изделия", GetData(dateTimeStart, dateTimeEnd))
.AddPieChart($"Созданные изделия за период с {dateTimeStart:dd.MM.yyyy} по {dateTimeEnd:dd.MM.yyyy}", GetData(dateTimeStart, dateTimeEnd))
.Build();
return true;
}
@ -43,14 +43,13 @@ internal class ChartReport
private List<(string Caption, double Value)> GetData(DateTime dateTimeStart, DateTime dateTimeEnd)
{
return _creatingRepository
.ReadProductCreates()
.Where(x => x.CreatingDate >= dateTimeStart && x.CreatingDate <= dateTimeEnd)
.GroupBy(x => x.ProductId, (key, group) => new
.ReadProductCreates(dateFrom: dateTimeStart, dateTo: dateTimeEnd)
.GroupBy(x => x.ProductName, (key, group) => new
{
Id = key,
ProductName = key,
Count = group.Count()
})
.Select(x => (x.Id.ToString(), (double)x.Count))
.Select(x => (x.ProductName.ToString(), (double)x.Count))
.ToList();
}
}

View File

@ -31,17 +31,17 @@ internal class DocReport
if (includeMaster)
{
builder.AddParagraph("Мастера")
builder.AddHeader("Мастера")
.AddTable([2400, 2400, 1200, 2400], GetMasters());
}
if (includeMaterial)
{
builder.AddParagraph("Материалы")
builder.AddHeader("Материалы")
.AddTable([2400, 1200, 1200], GetMaterials());
}
if (includeProduct)
{
builder.AddParagraph("Изделия")
builder.AddHeader("Изделия")
.AddTable([2400, 1200, 1200, 2400], GetProducts());
}
builder.Build();

View File

@ -17,13 +17,13 @@ namespace Workshop.Reports
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, long productId, DateTime startDate, DateTime endDate)
public bool CreateTable(string filePath, int productId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению изделия", 0, 3)
.AddParagraph("за период", 0)
.AddParagraph($"за период с {startDate:dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable([15, 15, 15, 15], GetData(productId, startDate,
endDate))
.Build();
@ -35,13 +35,11 @@ namespace Workshop.Reports
return false;
}
}
private List<string[]> GetData(long productId, DateTime startDate, DateTime
private List<string[]> GetData(int productId, DateTime startDate, DateTime
endDate)
{
var data = _chequeRepository
.ReadCheques()
.Where(x => x.Date >= startDate && x.Date <= endDate &&
x.ChequeProduct.Any(y => y.ProductId == productId))
.ReadCheques(dateFrom: startDate, dateTo: endDate, productId: productId)
.Select(x => new
{
Date = x.Date,

View File

@ -27,7 +27,8 @@ internal class WordBuilder
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
//TODO прописать настройки под жирный текст
var runProperties = run.AppendChild(new RunProperties());
runProperties.AppendChild(new Bold());
run.AppendChild(new Text(header));
return this;
}

View File

@ -9,6 +9,6 @@ namespace Workshop.Repositories;
public interface IChequeRepository
{
IEnumerable<Cheque> ReadCheques(DateTime? dateFrom = null, DateTime? dateTo = null, int? chequeId = null);
IEnumerable<Cheque> ReadCheques(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null);
void CreateCheque(Cheque cheque);
}

View File

@ -43,7 +43,7 @@ INSERT INTO CHEQUE_PRODUCT (ProductID, ChequeID, Amount)
VALUES (@ProductId, @ChequeID, @Amount)";
foreach (var elem in cheque.ChequeProduct)
{
connection.Execute(querySubInsert, new {chequeId, elem.ProductId, elem.Amount});
connection.Execute(querySubInsert, new { elem.ProductId, chequeId, elem.Amount});
}
transaction.Commit();
}
@ -54,21 +54,47 @@ VALUES (@ProductId, @ChequeID, @Amount)";
}
}
public IEnumerable<Cheque> ReadCheques(DateTime? dateFrom = null, DateTime? dateTo = null, int? chequeId = null)
public IEnumerable<Cheque> ReadCheques(DateTime? dateFrom = null, DateTime? dateTo = null, int? productId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
builder.AddCondition("c.Date >= @dateFrom");
if (dateTo.HasValue)
builder.AddCondition("c.Date <= @dateTo");
if (productId.HasValue)
builder.AddCondition("cp.ProductId = @productId");
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT c.*, cp.ProductId, cp.Amount " + "FROM cheque c " +
"INNER JOIN cheque_product cp ON cp.ChequeId = c.Id";
var cheques = connection.Query<TempChequeProduct>(querySelect);
var querySelect = @$"SELECT
c.*,
cp.ProductId,
cp.Amount,
p.Name as ""ProductName""
FROM Cheque c
INNER JOIN Cheque_Product cp on cp.ChequeId = c.Id
LEFT JOIN Product p on p.Id = cp.ProductId
{builder.Build()}";
var productDict = new Dictionary<int, List<ChequeProduct>>();
var cheques = connection.Query<Cheque, ChequeProduct, Cheque>(querySelect,
(cheque, chequeproduct) =>
{
if (!productDict.TryGetValue(cheque.Id, out var cp))
{
cp = [];
productDict.Add(cheque.Id, cp);
}
cp.Add(chequeproduct);
return cheque;
}, splitOn: "ProductId", param: new { dateFrom, dateTo, productId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(cheques));
return cheques.GroupBy(x => x.Id, y => y,
(key, value) =>
Cheque.CreateOperation(value.First(),
value.Select(z =>
ChequeProduct.CreateEntity(z.ProductId, z.Id, z.Amount)))).ToList();
return productDict.Select(x =>
{
var c = cheques.First(y => y.Id == x.Key);
c.SetChequeProduct(x.Value);
return c;
}).ToArray();
}
catch (Exception ex)
{

View File

@ -67,9 +67,25 @@ WHERE Id=@id";
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (dateFrom.HasValue)
builder.AddCondition("pc.CreatingDate >= @dateFrom");
if (dateTo.HasValue)
builder.AddCondition("pc.CreatingDate <= @dateTo");
if (productId.HasValue)
builder.AddCondition("pc.ProductId = @productId");
if (masterId.HasValue)
builder.AddCondition("pc.MasterId = @masterId");
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM PRODUCTCREATE";
var productCreatings = connection.Query<ProductCreate>(querySelect);
var querySelect = @$"SELECT
pc.*,
p.Name as ""ProductName"",
CONCAT(m.LastName, ' ', m.Name) as MasterName
FROM ProductCreate pc
LEFT JOIN Product p on p.Id = pc.ProductId
LEFT JOIN Master m on m.Id = pc.MasterId
{builder.Build()}";
var productCreatings = connection.Query<ProductCreate>(querySelect, new { dateFrom, dateTo, productId, masterId });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(productCreatings));
return productCreatings;
}
@ -77,7 +93,6 @@ WHERE Id=@id";
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}

View File

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