Lab4 alpha

This commit is contained in:
grishazagidulin 2024-12-16 10:35:55 +04:00
parent 1bca64b238
commit 117c1df988
17 changed files with 147 additions and 33 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

@ -19,7 +19,7 @@ public class Master
public int Age { get; private set; }
[DisplayName("Должность")]
public MasterPosition Position { get; private set; }
public string fullName => $"{Name} {LastName}";
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;
@ -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

@ -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;
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,7 @@ namespace Workshop
{
internal static class Program
{
//TODO: 1. Update со связью МкМ.
//TODO: Спросить про заполнение связей МкМ в FormProduct
//TODO: Спросить про заполнение колонки materials в таблице
//TODO: Èçìåíèòü chequeId íà productId â TableReport, ChequeRepository, IChequeRepository
/// <summary>
/// The main entry point for the application.
/// </summary>

View File

@ -43,8 +43,7 @@ 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)
.ReadProductCreates(dateFrom: dateTimeStart, dateTo: dateTimeEnd)
.GroupBy(x => x.ProductId, (key, group) => new
{
Id = key,

View File

@ -17,7 +17,7 @@ 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
{
@ -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

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

@ -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("cp.CreatingDate >= @dateFrom");
if (dateTo.HasValue)
builder.AddCondition("cp.CreatingDate <= @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}";
}
}