diff --git a/ProjectGasStation/ProjectGasStation/Entities/Product.cs b/ProjectGasStation/ProjectGasStation/Entities/Product.cs index e89c8b9..54cd445 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Product.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Product.cs @@ -1,6 +1,7 @@ using ProjectGasStation.Entities.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,8 +11,14 @@ namespace ProjectGasStation.Entities; public class Product { public int Id { get; private set; } + + [DisplayName("Наименование")] public string Name { get; private set; } = string.Empty; + + [DisplayName("Цена")] public decimal Price { get; private set; } + + [DisplayName("Категория")] public Category Category { get; private set; } public static Product CreatEntity(int id, string name, decimal price, Category category) diff --git a/ProjectGasStation/ProjectGasStation/Entities/Receipt.cs b/ProjectGasStation/ProjectGasStation/Entities/Receipt.cs index 83f0355..fc6d003 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Receipt.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Receipt.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Security.Cryptography.Pkcs; using System.Text; @@ -9,10 +10,26 @@ namespace ProjectGasStation.Entities; public class Receipt { - public int Id { get; set; } - public DateTime DateTime { get; set; } - public int SupplierId { get; set; } + public int Id { get; private set; } + + [Browsable(false)] + public int SupplierId { get; private set; } + + + [DisplayName("Поставщик")] + public string SupplierName { get; private set; } = string.Empty; + + [DisplayName("Дата поставки")] + public DateTime DateTime { get; private set; } + + [DisplayName("Товары")] + public string Product => ReceiptProducts != null ? + string.Join(", ", ReceiptProducts.Select(x => $"{x.ProductName} {x.Quantity}")) : + string.Empty; + + + [Browsable(false)] public IEnumerable ReceiptProducts { get; set; } = []; public static Receipt CreateOperation (int id, int supplierID, IEnumerable receiptProducts) @@ -29,15 +46,12 @@ public class Receipt }; } - public static Receipt CreateOperation(TempSaleReceiptProduct tempSaleReceiptProduct, IEnumerable receiptProducts) + public void SetReceiptProduct(IEnumerable saleReceiptProduct) { - return new Receipt + if(saleReceiptProduct != null && saleReceiptProduct.Any()) { - Id = tempSaleReceiptProduct.Id, - DateTime = tempSaleReceiptProduct.DateTime, - SupplierId = tempSaleReceiptProduct.SupplierId, - ReceiptProducts = receiptProducts - }; + ReceiptProducts = saleReceiptProduct; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Entities/Sale.cs b/ProjectGasStation/ProjectGasStation/Entities/Sale.cs index c35ae39..36efa26 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Sale.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Sale.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -8,11 +9,30 @@ namespace ProjectGasStation.Entities; public class Sale { - public int Id { get; set; } - public DateTime DateTime { get; set; } - public int WorkerId { get; set; } - public IEnumerable SaleProducts { get; set; } = []; + 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 DateTime { get; private set; } + + + [DisplayName("Товары")] + public string Product => SaleProducts != null ? + string.Join(", ", SaleProducts.Select(x => $"{x.ProductName} {x.Quantity}")) : + string.Empty; + + + [Browsable(false)] + public IEnumerable SaleProducts { get; set; } = []; public static Sale CreateOperation(int id, int workerId, IEnumerable saleProduct) { @@ -26,14 +46,12 @@ public class Sale }; } - public static Sale CreateOperation(TempSaleReceiptProduct tempSaleReceiptProduct, IEnumerable saleProducts) + + public void SetSaleProduct(IEnumerable saleReceiptProduct) { - return new Sale + if (saleReceiptProduct != null && saleReceiptProduct.Any()) { - Id = tempSaleReceiptProduct.Id, - DateTime = tempSaleReceiptProduct.DateTime, - WorkerId = tempSaleReceiptProduct.WorkerId, - SaleProducts = saleProducts - }; + SaleProducts = saleReceiptProduct; + } } } diff --git a/ProjectGasStation/ProjectGasStation/Entities/SaleReceiptProduct.cs b/ProjectGasStation/ProjectGasStation/Entities/SaleReceiptProduct.cs index 77a93f7..c3248ae 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/SaleReceiptProduct.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/SaleReceiptProduct.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -10,6 +11,9 @@ public class SaleReceiptProduct { public int Id { get; set; } public int ProductId { get; set; } + + public string ProductName { get; private set; } = string.Empty; + public int Quantity { get; set; } public static SaleReceiptProduct CreateElement(int id, int productId, int quantity) { diff --git a/ProjectGasStation/ProjectGasStation/Entities/Supplier.cs b/ProjectGasStation/ProjectGasStation/Entities/Supplier.cs index 0e6a378..e31934e 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Supplier.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Supplier.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -9,10 +10,16 @@ namespace ProjectGasStation.Entities; public class Supplier { public int Id { get; private set; } + [DisplayName("ФИО")] public string Name { get; private set; } = string.Empty; - public string PhoneNumber { get; private set; } + + [DisplayName("Номер телефона")] + public string PhoneNumber { get; private set; } + + [DisplayName("Адрес")] public string Address { get; private set; } = string.Empty; + public static Supplier CreateEntity(int id, string name, string phoneNumber, string address) { return new Supplier diff --git a/ProjectGasStation/ProjectGasStation/Entities/TempSaleReceiptProduct.cs b/ProjectGasStation/ProjectGasStation/Entities/TempSaleReceiptProduct.cs deleted file mode 100644 index 04a4db2..0000000 --- a/ProjectGasStation/ProjectGasStation/Entities/TempSaleReceiptProduct.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectGasStation.Entities; - -public class TempSaleReceiptProduct -{ - public int Id { get; private set; } - public DateTime DateTime { get; private set; } - public int SupplierId { get; private set; } - - public int WorkerId { get; private set; } - public int ProductId { get; private set; } - - public int Quantity { get; private set; } -} diff --git a/ProjectGasStation/ProjectGasStation/Entities/Worker.cs b/ProjectGasStation/ProjectGasStation/Entities/Worker.cs index ba06e56..fb21429 100644 --- a/ProjectGasStation/ProjectGasStation/Entities/Worker.cs +++ b/ProjectGasStation/ProjectGasStation/Entities/Worker.cs @@ -1,6 +1,7 @@ using ProjectGasStation.Entities.Enums; using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; @@ -11,7 +12,11 @@ namespace ProjectGasStation.Entities; public class Worker { public int Id { get; private set; } + + [DisplayName("ФИО")] public string Name { get; private set; } = string.Empty; + + [DisplayName("Должность")] public JobTitle JobTitle { get; private set; } public static Worker CreateEntity (int id, string name, JobTitle jobTitle) diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormProducts.cs b/ProjectGasStation/ProjectGasStation/Forms/FormProducts.cs index e6e2eda..8e2e963 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormProducts.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormProducts.cs @@ -98,7 +98,11 @@ namespace ProjectGasStation.Forms } } - private void LoadList() => dataGridViewData.DataSource = _productRepository.ReadProduct(); + private void LoadList() + { + dataGridViewData.DataSource = _productRepository.ReadProduct(); + dataGridViewData.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectedRow(out int id) { diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormReceipt.Designer.cs b/ProjectGasStation/ProjectGasStation/Forms/FormReceipt.Designer.cs index 05f17a4..8fc7a12 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormReceipt.Designer.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormReceipt.Designer.cs @@ -120,7 +120,7 @@ buttonCancel.UseVisualStyleBackColor = true; buttonCancel.Click += buttonCancel_Click; // - // FormReceipts + // FormReceipt // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; @@ -130,8 +130,8 @@ Controls.Add(groupBoxProducts); Controls.Add(comboBoxSupplier); Controls.Add(labelSupplier); - Name = "FormReceipts"; - Text = "Поставка"; + Name = "FormReceipt"; + Text = "13"; groupBoxProducts.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit(); ResumeLayout(false); diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormReceipts.cs b/ProjectGasStation/ProjectGasStation/Forms/FormReceipts.cs index 52bd604..34b91bd 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormReceipts.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormReceipts.cs @@ -85,7 +85,12 @@ namespace ProjectGasStation.Forms } - private void LoadList() => dataGridViewData.DataSource = _receiptRepository.ReadReceipt(); + private void LoadList() + { + dataGridViewData.DataSource = _receiptRepository.ReadReceipt(); + dataGridViewData.Columns["Id"].Visible = false; + dataGridViewData.Columns["DateTime"].DefaultCellStyle.Format = "dd MMMM yyyy"; + } private bool TryGetIdentifierFromSelectedRow(out int id) { diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormSales.cs b/ProjectGasStation/ProjectGasStation/Forms/FormSales.cs index ce912cc..2feaf43 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormSales.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormSales.cs @@ -77,7 +77,12 @@ namespace ProjectGasStation.Forms } } - private void LoadList() => dataGridViewData.DataSource = _saleRepository.ReadSale(); + private void LoadList() + { + dataGridViewData.DataSource = _saleRepository.ReadSale(); + dataGridViewData.Columns["Id"].Visible = false; + + } private bool TryGetIdentifierFromSelectedRow(out int id) { diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.cs b/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.cs index 7fa7c6c..19efb12 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormSuppliers.cs @@ -100,7 +100,11 @@ namespace ProjectGasStation.Forms } } - private void LoadList() => dataGridViewData.DataSource = _supplierRepository.ReadSupplier(); + private void LoadList() + { + dataGridViewData.DataSource = _supplierRepository.ReadSupplier(); + dataGridViewData.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs b/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs index 1f95782..c45a1fc 100644 --- a/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs +++ b/ProjectGasStation/ProjectGasStation/Forms/FormWorkers.cs @@ -96,7 +96,11 @@ namespace ProjectGasStation.Forms } } - private void LoadList() => dataGridViewData.DataSource = _workerRepository.ReadWorker(); + private void LoadList() + { + dataGridViewData.DataSource = _workerRepository.ReadWorker(); + dataGridViewData.Columns["Id"].Visible = false; + } private bool TryGetIdentifierFromSelectRow(out int id) { diff --git a/ProjectGasStation/ProjectGasStation/Reports/ChartReport.cs b/ProjectGasStation/ProjectGasStation/Reports/ChartReport.cs index 449db06..6386fe0 100644 --- a/ProjectGasStation/ProjectGasStation/Reports/ChartReport.cs +++ b/ProjectGasStation/ProjectGasStation/Reports/ChartReport.cs @@ -24,7 +24,8 @@ internal class ChartReport { new PdfBuilder(filePath) .AddHeader("Количество продаж каждого работника") - .AddPieChart("Работники", GetData(dateTime)) + .AddPieChart($"Продано на {dateTime:dd MMMM yyyy}", GetData(dateTime)) + .Build(); return true; } @@ -35,13 +36,14 @@ internal class ChartReport } } + //Caption - дписи для секторов + //Value - числ значения private List<(string Caption, double Value)> GetData(DateTime dateTime) { return _saleRepository - .ReadSale() - .Where(x => x.DateTime.Date == dateTime.Date) - .GroupBy(x => x.WorkerId, (key, group) => new { Id = key, Count = group.Sum(y => y.SaleProducts.Count()) }) - .Select(x => (x.Id.ToString(), (double)x.Count)) + .ReadSale(dateForm: dateTime.Date, dateTo: dateTime.Date.AddDays(1)) + .GroupBy(x => x.WorkerName, (key, group) => new { WorkerName = key, Count = group.Sum(y => y.SaleProducts.Count()) }) + .Select(x => (x.WorkerName.ToString(), (double)x.Count)) .ToList(); } } diff --git a/ProjectGasStation/ProjectGasStation/Reports/ExcelBuilder.cs b/ProjectGasStation/ProjectGasStation/Reports/ExcelBuilder.cs index ae7c890..a22eee5 100644 --- a/ProjectGasStation/ProjectGasStation/Reports/ExcelBuilder.cs +++ b/ProjectGasStation/ProjectGasStation/Reports/ExcelBuilder.cs @@ -97,7 +97,7 @@ internal class ExcelBuilder for (var j = 0; j < data.Last().Length; ++j) { CreateCell(j, _rowIndex, data.Last()[j], - StyleIndex.BoldTextWithoutBorder); + StyleIndex.BoldTextWithBorder); } _rowIndex++; return this; diff --git a/ProjectGasStation/ProjectGasStation/Reports/PdfBuilder.cs b/ProjectGasStation/ProjectGasStation/Reports/PdfBuilder.cs index d4bbbc3..494e2da 100644 --- a/ProjectGasStation/ProjectGasStation/Reports/PdfBuilder.cs +++ b/ProjectGasStation/ProjectGasStation/Reports/PdfBuilder.cs @@ -42,9 +42,11 @@ internal class PdfBuilder } var chart = new Chart(ChartType.Pie2D); var series = chart.SeriesCollection.AddSeries(); + // Извлекаются значения series.Add(data.Select(x => x.Value).ToArray()); var xseries = chart.XValues.AddXSeries(); + // Извлекаются подписи xseries.Add(data.Select(x => x.Caption).ToArray()); chart.DataLabel.Type = DataLabelType.Percent; diff --git a/ProjectGasStation/ProjectGasStation/Reports/TableReport.cs b/ProjectGasStation/ProjectGasStation/Reports/TableReport.cs index 7488758..83e3095 100644 --- a/ProjectGasStation/ProjectGasStation/Reports/TableReport.cs +++ b/ProjectGasStation/ProjectGasStation/Reports/TableReport.cs @@ -34,7 +34,7 @@ internal class TableReport { new ExcelBuilder(filePath) .AddHeader("Сводка по движению товара", 0, 4) - .AddParagraph("за период", 0) + .AddParagraph($"за период с {startDate: dd.MM.yyyy} no {endDate: dd.MM.yyyy}", 0) .AddTable([10, 10, 15, 15, 15], GetData(productId, startDate, endDate)) .Build(); @@ -48,30 +48,63 @@ internal class TableReport } private List GetData(int productId, DateTime startDate, DateTime endDate) - { - var data = _receiptRepository - .ReadReceipt() - .Where(x => x.DateTime >= startDate && x.DateTime <= endDate && x.ReceiptProducts.Any(y => y.ProductId == productId)) - .Select(x => new { WorkerId = (int?)null, SupplierId = (int?)null, Date = x.DateTime, CountIn = x.ReceiptProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity, CountOut = (int?)null }) - .Union( - _saleRepository - .ReadSale() - .Where(x => x.DateTime >= startDate && x.DateTime <= endDate && x.SaleProducts.Any(y => y.ProductId == productId)) - .Select(x => new { WorkerId = (int?)null, SupplierId = (int?)null, Date = x.DateTime, CountIn = (int?)null, CountOut = x.SaleProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity })) - .OrderBy(x => x.Date); + { + var receiptData = _receiptRepository + .ReadReceipt(dateForm: startDate, dateTo: endDate, productId: productId) + .Select(x => new + { + WorkerName = (string)null, // Работник не относится к Receipt, оставляем null + SupplierName = x.SupplierName, // Используем свойство SupplierName из Receipt + Date = x.DateTime, + CountIn = x.ReceiptProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity, + CountOut = (int?)null // Количество ушло не используется в Receipt + }); + var saleData = _saleRepository + .ReadSale() + .Where(x => x.DateTime >= startDate && x.DateTime <= endDate && x.SaleProducts.Any(y => y.ProductId == productId)) + .Select(x => new + { + WorkerName = x.WorkerName, // Используем свойство WorkerName из Sale + SupplierName = (string)null, // Поставщик не относится к Sale, оставляем null + Date = x.DateTime, + CountIn = (int?)null, // Количество пришло не используется в Sale + CountOut = x.SaleProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity + }); + + // Объединяем данные + var data = receiptData + .Union(saleData) + .OrderBy(x => x.Date) + .ToList(); _logger.LogInformation("Объединенные данные: {0}", string.Join(", ", data.Select(d => d.Date.ToString()))); - return - new List() { item } - .Union( - data - .Select(x => new string[] {x.WorkerId.ToString(), x.SupplierId.ToString(), x.Date.ToString(), 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()]]) + // Формируем таблицу + return new List { item } + .Union(data.Select(x => new string[] + { + x.WorkerName ?? string.Empty, // Если WorkerName отсутствует, используем пустую строку + x.SupplierName ?? string.Empty, // Если SupplierName отсутствует, используем пустую строку + x.Date.ToString("dd.MM.yyyy"), // Приводим дату к читаемому формату + x.CountIn?.ToString("N0") ?? string.Empty, // Если CountIn отсутствует, используем пустую строку + x.CountOut?.ToString("N0") ?? string.Empty // Если CountOut отсутствует, используем пустую строку + })) + .Union(new List + { + new string[] + { + "Всего", + "", + "", + data.Sum(x => x.CountIn ?? 0).ToString("N0"), + data.Sum(x => x.CountOut ?? 0).ToString("N0") + } + }) .ToList(); } + } + diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs index 36c2d36..8267d30 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/ReceiptRepository.cs @@ -23,6 +23,8 @@ internal class ReceiptRepository : IReceiptRepository _logger = logger; } + + public void CreateReceipt(Receipt receipt) { _logger.LogInformation("Добавление объекта"); @@ -82,22 +84,75 @@ VALUES (@ProductID, @ReceiptID, @Quantity)"; } } + + public IEnumerable ReadReceipt(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? supplierId = null) { _logger.LogInformation("Получение всех объектов"); try { + var builder = new QueryBuilder(); + if (dateForm.HasValue) + { + builder.AddCondition("r.DateTime >= @dateForm"); + } + if (dateTo.HasValue) + { + builder.AddCondition("r.DateTime <= @dateTo"); + } + if (supplierId.HasValue) + { + builder.AddCondition("r.SupplierId = @supplierId"); + } + if (productId.HasValue) + { + builder.AddCondition("rp.ProductID = @productId"); + } + + using var connection = new NpgsqlConnection(_conectionString.ConectionString); connection.Open(); - var querySelect = @" SELECT fr.*, ffr.ProductId, ffr. Quantity FROM Receipt fr -INNER JOIN ReceiptProducts ffr ON ffr.ReceiptId = fr.Id"; - var receipt = connection.Query(querySelect); - _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(receipt)); - return receipt.GroupBy(x => x.Id, y => y, - (key, value) => Receipt.CreateOperation(value.First(), - value.Select(z => SaleReceiptProduct.CreateElement(0, z.ProductId, z.Quantity)))).ToList(); + var querySelect = @$" +SELECT + r.ID AS Id, + s.Name AS SupplierName, + r.DateTime AS DateTime, + rp.ProductID AS ProductId, + p.Name AS ProductName, + rp.Quantity AS Quantity +FROM + Receipt r +JOIN + Suppliers s ON r.SupplierID = s.ID +JOIN + ReceiptProducts rp ON r.ID = rp.ReceiptID +JOIN + Products p ON rp.ProductID = p.ID +{builder.Build()}"; + + var receiptDict = new Dictionary>(); + + var receipts = connection.Query(querySelect, + (receipt, receiptProduct) => + { + if (!receiptDict.TryGetValue(receipt.Id, out var frr)) + { + frr = []; + receiptDict.Add(receipt.Id, frr); + } + frr.Add(receiptProduct); + return receipt; + }, splitOn: "ProductId", param: new { dateForm, dateTo, productId, supplierId}); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(receipts)); + + return receiptDict.Select(x => + { + var fr = receipts.First(y => y.Id == x.Key); + fr.SetReceiptProduct(x.Value); + return fr; + }).ToArray(); } catch (Exception ex) { diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs index 6a95c80..b43d91a 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SaleRepository.cs @@ -30,6 +30,7 @@ internal class SaleRepository : ISaleRepository try { + using var connection = new NpgsqlConnection(_conectionString.ConectionString); connection.Open(); using var transaction = connection.BeginTransaction(); @@ -83,23 +84,73 @@ VALUES (@SaleID, @ProductID, @Quantity)"; } } + public IEnumerable ReadSale(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? workerId = null) { _logger.LogInformation("Получение всех объектов"); try { + var builder = new QueryBuilder(); + if (dateForm.HasValue) + { + builder.AddCondition("s.DateTime >= @dateForm"); + } + if (dateTo.HasValue) + { + builder.AddCondition("s.DateTime <= @dateTo"); + } + if (workerId.HasValue) + { + builder.AddCondition("s.WorkerId = @workerId"); + } + if (productId.HasValue) + { + builder.AddCondition("sp.ProductID = @productId"); + } + using var connection = new NpgsqlConnection(_conectionString.ConectionString); connection.Open(); - var querySelect = @" SELECT fr.*, ffr.ProductId, ffr. Quantity FROM Sale fr -INNER JOIN SaleProducts ffr ON ffr.SaleId = fr.Id"; - var sale = connection.Query(querySelect); - _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(sale)); + var querySelect = $@" +SELECT + s.ID AS Id, + w.Name AS WorkerName, + s.DateTime AS DateTime, + sp.ProductID AS ProductId, + p.Name AS ProductName, + sp.Quantity AS Quantity +FROM + Sale s +JOIN + Workers w ON s.WorkerID = w.ID +JOIN + SaleProducts sp ON s.ID = sp.SaleID +JOIN + Products p ON sp.ProductID = p.ID +{builder.Build()}"; + var saleDict = new Dictionary>(); + + var sales = connection.Query(querySelect, + (sale, saleProduct) => + { + if (!saleDict.TryGetValue(sale.Id, out var frr)) + { + frr = []; + saleDict.Add(sale.Id, frr); + } + frr.Add(saleProduct); + return sale; + }, splitOn: "ProductId", param: new { dateForm, dateTo, productId, workerId }); + _logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(sales)); + + return saleDict.Select(x => + { + var fr = sales.First(y => y.Id == x.Key); + fr.SetSaleProduct(x.Value); + return fr; + }).ToArray(); - return sale.GroupBy(x => x.Id, y => y, - (key, value) => Sale.CreateOperation(value.First(), - value.Select(z => SaleReceiptProduct.CreateElement(0, z.ProductId, z.Quantity)))).ToList(); } catch (Exception ex) { diff --git a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs index 462ef80..902d379 100644 --- a/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs +++ b/ProjectGasStation/ProjectGasStation/Repositories/Implementations/SupplierRepository.cs @@ -56,7 +56,7 @@ VALUES (@Name, @PhoneNumber, @Address)"; var queryUpdate = @" UPDATE Suppliers SET - Name = @SupplierName, + Name = @Name, PhoneNumber = @PhoneNumber, Address = @Address WHERE ID = @Id"; diff --git a/ProjectGasStation/ProjectGasStation/Repositories/QueryBuilder.cs b/ProjectGasStation/ProjectGasStation/Repositories/QueryBuilder.cs new file mode 100644 index 0000000..12864d1 --- /dev/null +++ b/ProjectGasStation/ProjectGasStation/Repositories/QueryBuilder.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectGasStation.Repositories; + +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}"; + } + +}