Устранение конфликта.

This commit is contained in:
Programmist73 2023-04-20 00:13:18 +04:00
commit fdfc94016f
33 changed files with 1224 additions and 1000 deletions

View File

@ -1,33 +1,33 @@
namespace BlacksmithWorkshop
{
partial class FormReportManufactureWorkPieces
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormReportManufactureWorkPieces
{
/// <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);
}
/// <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
#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()
{
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonSaveToExcel = new Button();
ColumnManufacture = new DataGridViewTextBoxColumn();
@ -35,9 +35,9 @@
ColumnCount = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
//
// dataGridView
//
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
@ -56,9 +56,9 @@
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(704, 680);
dataGridView.TabIndex = 0;
//
//
// buttonSaveToExcel
//
//
buttonSaveToExcel.Location = new Point(16, 18);
buttonSaveToExcel.Margin = new Padding(4, 5, 4, 5);
buttonSaveToExcel.Name = "buttonSaveToExcel";
@ -67,33 +67,33 @@
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
//
// ColumnManufacture
//
//
ColumnManufacture.HeaderText = "Изделие";
ColumnManufacture.MinimumWidth = 6;
ColumnManufacture.Name = "ColumnManufacture";
ColumnManufacture.ReadOnly = true;
ColumnManufacture.Width = 200;
//
//
// ColumnWorkPiece
//
//
ColumnWorkPiece.HeaderText = "Заготовка";
ColumnWorkPiece.MinimumWidth = 6;
ColumnWorkPiece.Name = "ColumnWorkPiece";
ColumnWorkPiece.ReadOnly = true;
ColumnWorkPiece.Width = 200;
//
// ColumnCount
//
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
ColumnCount.Width = 125;
//
// FormReportManufactureWorkPieces
//
//
// FormReportManufactureWorkPieces
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(704, 743);
@ -105,14 +105,16 @@
Load += FormReportManufactureWorkPieces_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
}
#endregion
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumnManufacture;
private Button buttonSaveToExcel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumWorkPiece;
private DataGridViewTextBoxColumn ColumnManufacture;
private DataGridViewTextBoxColumn ColumnWorkPiece;
private DataGridViewTextBoxColumn ColumnCount;
}
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -13,82 +13,82 @@ using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormReportManufactureWorkPieces : Form
{
private readonly ILogger _logger;
public partial class FormReportManufactureWorkPieces : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
private readonly IReportLogic _logic;
public FormReportManufactureWorkPieces(ILogger<FormReportManufactureWorkPieces> logger, IReportLogic logic)
{
InitializeComponent();
public FormReportManufactureWorkPieces(ILogger<FormReportManufactureWorkPieces> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
_logger = logger;
_logic = logic;
}
private void FormReportManufactureWorkPieces_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetManufactureWorkPiece();
private void FormReportManufactureWorkPieces_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetManufactureWorkPiece();
if (dict != null)
{
dataGridView.Rows.Clear();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ManufactureName, "", "" });
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ManufactureName, "", "" });
foreach (var listElem in elem.WorkPieces)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
foreach (var listElem in elem.WorkPieces)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка изделий по заготовкам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий по заготовкам");
_logger.LogInformation("Загрузка списка изделий по заготовкам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий по заготовкам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
//фильтрация файлов для диалогового окна
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
//фильтрация файлов для диалогового окна
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveManufactureWorkPieceToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveManufactureWorkPieceToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Сохранение списка изделий по заготовкам");
_logger.LogInformation("Сохранение списка изделий по заготовкам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка изделий по заготовкам");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка изделий по заготовкам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -57,4 +57,22 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ColumWorkPiece.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnManufacture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumWorkPiece.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnManufacture.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -1,91 +1,95 @@
namespace BlacksmithWorkshop
{
partial class FormReportOrders
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormReportOrders
{
/// <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);
}
/// <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
#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()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonToPdf = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker();
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonToPdf = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.dateTimePickerTo = new System.Windows.Forms.DateTimePicker();
this.labelTo = new System.Windows.Forms.Label();
this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker();
this.dateTimePickerFrom = new System.Windows.Forms.DateTimePicker();
this.labelFrom = new System.Windows.Forms.Label();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
this.panel.Controls.Add(this.dateTimePickerTo);
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
this.panel.Controls.Add(this.label2);
this.panel.Controls.Add(this.label1);
this.panel.Controls.Add(this.dateTimePickerTo);
this.panel.Controls.Add(this.labelTo);
this.panel.Controls.Add(this.dateTimePickerFrom);
this.panel.Controls.Add(this.dateTimePickerFrom);
this.panel.Controls.Add(this.labelFrom);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Dock = System.Windows.Forms.DockStyle.Top;
this.panel.Location = new System.Drawing.Point(0, 0);
this.panel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.panel.Name = "panel";
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(1031, 40);
this.panel.TabIndex = 0;
//
// buttonToPdf
//
this.panel.TabIndex = 0;
//
// buttonToPdf
//
this.buttonToPdf.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonToPdf.Location = new System.Drawing.Point(878, 8);
this.buttonToPdf.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(139, 27);
this.buttonToPdf.TabIndex = 5;
this.buttonToPdf.Text = "В Pdf";
this.buttonToPdf.UseVisualStyleBackColor = true;
this.buttonToPdf.Click += new System.EventHandler(this.ButtonToPdf_Click);
//
// buttonMake
//
this.buttonToPdf.TabIndex = 5;
this.buttonToPdf.Text = "В Pdf";
this.buttonToPdf.UseVisualStyleBackColor = true;
this.buttonToPdf.Click += new System.EventHandler(this.ButtonToPdf_Click);
//
// buttonMake
//
this.buttonMake.Location = new System.Drawing.Point(476, 8);
this.buttonMake.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(139, 27);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
// dateTimePickerTo
//
//
this.dateTimePickerTo.Location = new System.Drawing.Point(237, 7);
this.dateTimePickerTo.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.dateTimePickerTo.Name = "dateTimePickerTo";
this.dateTimePickerTo.Size = new System.Drawing.Size(163, 23);
this.dateTimePickerTo.TabIndex = 3;
//
//
// labelTo
//
//
this.labelTo.AutoSize = true;
this.labelTo.Location = new System.Drawing.Point(208, 10);
this.labelTo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
@ -93,12 +97,12 @@
this.labelTo.Size = new System.Drawing.Size(21, 15);
this.labelTo.TabIndex = 2;
this.labelTo.Text = "по";
//
// dateTimePickerFrom
//
//
// dateTimePickerFrom
//
this.dateTimePickerFrom.Location = new System.Drawing.Point(37, 7);
this.dateTimePickerFrom.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.dateTimePickerFrom.Name = "dateTimePickerFrom";
this.dateTimePickerFrom.Name = "dateTimePickerFrom";
this.dateTimePickerFrom.Size = new System.Drawing.Size(163, 23);
this.dateTimePickerFrom.TabIndex = 1;
//
@ -111,31 +115,33 @@
this.labelFrom.Size = new System.Drawing.Size(15, 15);
this.labelFrom.TabIndex = 0;
this.labelFrom.Text = "С";
//
// FormReportOrders
//
//
// FormReportOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1031, 647);
this.Controls.Add(this.panel);
this.Controls.Add(this.panel);
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "FormReportOrders";
this.Name = "FormReportOrders";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Заказы";
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
this.ResumeLayout(false);
this.Text = "Заказы";
this.panel.ResumeLayout(false);
this.panel.PerformLayout();
this.ResumeLayout(false);
}
}
#endregion
#endregion
private Panel panel;
private Panel panel;
private Button buttonToPdf;
private Button buttonMake;
private DateTimePicker dateTimePickerTo;
private Button buttonMake;
private Label label2;
private Label label1;
private DateTimePicker dateTimePickerTo;
private Label labelTo;
private DateTimePicker dateTimePickerFrom;
private DateTimePicker dateTimePickerFrom;
private Label labelFrom;
}
}
}

