Второй шаг

This commit is contained in:
mara-1 2024-12-13 02:07:58 +04:00
parent e64555709f
commit 0ed0d71bc8
9 changed files with 802 additions and 18 deletions

View File

@ -11,21 +11,32 @@ public class RaceEntries
public int Id { get; private set; } public int Id { get; private set; }
public int JockeyId { get; private set; } public int JockeyId { get; private set; }
public DateTime DateReceipt { get; private set; } public DateTime DateReceipt { get; private set; }
public IEnumerable<RaceEntryDetails> RaceEntryDetails
{ public IEnumerable<RaceEntryDetails> RacesEntryDetails { get; private set; } = [];
get;
private set;
} = [];
public static RaceEntries CreateOpeartion(int id, int jockeyId, public static RaceEntries CreateOpeartion(int id, int jockeyId,
IEnumerable<RaceEntryDetails> raceEntryDetails) IEnumerable<RaceEntryDetails> racesEntryDetails)
{ {
return new RaceEntries return new RaceEntries
{ {
Id = id, Id = id,
JockeyId = jockeyId, JockeyId = jockeyId,
DateReceipt = DateTime.Now, DateReceipt = DateTime.Now,
RaceEntryDetails = raceEntryDetails RacesEntryDetails = racesEntryDetails
}; };
} }
public static RaceEntries CreateOpeartion(TempRaceEntryDetails tempRaceEntryDetails,
IEnumerable<RaceEntryDetails> racesEntryDetails)
{
return new RaceEntries
{
Id = tempRaceEntryDetails.Id,
JockeyId = tempRaceEntryDetails.JockeyId,
DateReceipt = tempRaceEntryDetails.DateReceipt,
RacesEntryDetails = racesEntryDetails
};
}
} }

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHorseRacingOrg.Entities;
public class TempRaceEntryDetails
{
public int Id { get; private set; }
public int JockeyId { get; private set; }
public DateTime DateReceipt { get; private set; }
public int RaceId { get; private set; }
public int Count { get; private set; }
}

View File

@ -70,7 +70,8 @@ namespace ProjectHorseRacingOrg.Forms
Convert.ToInt32(row.Cells["ColumnRace"].Value), Convert.ToInt32(row.Cells["ColumnRace"].Value),
Convert.ToInt32(row.Cells["ColumnCount"].Value))); Convert.ToInt32(row.Cells["ColumnCount"].Value)));
} }
return list; return list.GroupBy(x => x.RaceId, x => x.Count, (id, counts) =>
RaceEntryDetails.CreateElement(0, id, counts.Sum())).ToList();
} }
} }

View File

