Работа с отчетами Word и Excel, изменение сущности Contract_Tour

This commit is contained in:
145Game 2024-12-09 12:27:50 +04:00
parent cddd698911
commit 1aab16e288
21 changed files with 1335 additions and 52 deletions

View File

@ -1,4 +1,6 @@

using Unity;
namespace Travel_Agency.Entities;
public class Contract
{
@ -25,4 +27,19 @@ public class Contract
Tours = tours
};
}
public static Contract CreateOperation(TempContract_Tour tempContract_Tour, IEnumerable<Contract_Tour> tours)
{
return new Contract
{
Id = tempContract_Tour.Id,
ContractNumber = tempContract_Tour.ContractNumber,
Discount = tempContract_Tour.Discount,
TouristNumber = tempContract_Tour.TouristNumber,
FinalPrice = tempContract_Tour.FinalPrice,
ClientId = tempContract_Tour.ClientId,
Date = tempContract_Tour.Date,
Tours = tours
};
}
}

View File

@ -2,18 +2,16 @@
namespace Travel_Agency.Entities;
public class Contract_Tour
{
public int ContractId { get; private set; }
public int Id { get; private set; }
public int TourId { get; private set; }
public string StartDate { get; private set; } = string.Empty;
public string EndDate { get; private set; } = string.Empty;
public static Contract_Tour CreateElement(int Contractid, int tourId, string startDate, string endDate)
public int CountOfStop { get; private set; }
public static Contract_Tour CreateElement(int Contractid, int tourId, int countOfStop)
{
return new Contract_Tour
{
ContractId = Contractid,
Id = Contractid,
TourId = tourId,
StartDate = startDate,
EndDate = endDate
CountOfStop = countOfStop
};
}
}

View File

@ -0,0 +1,15 @@

namespace Travel_Agency.Entities;
public class TempContract_Tour
{
public int Id { get; private set; }
public int ClientId { get; private set; }
public int ContractNumber { get; private set; }
public int Discount { get; private set; } = 0;
public int TouristNumber { get; private set; }
public int FinalPrice { get; private set; }
public DateTime Date { get; private set; }
public int TourId { get; private set; }
public int CountOfStop { get; private set; }
}

View File

@ -37,6 +37,8 @@
ContractToolStripMenuItem = new ToolStripMenuItem();
PaymentToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
TourAndPaymentReportToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
SuspendLayout();
//
@ -101,10 +103,27 @@
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, TourAndPaymentReportToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(73, 24);
отчётыToolStripMenuItem.Text = "Отчёты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
DirectoryReportToolStripMenuItem.Size = new Size(467, 26);
DirectoryReportToolStripMenuItem.Text = "Документ со справочниками";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// TourAndPaymentReportToolStripMenuItem
//
TourAndPaymentReportToolStripMenuItem.Name = "TourAndPaymentReportToolStripMenuItem";
TourAndPaymentReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
TourAndPaymentReportToolStripMenuItem.Size = new Size(467, 26);
TourAndPaymentReportToolStripMenuItem.Text = "Сводка по числу остановок и оплате договора";
TourAndPaymentReportToolStripMenuItem.Click += TourAndPaymentReportToolStripMenuItem_Click;
//
// FormTravel_Agency
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -134,5 +153,7 @@
private ToolStripMenuItem ContractToolStripMenuItem;
private ToolStripMenuItem PaymentToolStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem TourAndPaymentReportToolStripMenuItem;
}
}

View File