View File

@ -14,98 +14,102 @@ using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormReportOrders : Form
{
private readonly ReportViewer reportViewer;
//форма с отчётом
public partial class FormReportOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
private readonly IReportLogic _logic;
public FormReportOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
public FormReportOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\PIbd-21_Eliseev_E.E._BlacksmithWorkshop\\BlacksmithWorkshop\\BlacksmithWorkshop\\ReportOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\Programmist73\\Desktop\\Практика\\2-й курс\\4-й семестр\\PIbd-21_Eliseev_E.E._BlacksmithWorkshop\\BlacksmithWorkshop\\BlacksmithWorkshop\\ReportOrders.rdlc", FileMode.Open));
private void ButtonMake_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var dataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
return;
}
try
{
var dataSource = _logic.GetOrders(new ReportBindingModel
{
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
var source = new ReportDataSource("DataSetOrders", dataSource);
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
var parameters = new[] { new ReportParameter("ReportParameterPeriod",
$"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters);
$"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") };
reportViewer.LocalReport.SetParameters(parameters);
reportViewer.RefreshReport();
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date)
{
MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
DateFrom = dateTimePickerFrom.Value,
DateTo = dateTimePickerTo.Value
});
_logger.LogInformation("Сохранение списка заказов на период {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString());
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<root>
<!--
Microsoft ResX Schema

View File

@ -235,7 +235,7 @@
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
@ -426,7 +426,7 @@
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Sum">
<CanGrow>true</CanGrow>

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using BlacksmithWorkshopBusinessLogic.OfficePackage;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
@ -13,59 +14,60 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class ReportLogic : IReportLogic
{
private readonly IManufactureStorage _manufactureStorage;
//Реализация бизнес-логики отчётов
public class ReportLogic : IReportLogic
{
private readonly IManufactureStorage _manufactureStorage;
private readonly IOrderStorage _orderStorage;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IManufactureStorage manufactureStorage, IOrderStorage orderStorage, IShopStorage shopStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_manufactureStorage = manufactureStorage;
_orderStorage = orderStorage;
{
_manufactureStorage = manufactureStorage;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
//Получение списка заготовок с указанием, в каких изделиях используются
public List<ReportManufactureWorkPieceViewModel> GetManufactureWorkPiece()
{
var manufactures = _manufactureStorage.GetFullList();
public List<ReportManufactureWorkPieceViewModel> GetManufactureWorkPiece()
{
var manufactures = _manufactureStorage.GetFullList();
var list = new List<ReportManufactureWorkPieceViewModel>();
var list = new List<ReportManufactureWorkPieceViewModel>();
foreach (var manufacture in manufactures)
{
var record = new ReportManufactureWorkPieceViewModel
{
ManufactureName = manufacture.ManufactureName,
WorkPieces = new List<(string, int)>(),
TotalCount = 0
};
foreach (var manufacture in manufactures)
{
var record = new ReportManufactureWorkPieceViewModel
{
ManufactureName = manufacture.ManufactureName,
WorkPieces = new List<(string, int)>(),
TotalCount = 0
};
foreach (var workPiece in manufacture.ManufactureWorkPieces)
{
foreach (var workPiece in manufacture.ManufactureWorkPieces)
{
record.WorkPieces.Add(new(workPiece.Value.Item1.WorkPieceName, workPiece.Value.Item2));
record.TotalCount += workPiece.Value.Item2;
}
record.TotalCount += workPiece.Value.Item2;
}
list.Add(record);
}
list.Add(record);
}
return list;
}
return list;
}
//Получение списка изделий с указанием, в каких магазинах в наличии
public List<ReportShopManufacturesViewModel> GetShopManufactures()
@ -95,20 +97,20 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
return list;
}
//Получение списка заказов за определенный период
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo })
.Select(x => new ReportOrdersViewModel
{
Id = x.Id,
DateCreate = x.DateCreate,
ManufactureName = x.ManufactureName,
Sum = x.Sum,
OrderStatus = x.Status.ToString()
})
.ToList();
}
//Получение списка заказов за определенный период
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo })
.Select(x => new ReportOrdersViewModel
{
Id = x.Id,
DateCreate = x.DateCreate,
ManufactureName = x.ManufactureName,
Sum = x.Sum,
OrderStatus = x.Status.ToString()
})
.ToList();
}
//Получение списка заказов за весь период
public List<ReportGroupedOrdersViewModel> GetGroupedOrders()
@ -125,15 +127,15 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
}
//Сохранение изделий в файл-Word
public void SaveManufacturesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список изделий",
Manufactures = _manufactureStorage.GetFullList()
});
}
public void SaveManufacturesToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список изделий",
Manufactures = _manufactureStorage.GetFullList()
});
}
//Сохранение магазинов в файл-Word
public void SaveShopsToWordFile(ReportBindingModel model)
@ -147,15 +149,15 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
}
//Сохранение изделий с указаеним заготовок в файл-Excel
public void SaveManufactureWorkPieceToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список заготовок",
ManufactureWorkPieces = GetManufactureWorkPiece()
});
}
public void SaveManufactureWorkPieceToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список заготовок",
ManufactureWorkPieces = GetManufactureWorkPiece()
});
}
//Сохранение магазинов с указанием изделий в файл-Excel
public void SaveShopManufacturesToExcelFile(ReportBindingModel model)
@ -168,18 +170,18 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
});
}
//Сохранение заказов в файл-Pdf
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetOrders(model)
});
}
//Сохранение заказов в файл-Pdf
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetOrders(model)
});
}
//Сохранение заказов за весь период в файл-Pdf
public void SaveGroupedOrdersToPdfFile(ReportBindingModel model)
@ -191,5 +193,5 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
GroupedOrders = GetGroupedOrders()
});
}
}
}
}

