Лабораторная 4

This commit is contained in:
aaahsap 2024-12-23 09:08:02 +04:00
parent 6833381b98
commit 658b0bc060
18 changed files with 199 additions and 61 deletions

View File

@ -1,13 +1,19 @@
namespace ProjectSellPC.Entites
using System.ComponentModel;
namespace ProjectSellPC.Entites
{
public class Cheque
{
[System.ComponentModel.Browsable(false)]
public int Id { get; set; }
[DisplayName("Товары")]
public List<ProductInCheque> Products { get; set; }
[DisplayName("Клиент")]
public Client Client { get; set; }
[System.ComponentModel.Browsable(false)]
public int ClientId { get; set; }
[DisplayName("Дата покупки")]
public DateTime PurchaseDate { get; set; }
public static Cheque CreateEntity(int id, List<ProductInCheque> products, Client client, DateTime purchaseDate)

View File

@ -1,6 +1,7 @@
using ProjectSellPC.Entites.Enums;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -10,8 +11,11 @@ namespace ProjectSellPC.Entites
public class Client
{
public int Id { get; set; }
[DisplayName("Имя")]
public string Name { get; set; }
[DisplayName("Номер телефона")]
public string PhoneNumber { get; set; }
[DisplayName("Вид клиента")]
public ClientType ClientType { get; set; }
public static Client CreateEntity(int id, string name, string phoneNumber, ClientType clientType)

View File

@ -1,13 +1,18 @@
using ProjectSellPC.Entites.Enums;
using System.ComponentModel;
namespace ProjectSellPC.Entites
{
public class Product
{
public int ID { get; private set; }
[DisplayName("Имя")]
public string Name { get; private set; }
[DisplayName("Описание")]
public string Description { get; private set; }
[DisplayName("Цена")]
public decimal Price { get; private set; }
[DisplayName("Вид")]
public ProductType ProductType { get; private set; }
public static Product CreateEntity(int id, string name, string desc, decimal price, ProductType productType)

View File

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -7,11 +8,11 @@ namespace ProjectSellPC.Entites
public class ProductInCheque
{
public int ID { get; set; }
//отредактировать базу данных!!!!!!!
[System.ComponentModel.Browsable(false)]
public int ProductID { get; set; }
[Browsable(false)]
public int ChequeID { get; set; }
[DisplayName("Количество")]
public int Count { get; set; }
public static ProductInCheque CreateElement(int id, int count)
{

View File

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -7,13 +8,17 @@ namespace ProjectSellPC.Entites
{
public class ProductsOnWarehouse
{
[System.ComponentModel.Browsable(false)]
public int Id { get; set; }
[System.ComponentModel.Browsable(false)]
public int ProductId { get; set; }
[DisplayName("Товар")]
public Product Product { get; set; }
[System.ComponentModel.Browsable(false)]
public int WarehouseId { get; set; }
[DisplayName("Склад")]
public Warehouse Warehouse { get; set; }
[DisplayName("Количество")]
public int Count { get; set; }
public static ProductsOnWarehouse CreateEntity(int id, Product product, Warehouse Warehouse, int count)

View File

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -8,8 +9,11 @@ namespace ProjectSellPC.Entites
{
public class Warehouse
{
[System.ComponentModel.Browsable(false)]
public int Id { get; set; }
[DisplayName("Вместимость")]
public int Size { get; set; } // Вместимость
[DisplayName("Адрес")]
public string Adress { get; set; }
public static Warehouse CreateEntity(int id, int size, string adress)

View File

@ -16,13 +16,15 @@ namespace ProjectSellPC.Forms.Receipt
{
private readonly IUnityContainer _container;
private readonly IChequeRepository _ChequeRepository;
private readonly IClientRepository _clientRepository;
public ChequeForm(IUnityContainer unityContainer, IChequeRepository ChequeRepository)
public ChequeForm(IUnityContainer unityContainer, IChequeRepository ChequeRepository, IClientRepository clientRepository)
{
InitializeComponent();
_container = unityContainer ?? throw new ArgumentNullException(nameof(unityContainer));
_ChequeRepository = ChequeRepository ?? throw new ArgumentNullException(nameof(ChequeRepository));
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
}
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)
{
try

View File

@ -37,7 +37,12 @@ namespace ProjectSellPC.Forms
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)
{

View File

@ -24,10 +24,6 @@ namespace ProjectSellPC.Forms.DocReports
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void PdfReportForm_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{

View File

@ -36,7 +36,12 @@ namespace ProjectSellPC
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)
{

View File

@ -18,7 +18,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//ТУТ ПРОБЛЕМЫ С КНОПКОЙ РЕДАКТИРОВАТЬ, ТАК КАК ЕЁ НАДО ПОМЕНЯТЬ!!!!!!!!!
namespace ProjectSellPC.Forms.ProductsOnWarehouse
{
public partial class ProductsOnWarehouseForm : Form

View File

@ -29,6 +29,7 @@ namespace ProjectSellPC.DocBuilder
new PdfBuilder(filePath)
.AddHeader("Отчет по продажам товаров")
.AddPieChart("Проданные товары", GetData(dateTime)) // Диаграмма с продуктами
.AddDate(dateTime) // Добавляем дату создания отчёта
.Build();
return true;

View File

@ -38,7 +38,14 @@ namespace ProjectSellPC.DocBuilder
_document.AddSection().AddParagraph(header, "NormalBold");
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
Value)> data)
{
@ -79,7 +86,7 @@ namespace ProjectSellPC.DocBuilder
public void Build()
{
var renderer = new PdfDocumentRenderer(true)
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};

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

View File

@ -3,23 +3,23 @@ using ProjectSellPC.Repos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSellPC.DocBuilder
{
internal class TableReport
{
private readonly IChequeRepository _chequeRepository;
private readonly IProductRepository _productRepository;
private readonly IClientRepository _clientRepository;
private readonly IProductInChequeRepository _productInChequeRepository;
private readonly ILogger<TableReport> _logger;
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));
_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>();
}
@ -41,9 +41,13 @@ namespace ProjectSellPC.DocBuilder
return false;
}
}
private List<string[]> GetData(int productId, DateTime startDate, DateTime endDate)
{
// Получение данных о товарах в чеках, содержащих указанный товар
var productsInChecks = _productInChequeRepository.ReadAll()
.Where(p => p.ProductID == productId) // Фильтр по товару
.ToList();
// Получение данных о чеках, содержащих указанный товар
var checksWithProduct = _chequeRepository
.ReadAll()
@ -51,34 +55,42 @@ namespace ProjectSellPC.DocBuilder
&& c.Products.Any(p => p.ProductID == productId))
.Select(c => new
{
ClientName = c.Client?.ToString() ?? "Неизвестно",
CheckId = c.Id, // Номер чека
ClientId = c.Client?.Id ?? 0, // Получаем ClientId или 0, если клиент неизвестен
Date = c.PurchaseDate,
Quantity = c.Products
.Where(p => p.ProductID == productId)
.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 }
.Union(
checksWithProduct.Select(x => new string[]
{
x.ClientName,
x.Date.ToShortDateString(),
x.Quantity.ToString()
clients.ContainsKey(x.ClientId) ? clients[x.ClientId] : "Неизвестно", // Имя клиента
x.Date.ToShortDateString(),
x.Quantity.ToString()
})
)
.Union(new[]
{
new string[]
{
"Всего",
"",
checksWithProduct.Sum(x => x.Quantity).ToString()
}
new string[]
{
"Всего",
"",
checksWithProduct.Sum(x => x.Quantity).ToString()
}
})
.ToList();
}
}
}
}

View File

@ -4,7 +4,7 @@ namespace ProjectSellPC.Repos
{
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);
void Create(Cheque Cheque);
}

View File

@ -1,11 +1,15 @@
using ProjectSellPC.Entites;
using ProjectSellPC.Reports;
using Dapper;
using Newtonsoft.Json;
using DocumentFormat.OpenXml.Drawing.Charts;
using Microsoft.Extensions.Logging;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace ProjectSellPC.Repos.Impements
{
@ -23,7 +27,7 @@ namespace ProjectSellPC.Repos.Impements
}
private IDbConnection CreateConnection() => new NpgsqlConnection(_connectionString.ConnectionString);
public void Create(Cheque Cheque)
public void Create(Cheque cheque)
{
_logger.LogInformation("Создание чека");
using (var connection = CreateConnection())
@ -33,19 +37,25 @@ namespace ProjectSellPC.Repos.Impements
{
try
{
var chequeSql = "INSERT INTO \"cheque\" (\"clientid\", \"purchasedate\") VALUES (@ClientId, @PurchaseDate) RETURNING \"id\"";
Cheque.Id = connection.ExecuteScalar<int>(chequeSql, new
// Убедитесь, что ClientId установлен
if (cheque.Client == null || cheque.Client.Id == 0)
{
ClientId = Cheque.Client.Id,
PurchaseDate = Cheque.PurchaseDate
throw new InvalidOperationException("ClientId не может быть пустым или равным 0");
}
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);
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
{
ChequeId = Cheque.Id,
ChequeId = cheque.Id,
ProductID = productInCheque.ProductID,
Count = productInCheque.Count
}, transaction);
@ -89,33 +99,59 @@ namespace ProjectSellPC.Repos.Impements
}
}
}
public IEnumerable<Cheque> ReadAll()
public IEnumerable<Cheque> ReadAll(DateTime? startDate = null, DateTime? endDate = null, int? productId = null, int? clientId = null)
{
_logger.LogInformation("Чтение всех чеков");
using (var connection = CreateConnection())
_logger.LogInformation("Чтение всех чеков с использованием фильтров");
try
{
try
{
var ChequeSql = "SELECT * FROM \"cheque\"";
var Cheques = connection.Query<Cheque>(ChequeSql).ToList();
var builder = new QueryBuilder();
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();
}
return Cheques;
}
catch (Exception ex)
// Загружаем товары для каждого чека
foreach (var cheque in cheques)
{
_logger.LogError(ex, "Ошибка при чтении всех чеков");
throw;
var productQuery = "SELECT * FROM \"productincheque\" WHERE \"chequeid\" = @ChequeId";
cheque.Products = connection.Query<ProductInCheque>(productQuery, new { ChequeId = cheque.Id }).ToList();
}
return cheques;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении всех чеков");
throw;
}
}
}
}

View File

@ -17,7 +17,7 @@ namespace ProjectSellPC.Repos.Impements
public ProductRepo(IConnectionString connectionString, ILoggerFactory loggerFactory)
{
_connectionString = connectionString;
//_logger = logger;
_logger = loggerFactory.CreateLogger<ProductRepo>();
}