@ -0,0 +1,163 @@
namespace ProjectHorseRacingOrg.Forms
{
partial class FormRaceReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dateTimePickerDateBegin = new DateTimePicker();
dateTimePickerDateEnd = new DateTimePicker();
ButtonMakeReport = new Button();
labelWay = new Label();
labelRace = new Label();
labelBegin = new Label();
labelEnd = new Label();
buttonSelectFilePath = new Button();
textBoxFilePath = new TextBox();
comboBoxRace = new ComboBox();
SuspendLayout();
//
// dateTimePickerDateBegin
//
dateTimePickerDateBegin.Location = new Point(164, 159);
dateTimePickerDateBegin.Name = "dateTimePickerDateBegin";
dateTimePickerDateBegin.Size = new Size(262, 27);
dateTimePickerDateBegin.TabIndex = 0;
//
// dateTimePickerDateEnd
//
dateTimePickerDateEnd.Location = new Point(164, 214);
dateTimePickerDateEnd.Name = "dateTimePickerDateEnd";
dateTimePickerDateEnd.Size = new Size(262, 27);
dateTimePickerDateEnd.TabIndex = 1;
//
// ButtonMakeReport
//
ButtonMakeReport.Location = new Point(164, 270);
ButtonMakeReport.Name = "ButtonMakeReport";
ButtonMakeReport.Size = new Size(136, 29);
ButtonMakeReport.TabIndex = 2;
ButtonMakeReport.Text = "Сформировать";
ButtonMakeReport.UseVisualStyleBackColor = true;
ButtonMakeReport.Click += ButtonMakeReport_Click;
//
// labelWay
//
labelWay.AutoSize = true;
labelWay.Location = new Point(37, 36);
labelWay.Name = "labelWay";
labelWay.Size = new Size(112, 20);
labelWay.TabIndex = 3;
labelWay.Text = "Путь до файла:";
//
// labelRace
//
labelRace.AutoSize = true;
labelRace.Location = new Point(37, 98);
labelRace.Name = "labelRace";
labelRace.Size = new Size(115, 20);
labelRace.TabIndex = 4;
labelRace.Text = "Соревнование:";
//
// labelBegin
//
labelBegin.AutoSize = true;
labelBegin.Location = new Point(37, 159);
labelBegin.Name = "labelBegin";
labelBegin.Size = new Size(97, 20);
labelBegin.TabIndex = 5;
labelBegin.Text = "Дата начала:";
//
// labelEnd
//
labelEnd.AutoSize = true;
labelEnd.Location = new Point(37, 219);
labelEnd.Name = "labelEnd";
labelEnd.Size = new Size(90, 20);
labelEnd.TabIndex = 6;
labelEnd.Text = "Дата конца:";
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(390, 31);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(36, 29);
buttonSelectFilePath.TabIndex = 7;
buttonSelectFilePath.Text = "..";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(164, 33);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(220, 27);
textBoxFilePath.TabIndex = 8;
//
// comboBoxRace
//
comboBoxRace.FormattingEnabled = true;
comboBoxRace.Location = new Point(164, 95);
comboBoxRace.Name = "comboBoxRace";
comboBoxRace.Size = new Size(262, 28);
comboBoxRace.TabIndex = 9;
//
// FormRaceReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(475, 322);
Controls.Add(comboBoxRace);
Controls.Add(textBoxFilePath);
Controls.Add(buttonSelectFilePath);
Controls.Add(labelEnd);
Controls.Add(labelBegin);
Controls.Add(labelRace);
Controls.Add(labelWay);
Controls.Add(ButtonMakeReport);
Controls.Add(dateTimePickerDateEnd);
Controls.Add(dateTimePickerDateBegin);
Name = "FormRaceReport";
Text = "FormRaceReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerDateBegin;
private DateTimePicker dateTimePickerDateEnd;
private Button ButtonMakeReport;
private Label labelWay;
private Label labelRace;
private Label labelBegin;
private Label labelEnd;
private Button buttonSelectFilePath;
private TextBox textBoxFilePath;
private ComboBox comboBoxRace;
}
}

View File

@ -0,0 +1,88 @@
using ProjectHorseRacingOrg.Reports;
using ProjectHorseRacingOrg.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Unity;
namespace ProjectHorseRacingOrg.Forms
{
public partial class FormRaceReport : Form
{
private readonly IUnityContainer _container;
public FormRaceReport(IUnityContainer container, IRaceRepository raceRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxRace.DataSource = raceRepository.ReadRaces();
comboBoxRace.DisplayMember = "Name";
comboBoxRace.ValueMember = "Id";
}
private void ButtonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxRace.SelectedIndex < 0)
{
throw new Exception("Не выбран корм");
}
if (dateTimePickerDateBegin.Value >=
dateTimePickerDateEnd.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if
(_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxRace.SelectedValue!,
dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,311 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHorseRacingOrg.Reports;
public class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header,
StyleIndex.SimpleTextWithoutBorder);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
}
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.SimpleTextWithoutBorder);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorder);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
Bold = new Bold(),
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
workbookStylesPart.Stylesheet.Append(fonts);
// Default Fill
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
// Default Border
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Medium },
RightBorder = new RightBorder() { Style = BorderStyleValues.Medium },
TopBorder = new TopBorder() { Style = BorderStyleValues.Medium },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Medium },
DiagonalBorder = new DiagonalBorder() { Style = BorderStyleValues.Medium },
});
workbookStylesPart.Stylesheet.Append(borders);
// Default cell format and a date cell format
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 1,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 2,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 3,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorder = 1,
BoldTextWithoutBorder = 2,
BoldTextWithBorder = 3,
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>().FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() +
columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}

