PIbd-23_Kulikova_D.R._LabWork_4 #6

Closed
kirkorovka_1 wants to merge 2 commits from LabWork_4 into LabWork_3
21 changed files with 324 additions and 89 deletions

View File

@ -1,6 +1,7 @@
using ProjectGasStation.Entities.Enums; using ProjectGasStation.Entities.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -10,8 +11,14 @@ namespace ProjectGasStation.Entities;
public class Product public class Product
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("Наименование")]
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
[DisplayName("Цена")]
public decimal Price { get; private set; } public decimal Price { get; private set; }
[DisplayName("Категория")]
public Category Category { get; private set; } public Category Category { get; private set; }
public static Product CreatEntity(int id, string name, decimal price, Category category) public static Product CreatEntity(int id, string name, decimal price, Category category)

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.Pkcs;
using System.Text; using System.Text;
@ -9,10 +10,26 @@ namespace ProjectGasStation.Entities;
public class Receipt public class Receipt
{ {
public int Id { get; set; } public int Id { get; private set; }
public DateTime DateTime { get; set; }
public int SupplierId { get; 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<SaleReceiptProduct> ReceiptProducts { get; set; } = []; public IEnumerable<SaleReceiptProduct> ReceiptProducts { get; set; } = [];
public static Receipt CreateOperation (int id, int supplierID, IEnumerable<SaleReceiptProduct> receiptProducts) public static Receipt CreateOperation (int id, int supplierID, IEnumerable<SaleReceiptProduct> receiptProducts)
@ -29,15 +46,12 @@ public class Receipt
}; };
} }
public static Receipt CreateOperation(TempSaleReceiptProduct tempSaleReceiptProduct, IEnumerable<SaleReceiptProduct> receiptProducts) public void SetReceiptProduct(IEnumerable<SaleReceiptProduct> saleReceiptProduct)
{ {
return new Receipt if(saleReceiptProduct != null && saleReceiptProduct.Any())
{ {
Id = tempSaleReceiptProduct.Id, ReceiptProducts = saleReceiptProduct;
DateTime = tempSaleReceiptProduct.DateTime, }
SupplierId = tempSaleReceiptProduct.SupplierId,
ReceiptProducts = receiptProducts
};
} }
} }

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -8,11 +9,30 @@ namespace ProjectGasStation.Entities;
public class Sale public class Sale
{ {
public int Id { get; set; } public int Id { get; private set; }
public DateTime DateTime { get; set; }
public int WorkerId { get; set; }
public IEnumerable<SaleReceiptProduct> SaleProducts { get; 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<SaleReceiptProduct> SaleProducts { get; set; } = [];
public static Sale CreateOperation(int id, int workerId, IEnumerable<SaleReceiptProduct> saleProduct) public static Sale CreateOperation(int id, int workerId, IEnumerable<SaleReceiptProduct> saleProduct)
{ {
@ -26,14 +46,12 @@ public class Sale
}; };
} }
public static Sale CreateOperation(TempSaleReceiptProduct tempSaleReceiptProduct, IEnumerable<SaleReceiptProduct> saleProducts)
public void SetSaleProduct(IEnumerable<SaleReceiptProduct> saleReceiptProduct)
{ {
return new Sale if (saleReceiptProduct != null && saleReceiptProduct.Any())
{ {
Id = tempSaleReceiptProduct.Id, SaleProducts = saleReceiptProduct;
DateTime = tempSaleReceiptProduct.DateTime, }
WorkerId = tempSaleReceiptProduct.WorkerId,
SaleProducts = saleProducts
};
} }
} }

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -10,6 +11,9 @@ public class SaleReceiptProduct
{ {
public int Id { get; set; } public int Id { get; set; }
public int ProductId { get; set; } public int ProductId { get; set; }
public string ProductName { get; private set; } = string.Empty;
public int Quantity { get; set; } public int Quantity { get; set; }
public static SaleReceiptProduct CreateElement(int id, int productId, int quantity) public static SaleReceiptProduct CreateElement(int id, int productId, int quantity)
{ {

View File

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -9,10 +10,16 @@ namespace ProjectGasStation.Entities;
public class Supplier public class Supplier
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("ФИО")]
public string Name { get; private set; } = string.Empty; 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 string Address { get; private set; } = string.Empty;
public static Supplier CreateEntity(int id, string name, string phoneNumber, string address) public static Supplier CreateEntity(int id, string name, string phoneNumber, string address)
{ {
return new Supplier return new Supplier

View File

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

View File

@ -1,6 +1,7 @@
using ProjectGasStation.Entities.Enums; using ProjectGasStation.Entities.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
@ -11,7 +12,11 @@ namespace ProjectGasStation.Entities;
public class Worker public class Worker
{ {
public int Id { get; private set; } public int Id { get; private set; }
[DisplayName("ФИО")]
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
[DisplayName("Должность")]
public JobTitle JobTitle { get; private set; } public JobTitle JobTitle { get; private set; }
public static Worker CreateEntity (int id, string name, JobTitle jobTitle) public static Worker CreateEntity (int id, string name, JobTitle jobTitle)

View File

@ -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) private bool TryGetIdentifierFromSelectedRow(out int id)
{ {

View File

@ -120,7 +120,7 @@
buttonCancel.UseVisualStyleBackColor = true; buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click; buttonCancel.Click += buttonCancel_Click;
// //
// FormReceipts // FormReceipt
// //
AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
@ -130,8 +130,8 @@
Controls.Add(groupBoxProducts); Controls.Add(groupBoxProducts);
Controls.Add(comboBoxSupplier); Controls.Add(comboBoxSupplier);
Controls.Add(labelSupplier); Controls.Add(labelSupplier);
Name = "FormReceipts"; Name = "FormReceipt";
Text = "Поставка"; Text = "13";
groupBoxProducts.ResumeLayout(false); groupBoxProducts.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit(); ((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit();
ResumeLayout(false); ResumeLayout(false);

View File

@ -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) private bool TryGetIdentifierFromSelectedRow(out int id)
{ {

View File

@ -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) private bool TryGetIdentifierFromSelectedRow(out int id)
{ {

View File

@ -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) private bool TryGetIdentifierFromSelectRow(out int id)
{ {

View File

@ -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) private bool TryGetIdentifierFromSelectRow(out int id)
{ {

View File

@ -24,7 +24,8 @@ internal class ChartReport
{ {
new PdfBuilder(filePath) new PdfBuilder(filePath)
.AddHeader("Количество продаж каждого работника") .AddHeader("Количество продаж каждого работника")
.AddPieChart("Работники", GetData(dateTime)) .AddPieChart($"Продано на {dateTime:dd MMMM yyyy}", GetData(dateTime))
.Build(); .Build();
return true; return true;
} }
@ -35,13 +36,14 @@ internal class ChartReport
} }
} }
//Caption - дписи для секторов
//Value - числ значения
private List<(string Caption, double Value)> GetData(DateTime dateTime) private List<(string Caption, double Value)> GetData(DateTime dateTime)
{ {
return _saleRepository return _saleRepository
.ReadSale() .ReadSale(dateForm: dateTime.Date, dateTo: dateTime.Date.AddDays(1))
.Where(x => x.DateTime.Date == dateTime.Date) .GroupBy(x => x.WorkerName, (key, group) => new { WorkerName = key, Count = group.Sum(y => y.SaleProducts.Count()) })
.GroupBy(x => x.WorkerId, (key, group) => new { Id = key, Count = group.Sum(y => y.SaleProducts.Count()) }) .Select(x => (x.WorkerName.ToString(), (double)x.Count))
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList(); .ToList();
} }
} }

View File

@ -97,7 +97,7 @@ internal class ExcelBuilder
for (var j = 0; j < data.Last().Length; ++j) for (var j = 0; j < data.Last().Length; ++j)
{ {
CreateCell(j, _rowIndex, data.Last()[j], CreateCell(j, _rowIndex, data.Last()[j],
StyleIndex.BoldTextWithoutBorder); StyleIndex.BoldTextWithBorder);
} }
_rowIndex++; _rowIndex++;
return this; return this;

View File

@ -42,9 +42,11 @@ internal class PdfBuilder
} }
var chart = new Chart(ChartType.Pie2D); var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries(); var series = chart.SeriesCollection.AddSeries();
// Извлекаются значения
series.Add(data.Select(x => x.Value).ToArray()); series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries(); var xseries = chart.XValues.AddXSeries();
// Извлекаются подписи
xseries.Add(data.Select(x => x.Caption).ToArray()); xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent; chart.DataLabel.Type = DataLabelType.Percent;

View File

@ -34,7 +34,7 @@ internal class TableReport
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader("Сводка по движению товара", 0, 4) .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)) .AddTable([10, 10, 15, 15, 15], GetData(productId, startDate, endDate))
.Build(); .Build();
@ -48,30 +48,63 @@ internal class TableReport
} }
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate) private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate)
{ {
var data = _receiptRepository var receiptData = _receiptRepository
.ReadReceipt() .ReadReceipt(dateForm: startDate, dateTo: endDate, productId: productId)
.Where(x => x.DateTime >= startDate && x.DateTime <= endDate && x.ReceiptProducts.Any(y => y.ProductId == productId)) .Select(x => new
.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( WorkerName = (string)null, // Работник не относится к Receipt, оставляем null
_saleRepository SupplierName = x.SupplierName, // Используем свойство SupplierName из Receipt
.ReadSale() Date = x.DateTime,
.Where(x => x.DateTime >= startDate && x.DateTime <= endDate && x.SaleProducts.Any(y => y.ProductId == productId)) CountIn = x.ReceiptProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity,
.Select(x => new { WorkerId = (int?)null, SupplierId = (int?)null, Date = x.DateTime, CountIn = (int?)null, CountOut = x.SaleProducts.FirstOrDefault(y => y.ProductId == productId)?.Quantity })) CountOut = (int?)null // Количество ушло не используется в Receipt
.OrderBy(x => x.Date); });
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()))); _logger.LogInformation("Объединенные данные: {0}", string.Join(", ", data.Select(d => d.Date.ToString())));
return // Формируем таблицу
new List<string[]>() { item } return new List<string[]> { item }
.Union( .Union(data.Select(x => new string[]
data {
.Select(x => new string[] {x.WorkerId.ToString(), x.SupplierId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? string.Empty, x.CountOut?.ToString() ?? string.Empty})) x.WorkerName ?? string.Empty, // Если WorkerName отсутствует, используем пустую строку
.Union( x.SupplierName ?? string.Empty, // Если SupplierName отсутствует, используем пустую строку
[["Всего", "", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]]) x.Date.ToString("dd.MM.yyyy"), // Приводим дату к читаемому формату
x.CountIn?.ToString("N0") ?? string.Empty, // Если CountIn отсутствует, используем пустую строку
x.CountOut?.ToString("N0") ?? string.Empty // Если CountOut отсутствует, используем пустую строку
}))
.Union(new List<string[]>
{
new string[]
{
"Всего",
"",
"",
data.Sum(x => x.CountIn ?? 0).ToString("N0"),
data.Sum(x => x.CountOut ?? 0).ToString("N0")
}
})
.ToList(); .ToList();
} }
} }