View File

@ -8,83 +8,83 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public abstract class AbstractSaveToExcel
{
//Создание отчета
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
public void CreateReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
uint rowIndex = 2;
foreach (var mwp in info.ManufactureWorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = mwp.ManufactureName,
StyleInfo = ExcelStyleInfoType.Text
});
foreach (var mwp in info.ManufactureWorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = mwp.ManufactureName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
rowIndex++;
foreach (var (WorkPiece, Count) in mwp.WorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = WorkPiece,
foreach (var (WorkPiece, Count) in mwp.WorkPieces)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = WorkPiece,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
});
rowIndex++;
}
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = mwp.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = mwp.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
rowIndex++;
}
SaveExcel(info);
}
SaveExcel(info);
}
public void CreateShopReport(ExcelInfo info)
{
@ -161,16 +161,16 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage
SaveExcel(info);
}
//Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info);
//Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info);
//Добавляем новую ячейку в лист
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
//Добавляем новую ячейку в лист
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
//Объединение ячеек
protected abstract void MergeCells(ExcelMergeParameters excelParams);
//Объединение ячеек
protected abstract void MergeCells(ExcelMergeParameters excelParams);
//Сохранение файла
protected abstract void SaveExcel(ExcelInfo info);
}
//Сохранение файла
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -8,11 +8,12 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
public abstract class AbstractSaveToPdf
{
//публичный метод создания документа. Описание методов ниже
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
@ -21,20 +22,20 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Статус заказа", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
{
CreateRow(new PdfRowParameters
{
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.ManufactureName, order.OrderStatus, order.Sum.ToString() },
Style = "Normal",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Rigth });
@ -50,41 +51,41 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage
CreateTable(new List<string> { "3cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата заказа", "Количество заказов", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.GroupedOrders)
{
CreateRow(new PdfRowParameters
{
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.DateCreate.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
SavePdf(info);
}
SavePdf(info);
}
//Создание doc-файла
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreatePdf(PdfInfo info);
//Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateParagraph(PdfParagraph paragraph);
//Создание таблицы
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateTable(List<string> columns);
//Создание и заполнение строки
protected abstract void CreateRow(PdfRowParameters rowParameters);
protected abstract void CreateRow(PdfRowParameters rowParameters);
//Сохранение файла
protected abstract void SavePdf(PdfInfo info);
}
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -8,35 +8,38 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info)
{
CreateWord(info);
public abstract class AbstractSaveToWord
{
//метод создания документа
public void CreateDoc(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
//создание ряда абзацев
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var manufacture in info.Manufactures)
{
CreateParagraph(new WordParagraph
{
//заполнение абзацев текстом
foreach (var manufacture in info.Manufactures)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (manufacture.ManufactureName + " ", new WordTextProperties { Bold = true, Size = "24" }),
(manufacture.Price.ToString(), new WordTextProperties { Size = "24" }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
(manufacture.Price.ToString(), new WordTextProperties { Size = "24" }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Both
}
});
}
SaveWord(info);
}
@ -87,19 +90,20 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage
}
});
SaveWord(info);
}
SaveWord(info);
}
//Создание doc-файла
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateWord(WordInfo info);
//Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void CreateParagraph(WordParagraph paragraph);
//Создание таблицы
protected abstract void CreateTable(WordParagraph paragraph);
//Сохранение файла
protected abstract void SaveWord(WordInfo info);
}
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -6,12 +6,15 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
//вспомогательное перечисление для оформления exel
public enum ExcelStyleInfoType
{
//заголовок
Title,
Text,
//просто текст
Text,
TextWithBorder
}
}
}