View File

@ -0,0 +1,70 @@
using Microsoft.Extensions.Logging;
using ProjectHorseRacingOrg.Entities;
using ProjectHorseRacingOrg.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHorseRacingOrg.Reports;
internal class TableReport
{
private readonly IRaceEntriesRepository _raceEntriesRepository;
private readonly IRacingHorsesRepository _racingHorsesRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Жокей", "Дата", "Количество пришло", "Количество ушло"];
public TableReport(IRaceEntriesRepository raceEntriesRepositor,
IRacingHorsesRepository racingHorsesRepository,
ILogger<TableReport> logger)
{
_raceEntriesRepository = raceEntriesRepositor ?? throw new ArgumentNullException(nameof(raceEntriesRepositor));
_racingHorsesRepository = racingHorsesRepository ?? throw new ArgumentNullException(nameof(racingHorsesRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int raceId, DateTime startDate,
DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по движению соревнований", 0, 4)
.AddParagraph("за период", 0)
.AddTable([10, 10, 15, 15], GetData(raceId, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int raceId, DateTime startDate, DateTime endDate)
{
var data = _raceEntriesRepository
.ReadRaceEntries()
.Where(x => x.DateReceipt >= startDate && x.DateReceipt <= endDate && x.RacesEntryDetails.Any(y => y.RaceId == raceId))
.Select(x => new { x.JockeyId, Date = x.DateReceipt, CountIn = x.RacesEntryDetails.FirstOrDefault(y => y.RaceId == raceId)?.Count, CountOut = (int?)null })
.Union(
_racingHorsesRepository
.ReadRacingHorses()
.Where(x => x.RacingDate >= startDate && x.RacingDate <= endDate && x.RaceId == raceId)
.Select(x => new { x.JockeyId, Date = x.RacingDate, CountIn = (int?)null, CountOut = (int?)x.Result }))
.OrderBy(x => x.Date);
return
new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.JockeyId.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()]])
.ToList();
}
}

View File

@ -44,7 +44,7 @@ SELECT MAX(Id) FROM RaceEntries";
var querySubInsert = @" var querySubInsert = @"
INSERT INTO RaceEntryDetails (RaceEntryId, RaceId, Count) INSERT INTO RaceEntryDetails (RaceEntryId, RaceId, Count)
VALUES (@RaceEntryId,@RaceId, @Count)"; VALUES (@RaceEntryId,@RaceId, @Count)";
foreach (var elem in raceEntries.RaceEntryDetails) foreach (var elem in raceEntries.RacesEntryDetails)
{ {
connection.Execute(querySubInsert, new connection.Execute(querySubInsert, new
{ {
@ -88,20 +88,24 @@ WHERE Id=@id";
_logger.LogInformation("Получение всех объектов"); _logger.LogInformation("Получение всех объектов");
try try
{ {
using var connection = new using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
NpgsqlConnection(_connectionString.ConnectionString); var querySelect = @"
var querySelect = "SELECT * FROM RaceEntries"; SELECT fr.*, ffr.RaceId, ffr.Count FROM RaceEntries fr
var raceEntries = INNER JOIN RaceEntryDetails ffr ON ffr.RaceEntryId = fr.Id";
connection.Query<RaceEntries>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", var racesEntries = connection.Query<TempRaceEntryDetails>(querySelect);
JsonConvert.SerializeObject(raceEntries)); _logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(racesEntries));
return raceEntries;
return racesEntries.GroupBy(x => x.Id, y => y,
(key, value) =>
RaceEntries.CreateOpeartion(value.First(),
value.Select(z =>
RaceEntryDetails.CreateElement(0, z.RaceId, z.Count)))).ToList();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка при чтении объектов"); _logger.LogError(ex, "Ошибка при чтении объектов");
throw; throw;
} }
} }
} }