Лабораторная 4
This commit is contained in:
parent
6833381b98
commit
658b0bc060
@ -1,13 +1,19 @@
|
|||||||
namespace ProjectSellPC.Entites
|
using System.ComponentModel;
|
||||||
|
|
||||||
|
namespace ProjectSellPC.Entites
|
||||||
{
|
{
|
||||||
public class Cheque
|
public class Cheque
|
||||||
{
|
{
|
||||||
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
[DisplayName("Товары")]
|
||||||
public List<ProductInCheque> Products { get; set; }
|
public List<ProductInCheque> Products { get; set; }
|
||||||
|
[DisplayName("Клиент")]
|
||||||
public Client Client { get; set; }
|
public Client Client { get; set; }
|
||||||
|
|
||||||
[System.ComponentModel.Browsable(false)]
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int ClientId { get; set; }
|
public int ClientId { get; set; }
|
||||||
|
[DisplayName("Дата покупки")]
|
||||||
public DateTime PurchaseDate { get; set; }
|
public DateTime PurchaseDate { get; set; }
|
||||||
|
|
||||||
public static Cheque CreateEntity(int id, List<ProductInCheque> products, Client client, DateTime purchaseDate)
|
public static Cheque CreateEntity(int id, List<ProductInCheque> products, Client client, DateTime purchaseDate)
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
using ProjectSellPC.Entites.Enums;
|
using ProjectSellPC.Entites.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,11 @@ namespace ProjectSellPC.Entites
|
|||||||
public class Client
|
public class Client
|
||||||
{
|
{
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
[DisplayName("Имя")]
|
||||||
public string Name { get; set; }
|
public string Name { get; set; }
|
||||||
|
[DisplayName("Номер телефона")]
|
||||||
public string PhoneNumber { get; set; }
|
public string PhoneNumber { get; set; }
|
||||||
|
[DisplayName("Вид клиента")]
|
||||||
public ClientType ClientType { get; set; }
|
public ClientType ClientType { get; set; }
|
||||||
|
|
||||||
public static Client CreateEntity(int id, string name, string phoneNumber, ClientType clientType)
|
public static Client CreateEntity(int id, string name, string phoneNumber, ClientType clientType)
|
||||||
|
@ -1,13 +1,18 @@
|
|||||||
using ProjectSellPC.Entites.Enums;
|
using ProjectSellPC.Entites.Enums;
|
||||||
|
using System.ComponentModel;
|
||||||
|
|
||||||
namespace ProjectSellPC.Entites
|
namespace ProjectSellPC.Entites
|
||||||
{
|
{
|
||||||
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; }
|
public string Name { get; private set; }
|
||||||
|
[DisplayName("Описание")]
|
||||||
public string Description { get; private set; }
|
public string Description { get; private set; }
|
||||||
|
[DisplayName("Цена")]
|
||||||
public decimal Price { get; private set; }
|
public decimal Price { get; private set; }
|
||||||
|
[DisplayName("Вид")]
|
||||||
public ProductType ProductType { get; private set; }
|
public ProductType ProductType { get; private set; }
|
||||||
|
|
||||||
public static Product CreateEntity(int id, string name, string desc, decimal price, ProductType productType)
|
public static Product CreateEntity(int id, string name, string desc, decimal price, ProductType productType)
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
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;
|
||||||
@ -7,11 +8,11 @@ namespace ProjectSellPC.Entites
|
|||||||
public class ProductInCheque
|
public class ProductInCheque
|
||||||
{
|
{
|
||||||
public int ID { get; set; }
|
public int ID { get; set; }
|
||||||
|
[System.ComponentModel.Browsable(false)]
|
||||||
//отредактировать базу данных!!!!!!!
|
|
||||||
public int ProductID { get; set; }
|
public int ProductID { get; set; }
|
||||||
|
[Browsable(false)]
|
||||||
public int ChequeID { get; set; }
|
public int ChequeID { get; set; }
|
||||||
|
[DisplayName("Количество")]
|
||||||
public int Count { get; set; }
|
public int Count { get; set; }
|
||||||
public static ProductInCheque CreateElement(int id, int count)
|
public static ProductInCheque CreateElement(int id, int count)
|
||||||
{
|
{
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
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;
|
||||||
@ -7,13 +8,17 @@ namespace ProjectSellPC.Entites
|
|||||||
{
|
{
|
||||||
public class ProductsOnWarehouse
|
public class ProductsOnWarehouse
|
||||||
{
|
{
|
||||||
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
[System.ComponentModel.Browsable(false)]
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int ProductId { get; set; }
|
public int ProductId { get; set; }
|
||||||
|
[DisplayName("Товар")]
|
||||||
public Product Product { get; set; }
|
public Product Product { get; set; }
|
||||||
[System.ComponentModel.Browsable(false)]
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int WarehouseId { get; set; }
|
public int WarehouseId { get; set; }
|
||||||
|
[DisplayName("Склад")]
|
||||||
public Warehouse Warehouse { get; set; }
|
public Warehouse Warehouse { get; set; }
|
||||||
|
[DisplayName("Количество")]
|
||||||
public int Count { get; set; }
|
public int Count { get; set; }
|
||||||
|
|
||||||
public static ProductsOnWarehouse CreateEntity(int id, Product product, Warehouse Warehouse, int count)
|
public static ProductsOnWarehouse CreateEntity(int id, Product product, Warehouse Warehouse, int count)
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
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,8 +9,11 @@ namespace ProjectSellPC.Entites
|
|||||||
{
|
{
|
||||||
public class Warehouse
|
public class Warehouse
|
||||||
{
|
{
|
||||||
|
[System.ComponentModel.Browsable(false)]
|
||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
|
[DisplayName("Вместимость")]
|
||||||
public int Size { get; set; } // Вместимость
|
public int Size { get; set; } // Вместимость
|
||||||
|
[DisplayName("Адрес")]
|
||||||
public string Adress { get; set; }
|
public string Adress { get; set; }
|
||||||
|
|
||||||
public static Warehouse CreateEntity(int id, int size, string adress)
|
public static Warehouse CreateEntity(int id, int size, string adress)
|
||||||
|
@ -16,13 +16,15 @@ namespace ProjectSellPC.Forms.Receipt
|
|||||||
{
|
{
|
||||||
private readonly IUnityContainer _container;
|
private readonly IUnityContainer _container;
|
||||||
private readonly IChequeRepository _ChequeRepository;
|
private readonly IChequeRepository _ChequeRepository;
|
||||||
|
private readonly IClientRepository _clientRepository;
|
||||||
|
|
||||||
public ChequeForm(IUnityContainer unityContainer, IChequeRepository ChequeRepository)
|
public ChequeForm(IUnityContainer unityContainer, IChequeRepository ChequeRepository, IClientRepository clientRepository)
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
|
||||||
_container = unityContainer ?? throw new ArgumentNullException(nameof(unityContainer));
|
_container = unityContainer ?? throw new ArgumentNullException(nameof(unityContainer));
|
||||||
_ChequeRepository = ChequeRepository ?? throw new ArgumentNullException(nameof(ChequeRepository));
|
_ChequeRepository = ChequeRepository ?? throw new ArgumentNullException(nameof(ChequeRepository));
|
||||||
|
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ChequeForm_Load(object sender, EventArgs e)
|
private void ChequeForm_Load(object sender, EventArgs e)
|
||||||
@ -37,8 +39,17 @@ namespace ProjectSellPC.Forms.Receipt
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void LoadList() => ChequesDataGridView.DataSource = _ChequeRepository.ReadAll();
|
private void LoadList()
|
||||||
|
{
|
||||||
|
var checks = _ChequeRepository.ReadAll();
|
||||||
|
|
||||||
|
foreach (var check in checks)
|
||||||
|
{
|
||||||
|
check.Client = _clientRepository.Read(check.ClientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
ChequesDataGridView.DataSource = checks;
|
||||||
|
}
|
||||||
private void addButton_Click(object sender, EventArgs e)
|
private void addButton_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
@ -37,7 +37,12 @@ namespace ProjectSellPC.Forms
|
|||||||
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void LoadList() => productsDataGridView.DataSource = _repository.ReadAll();
|
private void LoadList()
|
||||||
|
{
|
||||||
|
|
||||||
|
productsDataGridView.DataSource = _repository.ReadAll();
|
||||||
|
productsDataGridView.Columns["Id"].Visible = false;
|
||||||
|
}
|
||||||
|
|
||||||
private bool TryGetIdentifierFromSelectedRow(out int id)
|
private bool TryGetIdentifierFromSelectedRow(out int id)
|
||||||
{
|
{
|
||||||
|
@ -24,10 +24,6 @@ namespace ProjectSellPC.Forms.DocReports
|
|||||||
_container = container ?? throw new ArgumentNullException(nameof(container));
|
_container = container ?? throw new ArgumentNullException(nameof(container));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void PdfReportForm_Load(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private void button1_Click(object sender, EventArgs e)
|
private void button1_Click(object sender, EventArgs e)
|
||||||
{
|
{
|
||||||
|
@ -36,7 +36,12 @@ namespace ProjectSellPC
|
|||||||
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private void LoadList() => productsDataGridView.DataSource = _productRepository.ReadAll();
|
private void LoadList()
|
||||||
|
{
|
||||||
|
|
||||||
|
productsDataGridView.DataSource = _productRepository.ReadAll();
|
||||||
|
productsDataGridView.Columns["ID"].Visible = false;
|
||||||
|
}
|
||||||
|
|
||||||
private bool TryGetIdentifierFromSelectedRow(out int id)
|
private bool TryGetIdentifierFromSelectedRow(out int id)
|
||||||
{
|
{
|
||||||
|
@ -18,7 +18,7 @@ using System.Linq;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Windows.Forms;
|
using System.Windows.Forms;
|
||||||
//ТУТ ПРОБЛЕМЫ С КНОПКОЙ РЕДАКТИРОВАТЬ, ТАК КАК ЕЁ НАДО ПОМЕНЯТЬ!!!!!!!!!
|
|
||||||
namespace ProjectSellPC.Forms.ProductsOnWarehouse
|
namespace ProjectSellPC.Forms.ProductsOnWarehouse
|
||||||
{
|
{
|
||||||
public partial class ProductsOnWarehouseForm : Form
|
public partial class ProductsOnWarehouseForm : Form
|
||||||
|
@ -29,6 +29,7 @@ namespace ProjectSellPC.DocBuilder
|
|||||||
new PdfBuilder(filePath)
|
new PdfBuilder(filePath)
|
||||||
.AddHeader("Отчет по продажам товаров")
|
.AddHeader("Отчет по продажам товаров")
|
||||||
.AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами
|
.AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами
|
||||||
|
.AddDate(dateTime) // Добавляем дату создания отчёта
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
@ -38,7 +38,14 @@ namespace ProjectSellPC.DocBuilder
|
|||||||
_document.AddSection().AddParagraph(header, "NormalBold");
|
_document.AddSection().AddParagraph(header, "NormalBold");
|
||||||
return this;//подпись, число
|
return this;//подпись, число
|
||||||
}
|
}
|
||||||
|
public PdfBuilder AddDate(DateTime date)
|
||||||
|
{
|
||||||
|
var paragraph = _document.LastSection.AddParagraph();
|
||||||
|
paragraph.AddText("Дата создания отчёта: ");
|
||||||
|
paragraph.AddText(date.ToString("dd.MM.yyyy")); // Форматируем дату в строку
|
||||||
|
paragraph.Format.Alignment = ParagraphAlignment.Right; // Выравнивание по правому краю
|
||||||
|
return this;
|
||||||
|
}
|
||||||
public PdfBuilder AddPieChart(string title, List<(string Caption, double
|
public PdfBuilder AddPieChart(string title, List<(string Caption, double
|
||||||
Value)> data)
|
Value)> data)
|
||||||
{
|
{
|
||||||
@ -79,7 +86,7 @@ namespace ProjectSellPC.DocBuilder
|
|||||||
|
|
||||||
public void Build()
|
public void Build()
|
||||||
{
|
{
|
||||||
var renderer = new PdfDocumentRenderer(true)
|
var renderer = new PdfDocumentRenderer(true)
|
||||||
{
|
{
|
||||||
Document = _document
|
Document = _document
|
||||||
};
|
};
|
||||||
|
40
ProjectSellPC/ProjectSellPC/Reports/QueryBuilder.cs
Normal file
40
ProjectSellPC/ProjectSellPC/Reports/QueryBuilder.cs
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace ProjectSellPC.Reports
|
||||||
|
{
|
||||||
|
public 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}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -3,23 +3,23 @@ using ProjectSellPC.Repos;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace ProjectSellPC.DocBuilder
|
namespace ProjectSellPC.DocBuilder
|
||||||
{
|
{
|
||||||
internal class TableReport
|
internal class TableReport
|
||||||
{
|
{
|
||||||
private readonly IChequeRepository _chequeRepository;
|
private readonly IChequeRepository _chequeRepository;
|
||||||
private readonly IProductRepository _productRepository;
|
private readonly IClientRepository _clientRepository;
|
||||||
|
private readonly IProductInChequeRepository _productInChequeRepository;
|
||||||
private readonly ILogger<TableReport> _logger;
|
private readonly ILogger<TableReport> _logger;
|
||||||
|
|
||||||
internal static readonly string[] Headers = { "Клиент", "Дата", "Количество" };
|
internal static readonly string[] Headers = { "Клиент", "Дата", "Количество" };
|
||||||
|
|
||||||
public TableReport(IChequeRepository chequeRepository, IProductRepository productRepository, ILoggerFactory loggerFactory)
|
public TableReport(IChequeRepository chequeRepository, IClientRepository clientRepository, IProductInChequeRepository productInChequeRepository, ILoggerFactory loggerFactory)
|
||||||
{
|
{
|
||||||
_chequeRepository = chequeRepository ?? throw new ArgumentNullException(nameof(chequeRepository));
|
_chequeRepository = chequeRepository ?? throw new ArgumentNullException(nameof(chequeRepository));
|
||||||
_productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
|
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
|
||||||
|
_productInChequeRepository = productInChequeRepository ?? throw new ArgumentNullException(nameof(productInChequeRepository));
|
||||||
_logger = loggerFactory.CreateLogger<TableReport>();
|
_logger = loggerFactory.CreateLogger<TableReport>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -41,9 +41,13 @@ namespace ProjectSellPC.DocBuilder
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate)
|
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate)
|
||||||
{
|
{
|
||||||
|
// Получение данных о товарах в чеках, содержащих указанный товар
|
||||||
|
var productsInChecks = _productInChequeRepository.ReadAll()
|
||||||
|
.Where(p => p.ProductID == productId) // Фильтр по товару
|
||||||
|
.ToList();
|
||||||
|
|
||||||
// Получение данных о чеках, содержащих указанный товар
|
// Получение данных о чеках, содержащих указанный товар
|
||||||
var checksWithProduct = _chequeRepository
|
var checksWithProduct = _chequeRepository
|
||||||
.ReadAll()
|
.ReadAll()
|
||||||
@ -51,34 +55,42 @@ namespace ProjectSellPC.DocBuilder
|
|||||||
&& c.Products.Any(p => p.ProductID == productId))
|
&& c.Products.Any(p => p.ProductID == productId))
|
||||||
.Select(c => new
|
.Select(c => new
|
||||||
{
|
{
|
||||||
ClientName = c.Client?.ToString() ?? "Неизвестно",
|
CheckId = c.Id, // Номер чека
|
||||||
|
ClientId = c.Client?.Id ?? 0, // Получаем ClientId или 0, если клиент неизвестен
|
||||||
Date = c.PurchaseDate,
|
Date = c.PurchaseDate,
|
||||||
Quantity = c.Products
|
Quantity = c.Products
|
||||||
.Where(p => p.ProductID == productId)
|
.Where(p => p.ProductID == productId)
|
||||||
.Sum(p => p.Count)
|
.Sum(p => p.Count)
|
||||||
})
|
})
|
||||||
.OrderBy(x => x.Date);
|
.OrderBy(x => x.Date)
|
||||||
|
.ToList(); // Добавляем ToList() для выполнения запроса
|
||||||
|
|
||||||
|
// Получение имен клиентов по ClientId
|
||||||
|
var clientIds = checksWithProduct.Select(x => x.ClientId).Distinct().ToList();
|
||||||
|
var clients = _clientRepository.ReadAll()
|
||||||
|
.Where(c => clientIds.Contains(c.Id)) // Фильтруем клиентов по ClientId
|
||||||
|
.ToDictionary(c => c.Id, c => c.Name); // Создаем словарь клиентов
|
||||||
|
|
||||||
// Формирование итоговой таблицы
|
// Формирование итоговой таблицы
|
||||||
return new List<string[]> { Headers }
|
return new List<string[]> { Headers }
|
||||||
.Union(
|
.Union(
|
||||||
checksWithProduct.Select(x => new string[]
|
checksWithProduct.Select(x => new string[]
|
||||||
{
|
{
|
||||||
x.ClientName,
|
clients.ContainsKey(x.ClientId) ? clients[x.ClientId] : "Неизвестно", // Имя клиента
|
||||||
x.Date.ToShortDateString(),
|
x.Date.ToShortDateString(),
|
||||||
x.Quantity.ToString()
|
x.Quantity.ToString()
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
.Union(new[]
|
.Union(new[]
|
||||||
{
|
{
|
||||||
new string[]
|
new string[]
|
||||||
{
|
{
|
||||||
"Всего",
|
"Всего",
|
||||||
"",
|
"",
|
||||||
checksWithProduct.Sum(x => x.Quantity).ToString()
|
checksWithProduct.Sum(x => x.Quantity).ToString()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -4,7 +4,7 @@ namespace ProjectSellPC.Repos
|
|||||||
{
|
{
|
||||||
public interface IChequeRepository
|
public interface IChequeRepository
|
||||||
{
|
{
|
||||||
IEnumerable<Cheque> ReadAll();
|
IEnumerable<Cheque> ReadAll(DateTime? startDate = null, DateTime? endDate = null, int? productId = null, int? clientId = null);
|
||||||
Cheque Read(int id);
|
Cheque Read(int id);
|
||||||
void Create(Cheque Cheque);
|
void Create(Cheque Cheque);
|
||||||
}
|
}
|
||||||
|
@ -1,11 +1,15 @@
|
|||||||
using ProjectSellPC.Entites;
|
using ProjectSellPC.Entites;
|
||||||
|
using ProjectSellPC.Reports;
|
||||||
using Dapper;
|
using Dapper;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using DocumentFormat.OpenXml.Drawing.Charts;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Npgsql;
|
using Npgsql;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Windows.Forms;
|
||||||
|
|
||||||
namespace ProjectSellPC.Repos.Impements
|
namespace ProjectSellPC.Repos.Impements
|
||||||
{
|
{
|
||||||
@ -23,7 +27,7 @@ namespace ProjectSellPC.Repos.Impements
|
|||||||
}
|
}
|
||||||
|
|
||||||
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
|
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
|
||||||
public void Create(Cheque Cheque)
|
public void Create(Cheque cheque)
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Создание чека");
|
_logger.LogInformation("Создание чека");
|
||||||
using (var connection = CreateConnection())
|
using (var connection = CreateConnection())
|
||||||
@ -33,19 +37,25 @@ namespace ProjectSellPC.Repos.Impements
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var chequeSql = "INSERT INTO \"cheque\" (\"clientid\", \"purchasedate\") VALUES (@ClientId, @PurchaseDate) RETURNING \"id\"";
|
// Убедитесь, что ClientId установлен
|
||||||
Cheque.Id = connection.ExecuteScalar<int>(chequeSql, new
|
if (cheque.Client == null || cheque.Client.Id == 0)
|
||||||
{
|
{
|
||||||
ClientId = Cheque.Client.Id,
|
throw new InvalidOperationException("ClientId не может быть пустым или равным 0");
|
||||||
PurchaseDate = Cheque.PurchaseDate
|
}
|
||||||
|
|
||||||
|
var chequeSql = "INSERT INTO \"cheque\" (\"clientid\", \"purchasedate\") VALUES (@ClientId, @PurchaseDate) RETURNING \"id\"";
|
||||||
|
cheque.Id = connection.ExecuteScalar<int>(chequeSql, new
|
||||||
|
{
|
||||||
|
ClientId = cheque.Client.Id,
|
||||||
|
PurchaseDate = cheque.PurchaseDate
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var productSql = "INSERT INTO \"productincheque\" (\"chequeid\", \"productid\", \"count\") VALUES (@ChequeId, @ProductID, @Count)";
|
var productSql = "INSERT INTO \"productincheque\" (\"chequeid\", \"productid\", \"count\") VALUES (@ChequeId, @ProductID, @Count)";
|
||||||
foreach (var productInCheque in Cheque.Products)
|
foreach (var productInCheque in cheque.Products)
|
||||||
{
|
{
|
||||||
connection.Execute(productSql, new
|
connection.Execute(productSql, new
|
||||||
{
|
{
|
||||||
ChequeId = Cheque.Id,
|
ChequeId = cheque.Id,
|
||||||
ProductID = productInCheque.ProductID,
|
ProductID = productInCheque.ProductID,
|
||||||
Count = productInCheque.Count
|
Count = productInCheque.Count
|
||||||
}, transaction);
|
}, transaction);
|
||||||
@ -89,33 +99,59 @@ namespace ProjectSellPC.Repos.Impements
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public IEnumerable<Cheque> ReadAll(DateTime? startDate = null, DateTime? endDate = null, int? productId = null, int? clientId = null)
|
||||||
public IEnumerable<Cheque> ReadAll()
|
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Чтение всех чеков");
|
_logger.LogInformation("Чтение всех чеков с использованием фильтров");
|
||||||
using (var connection = CreateConnection())
|
try
|
||||||
{
|
{
|
||||||
try
|
var builder = new QueryBuilder();
|
||||||
{
|
|
||||||
var ChequeSql = "SELECT * FROM \"cheque\"";
|
|
||||||
var Cheques = connection.Query<Cheque>(ChequeSql).ToList();
|
|
||||||
|
|
||||||
foreach (var Cheque in Cheques)
|
// Добавляем условия фильтрации, если параметры заданы
|
||||||
|
if (startDate.HasValue)
|
||||||
|
builder.AddCondition("\"cheque\".\"purchasedate\" >= @StartDate");
|
||||||
|
if (endDate.HasValue)
|
||||||
|
builder.AddCondition("\"cheque\".\"purchasedate\" <= @EndDate");
|
||||||
|
if (productId.HasValue)
|
||||||
|
builder.AddCondition("\"productincheque\".\"productid\" = @ProductId");
|
||||||
|
if (clientId.HasValue)
|
||||||
|
builder.AddCondition("\"cheque\".\"clientid\" = @ClientId");
|
||||||
|
|
||||||
|
// Формируем основной SQL-запрос
|
||||||
|
var query = $"SELECT \"cheque\".*, \"client\".\"id\" AS \"clientid\", \"client\".\"name\" AS \"clientname\" " +
|
||||||
|
$"FROM \"cheque\" " +
|
||||||
|
$"LEFT JOIN \"client\" ON \"cheque\".\"clientid\" = \"client\".\"id\" " +
|
||||||
|
$"LEFT JOIN \"productincheque\" ON \"productincheque\".\"chequeid\" = \"cheque\".\"id\" " +
|
||||||
|
$"{builder.Build()} " +
|
||||||
|
$"ORDER BY \"cheque\".\"purchasedate\"";
|
||||||
|
|
||||||
|
// Выполняем запрос
|
||||||
|
using var connection = CreateConnection();
|
||||||
|
var cheques = connection.Query<Cheque, int, string, Cheque>(
|
||||||
|
query,
|
||||||
|
(cheque, clientId, clientName) =>
|
||||||
{
|
{
|
||||||
Cheque.Client = _clientRepository.Read(Cheque.ClientId);
|
cheque.Client = new Client { Id = clientId, Name = clientName ?? "Неизвестно" };
|
||||||
|
return cheque;
|
||||||
|
},
|
||||||
|
new { StartDate = startDate, EndDate = endDate, ProductId = productId, ClientId = clientId },
|
||||||
|
splitOn: "clientid,clientname"
|
||||||
|
).ToList();
|
||||||
|
|
||||||
var productSql = "SELECT * FROM \"productincheque\" WHERE \"chequeid\" = @ChequeId";
|
// Загружаем товары для каждого чека
|
||||||
Cheque.Products = connection.Query<ProductInCheque>(productSql, new { ChequeId = Cheque.Id }).ToList();
|
foreach (var cheque in cheques)
|
||||||
}
|
|
||||||
|
|
||||||
return Cheques;
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Ошибка при чтении всех чеков");
|
var productQuery = "SELECT * FROM \"productincheque\" WHERE \"chequeid\" = @ChequeId";
|
||||||
throw;
|
cheque.Products = connection.Query<ProductInCheque>(productQuery, new { ChequeId = cheque.Id }).ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return cheques;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Ошибка при чтении всех чеков");
|
||||||
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@ namespace ProjectSellPC.Repos.Impements
|
|||||||
public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
|
public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
|
||||||
{
|
{
|
||||||
_connectionString = connectionString;
|
_connectionString = connectionString;
|
||||||
//_logger = logger;
|
|
||||||
_logger = loggerFactory.CreateLogger<ProductRepo>();
|
_logger = loggerFactory.CreateLogger<ProductRepo>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user