@ -78,5 +78,31 @@ namespace Travel_Agency
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void TourAndPaymentReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormTourAndPaymentReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -43,8 +43,7 @@
groupBoxTour = new GroupBox();
dataGridViewTours = new DataGridView();
ColumnTour = new DataGridViewComboBoxColumn();
ColumnStartDate = new DataGridViewTextBoxColumn();
ColumEndDate = new DataGridViewTextBoxColumn();
ColumnCountOfStop = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)numericUpDownContractNumber).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownDiscount).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownTouristNumber).BeginInit();
@ -164,7 +163,7 @@
groupBoxTour.Controls.Add(dataGridViewTours);
groupBoxTour.Location = new Point(403, 33);
groupBoxTour.Name = "groupBoxTour";
groupBoxTour.Size = new Size(463, 428);
groupBoxTour.Size = new Size(332, 428);
groupBoxTour.TabIndex = 16;
groupBoxTour.TabStop = false;
groupBoxTour.Text = "Туры";
@ -174,7 +173,7 @@
dataGridViewTours.AllowUserToResizeColumns = false;
dataGridViewTours.AllowUserToResizeRows = false;
dataGridViewTours.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewTours.Columns.AddRange(new DataGridViewColumn[] { ColumnTour, ColumnStartDate, ColumEndDate });
dataGridViewTours.Columns.AddRange(new DataGridViewColumn[] { ColumnTour, ColumnCountOfStop });
dataGridViewTours.Dock = DockStyle.Fill;
dataGridViewTours.Location = new Point(3, 23);
dataGridViewTours.MultiSelect = false;
@ -182,7 +181,7 @@
dataGridViewTours.RowHeadersVisible = false;
dataGridViewTours.RowHeadersWidth = 51;
dataGridViewTours.RowTemplate.Height = 29;
dataGridViewTours.Size = new Size(457, 402);
dataGridViewTours.Size = new Size(326, 402);
dataGridViewTours.StandardTab = true;
dataGridViewTours.TabIndex = 0;
//
@ -193,26 +192,19 @@
ColumnTour.Name = "ColumnTour";
ColumnTour.Width = 200;
//
// ColumnStartDate
// ColumnCountOfStop
//
ColumnStartDate.HeaderText = "Дата начала путишествия";
ColumnStartDate.MinimumWidth = 6;
ColumnStartDate.Name = "ColumnStartDate";
ColumnStartDate.Resizable = DataGridViewTriState.True;
ColumnStartDate.Width = 125;
//
// ColumEndDate
//
ColumEndDate.HeaderText = "Дата конца путешествия";
ColumEndDate.MinimumWidth = 6;
ColumEndDate.Name = "ColumEndDate";
ColumEndDate.Width = 125;
ColumnCountOfStop.HeaderText = "Число остановок";
ColumnCountOfStop.MinimumWidth = 6;
ColumnCountOfStop.Name = "ColumnCountOfStop";
ColumnCountOfStop.Resizable = DataGridViewTriState.True;
ColumnCountOfStop.Width = 125;
//
// FormContract
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(897, 496);
ClientSize = new Size(766, 496);
Controls.Add(groupBoxTour);
Controls.Add(numericUpDownFinalPrice);
Controls.Add(numericUpDownTouristNumber);
@ -256,7 +248,6 @@
private GroupBox groupBoxTour;
private DataGridView dataGridViewTours;
private DataGridViewComboBoxColumn ColumnTour;
private DataGridViewTextBoxColumn ColumnStartDate;
private DataGridViewTextBoxColumn ColumEndDate;
private DataGridViewTextBoxColumn ColumnCountOfStop;
}
}

View File

@ -47,6 +47,7 @@ namespace Travel_Agency.Forms
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<Contract_Tour> CreateListContract_TourFromDataGrid()
{
var list = new List<Contract_Tour>();
@ -58,11 +59,11 @@ namespace Travel_Agency.Forms
}
list.Add(Contract_Tour.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnTour"].Value),
row.Cells["ColumnStartDate"].Value.ToString(),
row.Cells["ColumEndDate"].Value.ToString()
));
Convert.ToInt32(row.Cells["ColumnCountOfStop"].Value
)));
}
return list;
return list.GroupBy(x => x.TourId, x => x.CountOfStop, (id, counts) =>
Contract_Tour.CreateElement(0, id, counts.Sum())).ToList();
}
}
}

View File