View File

@ -6,12 +6,16 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
//вспомогательное перечисление для оформления pdf документа
public enum PdfParagraphAlignmentType
{
//либо по центру
Center,
Left,
//либо с левого края
Left,
Rigth
}
//либо с правого края
Right
}
}

View File

@ -6,10 +6,13 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
//вспомогательное перечисление для настройки формата word документа
public enum WordJustificationType
{
//выравниваем либо по центру
Center,
Both
}
//либо на всю ширину
Both
}
}

View File

@ -7,16 +7,22 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class ExcelCellParameters
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
//информация по ячейке в таблице excel
public class ExcelCellParameters
{
//название колонки
public string ColumnName { get; set; } = string.Empty;
//строка
public uint RowIndex { get; set; }
//тект в ячейке
public string Text { get; set; } = string.Empty;
//геттер для того, чтобы не искать каждый раз
public string CellReference => $"{ColumnName}{RowIndex}";
//в каком стиле выводить информацию
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -7,11 +7,14 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
//информация по excel файлу, который хотим создать
public class ExcelInfo
{
//название файла
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
//заголовок
public string Title { get; set; } = string.Empty;
public List<ReportManufactureWorkPieceViewModel> ManufactureWorkPieces
{
@ -24,5 +27,5 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
get;
set;
} = new();
}
}
}

