PIbd-23_Kulikova_D.R._LabWork_4 #6
@ -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)
|
||||
|
@ -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<SaleReceiptProduct> ReceiptProducts { get; set; } = [];
|
||||
|
||||
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,
|
||||
DateTime = tempSaleReceiptProduct.DateTime,
|
||||
SupplierId = tempSaleReceiptProduct.SupplierId,
|
||||
ReceiptProducts = receiptProducts
|
||||
};
|
||||
ReceiptProducts = saleReceiptProduct;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
@ -8,12 +9,31 @@ namespace ProjectGasStation.Entities;
|
||||
|
||||
public class Sale
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public DateTime DateTime { get; set; }
|
||||
public int WorkerId { get; set; }
|
||||
public IEnumerable<SaleReceiptProduct> 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<SaleReceiptProduct> SaleProducts { get; set; } = [];
|
||||
|
||||
public static Sale CreateOperation(int id, int workerId, IEnumerable<SaleReceiptProduct> saleProduct)
|
||||
{
|
||||
return new Sale
|
||||
@ -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,
|
||||
DateTime = tempSaleReceiptProduct.DateTime,
|
||||
WorkerId = tempSaleReceiptProduct.WorkerId,
|
||||
SaleProducts = saleProducts
|
||||
};
|
||||
SaleProducts = saleReceiptProduct;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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;
|
||||
|
||||
[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
|
||||
|
@ -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; }
|
||||
}
|
@ -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)
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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);
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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)
|
||||
{
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
||||
|
@ -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;
|
||||
|
@ -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;
|
||||
|
@ -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();
|
||||
@ -49,29 +49,62 @@ internal class TableReport
|
||||
|
||||
private List<string[]> 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
|
||||
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 { 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);
|
||||
.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<string[]>() { 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<string[]> { 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<string[]>
|
||||
{
|
||||
new string[]
|
||||
{
|
||||
"Всего",
|
||||
"",
|
||||
"",
|
||||
data.Sum(x => x.CountIn ?? 0).ToString("N0"),
|
||||
data.Sum(x => x.CountOut ?? 0).ToString("N0")
|
||||
}
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
@ -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<Receipt> 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<TempSaleReceiptProduct>(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<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)
|
||||
{
|
||||
|
@ -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<Sale> 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<TempSaleReceiptProduct>(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<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)
|
||||
{
|
||||
|
@ -56,7 +56,7 @@ VALUES (@Name, @PhoneNumber, @Address)";
|
||||
|
||||
var queryUpdate = @" UPDATE Suppliers
|
||||
SET
|
||||
Name = @SupplierName,
|
||||
Name = @Name,
|
||||
PhoneNumber = @PhoneNumber,
|
||||
Address = @Address
|
||||
WHERE ID = @Id";
|
||||
|
@ -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}";
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user