@ -120,10 +120,7 @@
<metadata name="ColumnTour.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnStartDate.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumEndDate.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<metadata name="ColumnCountOfStop.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,99 @@
namespace Travel_Agency.Forms
{
partial class FormDirectoryReport
{
/// <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()
{
checkBoxClients = new CheckBox();
checkBoxTours = new CheckBox();
checkBoxRoutes = new CheckBox();
ButtonCreate = new Button();
SuspendLayout();
//
// checkBoxClients
//
checkBoxClients.AutoSize = true;
checkBoxClients.Location = new Point(34, 41);
checkBoxClients.Name = "checkBoxClients";
checkBoxClients.Size = new Size(91, 24);
checkBoxClients.TabIndex = 0;
checkBoxClients.Text = "Клиенты";
checkBoxClients.UseVisualStyleBackColor = true;
//
// checkBoxTours
//
checkBoxTours.AutoSize = true;
checkBoxTours.Location = new Point(34, 93);
checkBoxTours.Name = "checkBoxTours";
checkBoxTours.Size = new Size(66, 24);
checkBoxTours.TabIndex = 1;
checkBoxTours.Text = "Туры";
checkBoxTours.UseVisualStyleBackColor = true;
//
// checkBoxRoutes
//
checkBoxRoutes.AutoSize = true;
checkBoxRoutes.Location = new Point(34, 152);
checkBoxRoutes.Name = "checkBoxRoutes";
checkBoxRoutes.Size = new Size(106, 24);
checkBoxRoutes.TabIndex = 2;
checkBoxRoutes.Text = "Маршруты";
checkBoxRoutes.UseVisualStyleBackColor = true;
//
// ButtonCreate
//
ButtonCreate.Location = new Point(210, 83);
ButtonCreate.Name = "ButtonCreate";
ButtonCreate.Size = new Size(127, 43);
ButtonCreate.TabIndex = 3;
ButtonCreate.Text = "Сформировать";
ButtonCreate.UseVisualStyleBackColor = true;
ButtonCreate.Click += ButtonCreate_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(409, 228);
Controls.Add(ButtonCreate);
Controls.Add(checkBoxRoutes);
Controls.Add(checkBoxTours);
Controls.Add(checkBoxClients);
Name = "FormDirectoryReport";
Text = "FormDirectoryReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxClients;
private CheckBox checkBoxTours;
private CheckBox checkBoxRoutes;
private Button ButtonCreate;
}
}

View File

@ -0,0 +1,50 @@
using Travel_Agency.Reports;
using Unity;
namespace Travel_Agency.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxClients.Checked && !checkBoxTours.Checked && !checkBoxRoutes.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if (_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxClients.Checked,
checkBoxTours.Checked, checkBoxRoutes.Checked))
{
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

@ -27,8 +27,9 @@ namespace Travel_Agency.Forms
throw new Exception("Имеются незаполненные поля");
}
_paymentRepository.CreatePayment(Payment.CreateOperation(0,
(int)comboBoxClient.SelectedValue!,
Convert.ToInt32(numericUpDownSum.Value)));
Convert.ToInt32(numericUpDownSum.Value),
(int)comboBoxClient.SelectedValue!));
Close();
}
catch (Exception ex)

View File