View File

@ -6,12 +6,14 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
//информация для объединения ячеек
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
//гетер для указания диапазона для объединения, чтобы каждый раз его не вычислять
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -7,18 +7,20 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
//общая информация по pdf файлу
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
//перечень заказов за указанный период для вывода/сохранения
public List<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportGroupedOrdersViewModel> GroupedOrders { get; set; } = new();
}
}
}

View File

@ -7,12 +7,14 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
//информация п параграфу в pdf документе
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
//информация по выравниванию текста в параграфе
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -7,12 +7,16 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
//информация по параметрам строк таблицы
public class PdfRowParameters
{
//набор текстов
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
//стиль к текстам
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
//как выравниваем
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -7,14 +7,16 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
//общая информация по документу
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ManufactureViewModel> Manufactures { get; set; } = new();
//список заготовок для вывода и сохранения
public List<ManufactureViewModel> Manufactures { get; set; } = new();
public List<ShopViewModel> Shops { get; set; } = new();
}
}
}

View File

@ -6,12 +6,15 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
//модель параграфов, которые есть в тексте
public class WordParagraph
{
//набор текстов в абзаце (для случая, если в абзаце текст разных стилей)
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
//свойства параграфа, если они есть
public WordTextProperties? TextProperties { get; set; }
public List<List<(string, WordTextProperties)>> RowTexts { get; set; } = new();
}
}
}

View File

