не создаётся pdf

This commit is contained in:
RozhVan 2024-12-21 10:43:19 +04:00
parent 8a1b622b21
commit 07e82fc4a3
14 changed files with 57 additions and 55 deletions

View File

@ -1,4 +1,6 @@
namespace GasStation.Entities; using System.Collections;
namespace GasStation.Entities;
public class Selling public class Selling
{ {
@ -6,21 +8,29 @@ public class Selling
public int GasmanId { get; private set; } public int GasmanId { get; private set; }
public int Count { get; private set; }
public IEnumerable<ProductSelling> ProdutcSellings { get; private set; } = []; public IEnumerable<ProductSelling> ProdutcSellings { get; private set; } = [];
public DateTime SellingDateTime { get; private set; } public DateTime SellingDateTime { get; private set; }
public static Selling CreateSelling(int id, int gasmanId, int count, IEnumerable<ProductSelling> produtcSellings) public static Selling CreateSelling(int id, int gasmanId, IEnumerable<ProductSelling> produtcSellings)
{ {
return new Selling return new Selling
{ {
Id = id, Id = id,
GasmanId = gasmanId, GasmanId = gasmanId,
Count = count,
SellingDateTime = DateTime.Now, SellingDateTime = DateTime.Now,
ProdutcSellings = produtcSellings ProdutcSellings = produtcSellings
}; };
} }
public static Selling CreateSelling(TempProductSelling tempProductSelling, IEnumerable<ProductSelling> produtcSellings)
{
return new Selling
{
Id = tempProductSelling.Id,
GasmanId = tempProductSelling.GasmanId,
SellingDateTime = tempProductSelling.SellingDateTime,
ProdutcSellings = produtcSellings
};
}
} }

View File

@ -120,6 +120,7 @@
// ProductReportToolStripMenuItem // ProductReportToolStripMenuItem
// //
ProductReportToolStripMenuItem.Name = "ProductReportToolStripMenuItem"; ProductReportToolStripMenuItem.Name = "ProductReportToolStripMenuItem";
ProductReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
ProductReportToolStripMenuItem.Size = new Size(280, 22); ProductReportToolStripMenuItem.Size = new Size(280, 22);
ProductReportToolStripMenuItem.Text = "Движение товаров"; ProductReportToolStripMenuItem.Text = "Движение товаров";
ProductReportToolStripMenuItem.Click += ProductReportToolStripMenuItem_Click; ProductReportToolStripMenuItem.Click += ProductReportToolStripMenuItem_Click;

View File

@ -103,7 +103,7 @@ namespace GasStation
{ {
try try
{ {
_container.Resolve<FormSellDistRep>().ShowDialog(); _container.Resolve<FormSupplyDistRep>().ShowDialog();
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -41,7 +41,7 @@ namespace GasStation.Forms
} }
if (comboBoxProduct.SelectedIndex < 0) if (comboBoxProduct.SelectedIndex < 0)
{ {
throw new Exception("Не выбран корм"); throw new Exception("Не выбран товар");
} }
if (dateTimePickerEnd.Value <= dateTimePickerBegin.Value) if (dateTimePickerEnd.Value <= dateTimePickerBegin.Value)
{ {

View File

@ -33,8 +33,7 @@ namespace GasStation.Forms
throw new Exception("Имеются незаполненые поля"); throw new Exception("Имеются незаполненые поля");
} }
_sellingRepository.CreateSelling(Selling.CreateSelling(0, (int)comboBoxGasman.SelectedValue!, _sellingRepository.CreateSelling(Selling.CreateSelling(0, (int)comboBoxGasman.SelectedValue!, CreateProductSellingsFromDataGrid()));
0, CreateProductSellingsFromDataGrid()));
Close(); Close();
} }

View File

@ -1,6 +1,6 @@
namespace GasStation.Reports namespace GasStation.Reports
{ {
partial class FormSellDistRep partial class FormSupplyDistRep
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
@ -80,7 +80,7 @@
labelFileName.TabIndex = 4; labelFileName.TabIndex = 4;
labelFileName.Text = "Файл"; labelFileName.Text = "Файл";
// //
// FormSellDistRep // FormSupplyDistRep
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
@ -90,8 +90,8 @@
Controls.Add(dateTimePicker); Controls.Add(dateTimePicker);
Controls.Add(buttonCreate); Controls.Add(buttonCreate);
Controls.Add(buttonSelectFileName); Controls.Add(buttonSelectFileName);
Name = "FormSellDistRep"; Name = "FormSupplyDistRep";
Text = "Распределение товара"; Text = "Поступление товара";
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }

View File

@ -2,13 +2,13 @@
namespace GasStation.Reports; namespace GasStation.Reports;
public partial class FormSellDistRep : Form public partial class FormSupplyDistRep : Form
{ {
private string _fileName = string.Empty; private string _fileName = string.Empty;
private readonly IUnityContainer _container; private readonly IUnityContainer _container;
public FormSellDistRep(IUnityContainer container) public FormSupplyDistRep(IUnityContainer container)
{ {
InitializeComponent(); InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container)); _container = container ?? throw new ArgumentNullException(nameof(container));

View File

@ -5,13 +5,13 @@ namespace GasStation.Reports;
internal class ChartReport internal class ChartReport
{ {
private readonly ISellingRepository _sellingRepository; private readonly ISupplyRepository _supplyRepository;
private readonly ILogger<ChartReport> _logger; private readonly ILogger<ChartReport> _logger;
public ChartReport(ISellingRepository sellingRepository, ILogger<ChartReport> logger) public ChartReport(ISupplyRepository supplyRepository, ILogger<ChartReport> logger)
{ {
_sellingRepository = sellingRepository ?? _supplyRepository = supplyRepository ??
throw new throw new
ArgumentNullException(nameof(sellingRepository)); ArgumentNullException(nameof(supplyRepository));
_logger = logger ?? _logger = logger ??
throw new ArgumentNullException(nameof(logger)); throw new ArgumentNullException(nameof(logger));
} }
@ -20,8 +20,8 @@ internal class ChartReport
try try
{ {
new PdfBuilder(filePath) new PdfBuilder(filePath)
.AddHeader(родажа продукта") .AddHeader(оступление продукта")
.AddPieChart(роданный товар", GetData(dateTime)) .AddPieChart(оступивший товар", GetData(dateTime))
.Build(); .Build();
return true; return true;
} }
@ -33,10 +33,10 @@ internal class ChartReport
} }
private List<(string Caption, double Value)> GetData(DateTime dateTime) private List<(string Caption, double Value)> GetData(DateTime dateTime)
{ {
return _sellingRepository return _supplyRepository
.ReadSelling() .ReadSupply()
.Where(x => x.SellingDateTime.Date == dateTime.Date) .Where(x => x.SupplyDate.Date == dateTime.Date)
.GroupBy(x => x.GasmanId, (key, group) => new { Id = key, Count = group.Sum(x => x.Count)}) .GroupBy(x => x.ProductID, (key, group) => new { Id = key, Count = group.Sum(x => x.Count)})
.Select(x => (x.Id.ToString(), (double)x.Count)).ToList(); .Select(x => (x.Id.ToString(), (double)x.Count)).ToList();
} }
} }

View File

@ -79,7 +79,7 @@ internal class DocReport
private List<string[]> GetProducts() private List<string[]> GetProducts()
{ {
return [ return [
["Тип корма", "Название"], ["Стоимость товара", "Тип товара"],
.. _productRepository .. _productRepository
.ReadProduct() .ReadProduct()
.Select(x => new string[] { x.ProductCost.ToString(), x.ProductType.ToString() }), .Select(x => new string[] { x.ProductCost.ToString(), x.ProductType.ToString() }),

View File

@ -30,7 +30,7 @@ internal class ExcelBuilder
public ExcelBuilder AddHeader(string header, int startIndex, int count) public ExcelBuilder AddHeader(string header, int startIndex, int count)
{ {
CreateCell(startIndex, _rowIndex, header, CreateCell(startIndex, _rowIndex, header,
StyleIndex.SimpleTextWithoutBorder); StyleIndex.BoldTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i) for (int i = startIndex + 1; i < startIndex + count; ++i)
{ {
CreateCell(i, _rowIndex, "", CreateCell(i, _rowIndex, "",
@ -79,7 +79,7 @@ internal class ExcelBuilder
for (var j = 0; j < data.First().Length; ++j) for (var j = 0; j < data.First().Length; ++j)
{ {
CreateCell(j, _rowIndex, data.First()[j], CreateCell(j, _rowIndex, data.First()[j],
StyleIndex.SimpleTextWithoutBorder); StyleIndex.BoldTextWithBorder);
} }
_rowIndex++; _rowIndex++;
for (var i = 1; i < data.Count - 1; ++i) for (var i = 1; i < data.Count - 1; ++i)
@ -87,14 +87,14 @@ internal class ExcelBuilder
for (var j = 0; j < data[i].Length; ++j) for (var j = 0; j < data[i].Length; ++j)
{ {
CreateCell(j, _rowIndex, data[i][j], CreateCell(j, _rowIndex, data[i][j],
StyleIndex.SimpleTextWithoutBorder); StyleIndex.SimpleTextWithBorder);
} }
_rowIndex++; _rowIndex++;
} }
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.SimpleTextWithoutBorder); StyleIndex.BoldTextWithBorder);
} }
_rowIndex++; _rowIndex++;
return this; return this;

View File

@ -1,6 +1,7 @@
using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts; using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.Rendering; using MigraDoc.Rendering;
using System.Text;
namespace GasStation.Reports; namespace GasStation.Reports;
@ -9,6 +10,7 @@ internal class PdfBuilder
private readonly string _filePath; private readonly string _filePath;
private readonly Document _document; private readonly Document _document;
public PdfBuilder(string filePath) public PdfBuilder(string filePath)
{ {
if (string.IsNullOrWhiteSpace(filePath)) if (string.IsNullOrWhiteSpace(filePath))
@ -58,6 +60,7 @@ internal class PdfBuilder
} }
public void Build() public void Build()
{ {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var renderer = new PdfDocumentRenderer(true) var renderer = new PdfDocumentRenderer(true)
{ {
Document = _document Document = _document

View File

@ -5,20 +5,15 @@ namespace GasStation.Reports;
internal class TableReport internal class TableReport
{ {
private readonly ISupplyRepository _supplyRepository;
private readonly ISellingRepository _sellingRepository; private readonly ISellingRepository _sellingRepository;
private readonly ILogger<TableReport> _logger; private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Сотрудник", "Дата", "Количество пришло", "Количество ушло"]; internal static readonly string[] item = ["Сотрудник", "Дата", "Продажа"];
public TableReport(ISupplyRepository supplyRepository, ISellingRepository sellingRepository, public TableReport(ISellingRepository sellingRepository,
ILogger<TableReport> logger) ILogger<TableReport> logger)
{ {
_supplyRepository = supplyRepository ??
throw new
ArgumentNullException(nameof(supplyRepository));
_sellingRepository = sellingRepository ?? _sellingRepository = sellingRepository ??
throw new throw new ArgumentNullException(nameof(sellingRepository));
ArgumentNullException(nameof(sellingRepository));
_logger = logger ?? _logger = logger ??
throw new ArgumentNullException(nameof(logger)); throw new ArgumentNullException(nameof(logger));
} }
@ -27,9 +22,9 @@ internal class TableReport
try try
{ {
new ExcelBuilder(filePath) new ExcelBuilder(filePath)
.AddHeader("Сводка по движению товара", 0, 4) .AddHeader("Сводка по движению товара", 0, 3)
.AddParagraph("за период", 0) .AddParagraph("за период", 0)
.AddTable([10, 10, 15, 15], GetData(productId, startDate, endDate)) .AddTable([10, 10, 15], GetData(productId, startDate, endDate))
.Build(); .Build();
return true; return true;
} }
@ -39,27 +34,21 @@ internal class TableReport
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 data = _supplyRepository var data = _sellingRepository
.ReadSupply()
.Where(x => x.SupplyDate >= startDate && x.SupplyDate <= endDate)
.Select(x => new { x.SupplierID, Date = x.SupplyDate, CountIn = (int?)x.Count, CountOut = (int?)null })
.Union(
_sellingRepository
.ReadSelling() .ReadSelling()
.Where(x => x.SellingDateTime >= startDate && x.SellingDateTime <= endDate && x.ProdutcSellings.Any(y => y.ProductID == productId)) .Where(x => x.SellingDateTime >= startDate && x.SellingDateTime <= endDate && x.ProdutcSellings.Any(y => y.ProductID == productId))
.Select(x => new {x.GasmanId, Date = x.SellingDateTime, CountIn = (int?)null, .Select(x => new {x.GasmanId, Date = x.SellingDateTime,
CountOut = x.ProdutcSellings.FirstOrDefault(y => y.ProductID == productId)?.Count }) CountOut = x.ProdutcSellings.FirstOrDefault(y => y.ProductID == productId)?.Count })
) .OrderBy(x => x.Date);
.OrderBy(x => x.Date);
return new List<string[]>() { item }.Union(data return new List<string[]>() { item }.Union(data
.Select(x => .Select(x =>
new string[] { x.GasmanId.ToString(), x.Date.ToString(), x.CountIn?.ToString() ?? new string[] { x.GasmanId.ToString(), x.Date.ToString(), x.CountOut?.ToString() ?? string.Empty}))
string.Empty, x.CountOut?.ToString() ?? string.Empty}))
.Union( .Union(
[["Всего", "", data.Sum(x => x.CountIn ?? 0).ToString(), data.Sum(x => x.CountOut ?? 0).ToString()]] [["Всего", "", data.Sum(x => x.CountOut ?? 0).ToString()]]
).ToList(); ).ToList();
} }
} }

View File

@ -29,8 +29,8 @@ public class SellingRepository : ISellingRepository
connection.Open(); connection.Open();
using var transaction = connection.BeginTransaction(); using var transaction = connection.BeginTransaction();
var queryInsert = @" var queryInsert = @"
INSERT INTO selling (sellingDateTime, gasmanId, count) INSERT INTO selling (sellingDateTime, gasmanId)
VALUES (@SellingDateTime, @GasmanId, @Count); VALUES (@SellingDateTime, @GasmanId);
SELECT MAX(Id) FROM selling"; SELECT MAX(Id) FROM selling";
var Id = connection.QueryFirst<int>(queryInsert, selling, transaction); var Id = connection.QueryFirst<int>(queryInsert, selling, transaction);
var querySubInsert = @" var querySubInsert = @"
@ -57,7 +57,7 @@ VALUES (@Id, @ProductID, @Count)";
using var connection = new NpgsqlConnection(_connectionString.ConnectionString); using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @" var querySelect = @"
SELECT s.*, ps.ProductID, ps.Count FROM selling s SELECT s.*, ps.ProductID, ps.Count FROM selling s
INNER JOIN ProductSelling ps ON ps.SellingId = s.Id"; INNER JOIN Product_Selling ps ON ps.Id = s.Id";
var selling = connection.Query<TempProductSelling>(querySelect); var selling = connection.Query<TempProductSelling>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(selling)); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(selling));
return selling.GroupBy(x => x.Id, y => y, (key, value) => return selling.GroupBy(x => x.Id, y => y, (key, value) =>