@ -0,0 +1,186 @@
namespace Travel_Agency.Forms
{
partial class FormTourAndPaymentReport
{
/// <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()
{
labelPath = new Label();
textBoxFilePath = new TextBox();
ButtonSelectFilePath = new Button();
ButtonCreate = new Button();
labelClient = new Label();
labelStartDate = new Label();
labelEndDate = new Label();
dateTimePickerStartDate = new DateTimePicker();
dateTimePickerEndDate = new DateTimePicker();
labelTour = new Label();
comboBoxClient = new ComboBox();
comboBoxTour = new ComboBox();
SuspendLayout();
//
// labelPath
//
labelPath.AutoSize = true;
labelPath.Location = new Point(32, 27);
labelPath.Name = "labelPath";
labelPath.Size = new Size(112, 20);
labelPath.TabIndex = 0;
labelPath.Text = "Путь до файла:";
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(158, 24);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(214, 27);
textBoxFilePath.TabIndex = 1;
//
// ButtonSelectFilePath
//
ButtonSelectFilePath.Location = new Point(378, 22);
ButtonSelectFilePath.Name = "ButtonSelectFilePath";
ButtonSelectFilePath.Size = new Size(30, 29);
ButtonSelectFilePath.TabIndex = 2;
ButtonSelectFilePath.Text = "..";
ButtonSelectFilePath.UseVisualStyleBackColor = true;
ButtonSelectFilePath.Click += ButtonSelectFilePath_Click;
//
// ButtonCreate
//
ButtonCreate.Location = new Point(158, 305);
ButtonCreate.Name = "ButtonCreate";
ButtonCreate.Size = new Size(124, 29);
ButtonCreate.TabIndex = 3;
ButtonCreate.Text = "Сформировать";
ButtonCreate.UseVisualStyleBackColor = true;
ButtonCreate.Click += ButtonCreate_Click;
//
// labelClient
//
labelClient.AutoSize = true;
labelClient.Location = new Point(32, 77);
labelClient.Name = "labelClient";
labelClient.Size = new Size(61, 20);
labelClient.TabIndex = 4;
labelClient.Text = "Клиент:";
//
// labelStartDate
//
labelStartDate.AutoSize = true;
labelStartDate.Location = new Point(32, 196);
labelStartDate.Name = "labelStartDate";
labelStartDate.Size = new Size(97, 20);
labelStartDate.TabIndex = 5;
labelStartDate.Text = "Дата начала:";
//
// labelEndDate
//
labelEndDate.AutoSize = true;
labelEndDate.Location = new Point(32, 240);
labelEndDate.Name = "labelEndDate";
labelEndDate.Size = new Size(90, 20);
labelEndDate.TabIndex = 6;
labelEndDate.Text = "Дата конца:";
//
// dateTimePickerStartDate
//
dateTimePickerStartDate.Location = new Point(158, 191);
dateTimePickerStartDate.Name = "dateTimePickerStartDate";
dateTimePickerStartDate.Size = new Size(250, 27);
dateTimePickerStartDate.TabIndex = 7;
//
// dateTimePickerEndDate
//
dateTimePickerEndDate.Location = new Point(158, 235);
dateTimePickerEndDate.Name = "dateTimePickerEndDate";
dateTimePickerEndDate.Size = new Size(250, 27);
dateTimePickerEndDate.TabIndex = 8;
//
// labelTour
//
labelTour.AutoSize = true;
labelTour.Location = new Point(32, 138);
labelTour.Name = "labelTour";
labelTour.Size = new Size(36, 20);
labelTour.TabIndex = 9;
labelTour.Text = "Тур:";
//
// comboBoxClient
//
comboBoxClient.FormattingEnabled = true;
comboBoxClient.Location = new Point(158, 74);
comboBoxClient.Name = "comboBoxClient";
comboBoxClient.Size = new Size(250, 28);
comboBoxClient.TabIndex = 10;
//
// comboBoxTour
//
comboBoxTour.FormattingEnabled = true;
comboBoxTour.Location = new Point(158, 135);
comboBoxTour.Name = "comboBoxTour";
comboBoxTour.Size = new Size(250, 28);
comboBoxTour.TabIndex = 11;
//
// FormTourAndPaymentReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(462, 352);
Controls.Add(comboBoxTour);
Controls.Add(comboBoxClient);
Controls.Add(labelTour);
Controls.Add(dateTimePickerEndDate);
Controls.Add(dateTimePickerStartDate);
Controls.Add(labelEndDate);
Controls.Add(labelStartDate);
Controls.Add(labelClient);
Controls.Add(ButtonCreate);
Controls.Add(ButtonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(labelPath);
Name = "FormTourAndPaymentReport";
Text = "FormTourAndPaymentReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelPath;
private TextBox textBoxFilePath;
private Button ButtonSelectFilePath;
private Button ButtonCreate;
private Label labelClient;
private Label labelStartDate;
private Label labelEndDate;
private DateTimePicker dateTimePickerStartDate;
private DateTimePicker dateTimePickerEndDate;
private Label labelTour;
private ComboBox comboBoxClient;
private ComboBox comboBoxTour;
}
}

View File

@ -0,0 +1,92 @@
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 Travel_Agency.Reports;
using Travel_Agency.Repositories;
using Unity;
namespace Travel_Agency.Forms
{
public partial class FormTourAndPaymentReport : Form
{
private readonly IUnityContainer _container;
public FormTourAndPaymentReport(IUnityContainer container, ITourRepository tourRepository, IClientRepository clientRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxClient.DataSource = clientRepository.ReadClients();
comboBoxClient.DisplayMember = "Name";
comboBoxClient.ValueMember = "Id";
comboBoxTour.DataSource = tourRepository.ReadTours();
comboBoxTour.DisplayMember = "Name";
comboBoxTour.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 ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxClient.SelectedIndex < 0)
{
throw new Exception("Не выбран клиент");
}
if (comboBoxTour.SelectedIndex < 0)
{
throw new Exception("Не выбран тур");
}
if (dateTimePickerEndDate.Value <=
dateTimePickerStartDate.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if
(_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxClient.SelectedValue!, (int)comboBoxTour.SelectedValue!,
dateTimePickerStartDate.Value, dateTimePickerEndDate.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,82 @@

using Microsoft.Extensions.Logging;
using Travel_Agency.Repositories;
namespace Travel_Agency.Reports;
public class DocReport
{
private readonly IClientRepository _clientRepository;
private readonly IRouteRepository _routeRepository;
private readonly ITourRepository _tourRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IClientRepository clientRepository, IRouteRepository routeRepository,
ITourRepository tourRepository, ILogger<DocReport> logger)
{
_clientRepository = clientRepository ?? throw new ArgumentNullException(nameof(clientRepository));
_tourRepository = tourRepository ?? throw new ArgumentNullException(nameof(tourRepository));
_routeRepository = routeRepository ?? throw new ArgumentNullException(nameof(routeRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeClients, bool includeTours, bool includeRoutes)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (includeClients)
{
builder.AddParagraph("Клиенты").AddTable([2400, 2400, 2400], GetClients());
}
if (includeTours)
{
builder.AddParagraph("Туры").AddTable([2400, 2400, 2400], GetTours());
}
if (includeRoutes)
{
builder.AddParagraph("Маршруты").AddTable([1200, 1200, 2400, 1200, 1200], GetRoutes());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetClients()
{
return [
["ФИО клиента", "Паспортные данные", "позиция в обществе"],
.. _clientRepository
.ReadClients()
.Select(x => new string[] { x.Name, x.PassportDetails, x.PositionInSociety.ToString() }),
];
}
private List<string[]> GetTours()
{
return [
["Название", "Тип тура", "Цена"],
.. _tourRepository
.ReadTours()
.Select(x => new string[] { x.Name, x.TypeOfTour.ToString(), x.Price.ToString() }),
];
}
private List<string[]> GetRoutes()
{
return [
["Название", "Рейтинг в %", "Места посещения", "Цена", "Тур"],
.. _routeRepository
.ReadRoutes()
.Select(x => new string[] { x.Name, x.Rating.ToString(), x.Places, x.Price.ToString(), x.TourId.ToString() }),
];
}
}

View File

@ -0,0 +1,310 @@

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace Travel_Agency.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.BoldTextWithoutBorder);
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.BoldTextWithBorder);
}
_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" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold() { Val = true }
});
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.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder()
});
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 = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Right,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
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,61 @@
using Microsoft.Extensions.Logging;
using Travel_Agency.Entities;
using Travel_Agency.Repositories;
namespace Travel_Agency.Reports;
public class TableReport
{
private readonly IContractRepository _contractRepository;
private readonly IPaymentRepository _paymentRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Клиент", "Дата", "Число остановок", "Оплата договора"];
public TableReport(IContractRepository contractRepository, IPaymentRepository paymentRepository,
ILogger<TableReport> logger)
{
_contractRepository = contractRepository ?? throw new ArgumentNullException(nameof(contractRepository));
_paymentRepository = paymentRepository ?? throw new ArgumentNullException(nameof(paymentRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int clientId, int tourId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по числу остановок и оплате договора", 0, 4)
.AddParagraph("за период", 0)
.AddTable([10, 10, 10, 10], GetData(clientId, tourId, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int clientId, int tourId, DateTime startDate, DateTime endDate)
{
var data = _contractRepository
.ReadContracts()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.Tours.Any(y => y.TourId == tourId))
.Select(x => new { x.ClientId, Date = x.Date, CountOfStop = x.Tours.FirstOrDefault(y => y.TourId == tourId)?.CountOfStop, Payment = (int?)null})
.Union(
_paymentRepository
.ReadPayments()
.Where(x => x.Date >= startDate && x.Date <= endDate && x.ClientId == clientId)
.Select(x => new {x.ClientId, x.Date, CountOfStop = (int?)null, Payment = (int?)x.Sum }))
.OrderBy(x => x.Date);
return
new List<string[]>() { item }
.Union(
data
.Select(x => new string[] { x.ClientId.ToString(), x.Date.ToString(), x.CountOfStop?.ToString() ?? string.Empty, x.Payment?.ToString() ?? string.Empty }))
.Union(
[["Всего ", "", data.Sum(x => x.CountOfStop ?? 0).ToString(), data.Sum(x => x.Payment ?? 0).ToString()]])
.ToList();
}
}

View File

@ -0,0 +1,94 @@

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Travel_Agency.Reports;
public class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
// TODO прописать настройки под жирный текст
run.PrependChild(new RunProperties());
run.RunProperties.AddChild(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 })));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x => new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath,
WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}