View File

@ -23,6 +23,8 @@ internal class ReceiptRepository : IReceiptRepository
_logger = logger; _logger = logger;
} }
public void CreateReceipt(Receipt receipt) public void CreateReceipt(Receipt receipt)
{ {
_logger.LogInformation("Добавление объекта"); _logger.LogInformation("Добавление объекта");
@ -82,22 +84,75 @@ VALUES (@ProductID, @ReceiptID, @Quantity)";
} }
} }
public IEnumerable<Receipt> ReadReceipt(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? supplierId = null) public IEnumerable<Receipt> ReadReceipt(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? supplierId = null)
{ {
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try 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); using var connection = new NpgsqlConnection(_conectionString.ConectionString);
connection.Open(); 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<TempSaleReceiptProduct>(querySelect);
_logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(receipt));
return receipt.GroupBy(x => x.Id, y => y, var querySelect = @$"
(key, value) => Receipt.CreateOperation(value.First(), SELECT
value.Select(z => SaleReceiptProduct.CreateElement(0, z.ProductId, z.Quantity)))).ToList(); 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<int, List<SaleReceiptProduct>>();
var receipts = connection.Query<Receipt, SaleReceiptProduct, Receipt>(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) catch (Exception ex)
{ {

View File

@ -30,6 +30,7 @@ internal class SaleRepository : ISaleRepository
try try
{ {
using var connection = new NpgsqlConnection(_conectionString.ConectionString); using var connection = new NpgsqlConnection(_conectionString.ConectionString);
connection.Open(); connection.Open();
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
@ -83,23 +84,73 @@ VALUES (@SaleID, @ProductID, @Quantity)";
} }
} }
public IEnumerable<Sale> ReadSale(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? workerId = null) public IEnumerable<Sale> ReadSale(DateTime? dateForm = null, DateTime? dateTo = null, int? productId = null, int? workerId = null)
{ {
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try 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); using var connection = new NpgsqlConnection(_conectionString.ConectionString);
connection.Open(); connection.Open();
var querySelect = @" SELECT fr.*, ffr.ProductId, ffr. Quantity FROM Sale fr var querySelect = $@"
INNER JOIN SaleProducts ffr ON ffr.SaleId = fr.Id"; SELECT
var sale = connection.Query<TempSaleReceiptProduct>(querySelect); s.ID AS Id,
_logger.LogDebug("Получены объекты: {json}", JsonConvert.SerializeObject(sale)); 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<int, List<SaleReceiptProduct>>();
var sales = connection.Query<Sale, SaleReceiptProduct, Sale>(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) catch (Exception ex)
{ {

View File

@ -56,7 +56,7 @@ VALUES (@Name, @PhoneNumber, @Address)";
var queryUpdate = @" UPDATE Suppliers var queryUpdate = @" UPDATE Suppliers
SET SET
Name = @SupplierName, Name = @Name,
PhoneNumber = @PhoneNumber, PhoneNumber = @PhoneNumber,
Address = @Address Address = @Address
WHERE ID = @Id"; WHERE ID = @Id";

View File

@ -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}";
}
}