@ -7,12 +7,16 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
//модель свойств текста, которые нам нужны в word документе
public class WordTextProperties
{
//размере текста
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
//надо ли делать его жирным
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
//выравнивание
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -2,6 +2,7 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
@ -13,285 +14,382 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
//Настройка стилей для файла
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
//настройка шрифта простого текста
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
//настройка шрифта заголока
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
//добавление созданных шрифтов
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
//создание заливки
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill1 = new Fill();
fill1.Append(new PatternFill()
{
PatternType = PatternValues.None
});
var fill2 = new Fill();
fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
//стиль границ ячейки - незакрашенный (для заголовка) и закрашенный
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style = BorderStyleValues.Thin
};
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
//формирование CellFormat из комбинаций шрифтов, заливок и т. д.
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
cellStyleFormats.Append(cellFormatStyle);
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U
};
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true };
var cellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 1U, FormatId = 0U, ApplyFont = true, ApplyBorder = true };
var cellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true };
cellStyleFormats.Append(cellFormatStyle);
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellFormats = new CellFormats() { Count = 3U };
var cellStyles = new CellStyles() { Count = 1U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
cellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U });
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId = 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true
};
var tableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" };
//по итогу создали 3 стиля
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var stylesheetExtensionList = new StylesheetExtensionList();
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle = "TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" });
stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle = "SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" });
var stylesheetExtension2 = new StylesheetExtension()
{
Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBorder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
//Получение номера стиля (одного из 3-х нами созданных) из типа
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
CreateStyles(workbookpart);
protected override void CreateExcel(ExcelInfo info)
{
//создаём документ Excel
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
workbookpart.Workbook = new Workbook();
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
CreateStyles(workbookpart);
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
_worksheet = worksheetPart.Worksheet;
}
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
var newCell = new Cell() { CellReference = excelParams.CellReference };
row.InsertBefore(newCell, refCell);
sheets.Append(sheet);
cell = newCell;
}
_worksheet = worksheetPart.Worksheet;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
//метод вставки в лист книги
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (sheetData == null)
{
return;
}
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
// Ищем строку, либо добавляем ее
Row row;
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<SheetData>().First());
}
}
if (sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! == excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
// Ищем нужную ячейку
Cell cell;
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Close();
}
}
if (row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value == excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference = excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count() - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
//метод объединения ячеек
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells, _worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Close();
}
}
}

View File

@ -11,106 +11,121 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
//реализация астрактного класса создания pdf документа
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Section? _section;
private Table? _table;
private Table? _table;
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
//преобразование необходимого типа выравнивания в соотвествующее выравнивание в MigraDoc
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Rigth => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
_ => ParagraphAlignment.Justify,
};
}
//Создание стилей для документа
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
//Создание стилей для документа
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
_section = _document.AddSection();
}
protected override void CreatePdf(PdfInfo info)
{
//создаём документ
_document = new Document();
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
//передаём для него стили
DefineStyles(_document);
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
//получение первой секции документа
_section = _document.AddSection();
}
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
Unit borderWidth = 0.5;
//добавляем таблицу в документ как последнюю секцию (?)
_table = _document.LastSection.AddTable();
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
//добавление строки в таблицу
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
//ячейка добавляется добавлением параграфа
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -1,5 +1,6 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
@ -11,126 +12,143 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
//реализация абстрактного класса сохранения в word
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private Body? _docBody;
//Получение типа выравнивания
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
//Получение типа выравнивания
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
//выравнивание слева будет в том случае, если передаётся неизвестный тип выравнивания
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
//Настройки страницы
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
//Настройки страницы
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
//прописываем портретную ориентацию
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
properties.AppendChild(pageSize);
return properties;
}
return properties;
}
//Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
//Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
//вытаскиваем выравнивание текста
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
}
properties.AppendChild(paragraphMarkRunProperties);
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
return properties;
}
protected override void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateWord(WordInfo info)
{
//создаём документ word
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
//вытаскиваем главную часть из вордовского документа
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
var docParagraph = new Paragraph();
mainPart.Document = new Document();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
//генерируем тело основной части документа
_docBody = mainPart.Document.AppendChild(new Body());
}
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
protected override void CreateParagraph(WordParagraph paragraph)
{
//проверка на то, был ли вызван WordprocessingDocument.Create (создался ли документ) и есть ли вообще параграф для вставки
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
//добавляем свойства параграфа
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
//вставляем блоки текста (их называют Run)
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
//метод сохранения документа
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
//вставляем информацию по секциям (смотри, что является входным параметром)
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
//сохраняем документ
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
_wordDocument.Close();
}
protected override void CreateTable(WordParagraph paragraph)
{
@ -201,5 +219,5 @@ namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(table);
}
}
}
}

View File

@ -6,12 +6,12 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}
}

View File

@ -8,36 +8,36 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
public interface IReportLogic
{
//Получение списка добавок с указанием, в каких мороженых используются
List<ReportManufactureWorkPieceViewModel> GetManufactureWorkPiece();
List<ReportManufactureWorkPieceViewModel> GetManufactureWorkPiece();
//Получение списка мороженых с указанием, в каких магазинах в наличии
List<ReportShopManufacturesViewModel> GetShopManufactures();
//Получение списка заказов за определенный период
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
//Получение списка заказов за определенный период
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
//Получение списка заказов за весь период
List<ReportGroupedOrdersViewModel> GetGroupedOrders();
//Сохранение добавок в файл-Word
void SaveManufacturesToWordFile(ReportBindingModel model);
void SaveManufacturesToWordFile(ReportBindingModel model);
//Сохранение магазинов в виде таблицы в файл-Word
void SaveShopsToWordFile(ReportBindingModel model);
//Сохранение добавок с указаеним мороженых в файл-Excel
void SaveManufactureWorkPieceToExcelFile(ReportBindingModel model);
void SaveManufactureWorkPieceToExcelFile(ReportBindingModel model);
//Сохранение магазинов с указанием мороженых в файл-Excel
void SaveShopManufacturesToExcelFile(ReportBindingModel model);
//Сохранение заказов в файл-Pdf
void SaveOrdersToPdfFile(ReportBindingModel model);
//Сохранение заказов в файл-Pdf
void SaveOrdersToPdfFile(ReportBindingModel model);
//Сохранение заказов за весь период в файл-Pdf
void SaveGroupedOrdersToPdfFile(ReportBindingModel model);
}
}
}

View File

@ -6,12 +6,13 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class ReportManufactureWorkPieceViewModel
{
public string ManufactureName { get; set; } = string.Empty;
public class ReportManufactureWorkPieceViewModel
{
public string ManufactureName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public int TotalCount { get; set; }
public List<(string WorkPiece, int Count)> WorkPieces { get; set; } = new();
}
//список кортежей
public List<(string WorkPiece, int Count)> WorkPieces { get; set; } = new();
}
}

View File

@ -7,16 +7,16 @@ using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class ReportOrdersViewModel
{
public int Id { get; set; }
public class ReportOrdersViewModel
{
public int Id { get; set; }
public DateTime DateCreate { get; set; }
public DateTime DateCreate { get; set; }
public string ManufactureName { get; set; } = string.Empty;
public double Sum { get; set; }
public string ManufactureName { get; set; } = string.Empty;
public string OrderStatus { get; set; }
}
public double Sum { get; set; }
public string OrderStatus { get; set; }
}
}

View File

@ -17,16 +17,23 @@ namespace BlacksmithWorkshopDatabaseImplement.Implements
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDatabase();
var element = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
// для отображения КОРРЕКТНОЙ ViewModel-и
var deletedElement = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
return deletedElement;
}
return null;
@ -77,9 +84,9 @@ namespace BlacksmithWorkshopDatabaseImplement.Implements
using var context = new BlacksmithWorkshopDatabase();
return context.Orders
.Include(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
.Include(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
@ -92,6 +99,7 @@ namespace BlacksmithWorkshopDatabaseImplement.Implements
}
using var context = new BlacksmithWorkshopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();

View File

@ -28,9 +28,11 @@ namespace BlacksmithWorkshopFileImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue)
{
return new();
return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => GetViewModel(x))
.ToList();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList();

View File

@ -41,8 +41,16 @@ namespace BlacksmithWorkshopListImplement.Implements
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue)
if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo)
{
result.Add(GetViewModel(order));
}
}
return result;
}