View File

@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Travel_Agency.Entities;
using Unity;
namespace Travel_Agency.Repositories.Implementations;
@ -30,17 +31,16 @@ public class ContractRepository : IContractRepository
VALUES (@ContractNumber, @Discount,
@TouristNumber, @FinalPrice, @ClientId, @Date);
SELECT MAX(Id) FROM CONTRACT";
var contractId = connection.QueryFirst<int>(queryInsert, contract, transaction);
var querySubInsert = @"INSERT INTO CONTRACT_TOUR (ContractId, TourId, StartDate, EndDate)
VALUES (@ContractId, @TourId, @StartDate, @EndDate)";
var Id = connection.QueryFirst<int>(queryInsert, contract, transaction);
var querySubInsert = @"INSERT INTO CONTRACT_TOUR (Id, TourId, CountOfStop)
VALUES (@Id, @TourId, @CountOfStop)";
foreach (var elem in contract.Tours)
{
connection.Execute(querySubInsert, new
{
contractId,
Id,
elem.TourId,
elem.StartDate,
elem.EndDate
elem.CountOfStop
}, transaction);
}
transaction.Commit();
@ -78,11 +78,13 @@ public class ContractRepository : IContractRepository
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM CONTRACT";
var contracts = connection.Query<Contract>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(contracts));
return contracts;
var querySelect = @"SELECT inv.*, ipr.TourId, ipr.CountOfStop FROM CONTRACT inv
INNER JOIN CONTRACT_TOUR ipr ON ipr.Id = inv.Id";
var contracts = connection.Query<TempContract_Tour>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(contracts));
return contracts.GroupBy(x => x.Id, y => y,
(key, value) => Contract.CreateOperation(value.First(),
value.Select(z => Contract_Tour.CreateElement(0, z.TourId, z.CountOfStop)))).ToList();
}
catch (Exception ex)
{

View File

@ -11,9 +11,9 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />