ISEbd-21.Fedotov.I.A.LabWork04 #4

Closed
Ilfedotov.01 wants to merge 10 commits from ISEbd-21.Fedotov.I.A.LabWork04 into ISEbd-21.Fedotov.I.A.LabWork03
57 changed files with 2507 additions and 35 deletions

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set;}
}
}

View File

@ -0,0 +1,24 @@
using DinerContracts.BindingModels;
using DinerContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
// Получение списка компонент с указанием, в каких изделиях используются
List<ReportSnackFoodsViewModel> GetProductComponent();
// Получение списка заказов за определенный период
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
// Сохранение компонент в файл-Word
void SaveComponentsToWorldFile(ReportBindingModel model);
// Сохранение компонент с указаеним продуктов в файл-Excel
void SaveProductComponentToExcelFile(ReportBindingModel model);
// Сохранение заказов в файл-Pdf
void SaveOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -9,5 +9,7 @@ namespace DinerContracts.SearchModels
public class OrderSearchModel
{
public int? ID { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
}

View File

@ -31,8 +31,8 @@ namespace DinerContracts.ViewModels
[DisplayName("Номер")]
public int ID { get; set; }
[DisplayName("Снэк")]
// какой снэк изготавливается в рамках заказа
[DisplayName("Снэк")]
public string ProductName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,18 @@
using DinerDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerContracts.ViewModels
{
public class ReportOrdersViewModel
{
public int ID { get; set; }
public DateTime DateCreate { get; set; }
public string ProductName { get; set; } = string.Empty;
public double Sum { get; set; }
public string OrderStatus { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerContracts.ViewModels
{
public class ReportSnackFoodsViewModel
{
public string ProductName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Product, int count)> Components { get; set; } = new();
}
}

View File

@ -3,6 +3,7 @@ using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
@ -38,11 +39,17 @@ namespace DinerDataBaseImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.ID.HasValue) {
using var context = new DinerDataBase();
if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null)) {
return new();
}
using var context = new DinerDataBase();
return context.Orders.Where(x => x.ID == model.ID).Select(GetViewModel).ToList();
else {
return context.Orders
.Include(x => x.Snack)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(GetViewModel)
.ToList();
}
}
public List<OrderViewModel> GetFullList()

View File

@ -33,7 +33,7 @@ namespace DinerDataBaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ComponentName")
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
@ -94,7 +94,7 @@ namespace DinerDataBaseImplement.Migrations
b.HasKey("ID");
b.ToTable("Products");
b.ToTable("Components");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.SnackFood", b =>

View File

@ -44,7 +44,7 @@ namespace DinerDataBaseImplement.Migrations
});
migrationBuilder.CreateTable(
name: "Products",
name: "Components",
columns: table => new
{
ID = table.Column<int>(type: "int", nullable: false)
@ -79,7 +79,7 @@ namespace DinerDataBaseImplement.Migrations
table.ForeignKey(
name: "FK_ProductComponents_Products_ProductID",
column: x => x.ProductID,
principalTable: "Products",
principalTable: "Components",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
@ -108,7 +108,7 @@ namespace DinerDataBaseImplement.Migrations
name: "Components");
migrationBuilder.DropTable(
name: "Products");
name: "Components");
}
}
}

View File

@ -33,7 +33,7 @@ namespace DinerDataBaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ComponentName")
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
@ -93,7 +93,7 @@ namespace DinerDataBaseImplement.Migrations
b.HasKey("ID");
b.ToTable("Products");
b.ToTable("Components");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.SnackFood", b =>

View File

@ -33,7 +33,7 @@ namespace DinerDataBaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ComponentName")
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
@ -98,7 +98,7 @@ namespace DinerDataBaseImplement.Migrations
b.HasKey("ID");
b.ToTable("Products");
b.ToTable("Components");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.SnackFood", b =>

View File

@ -25,7 +25,7 @@ namespace DinerDataBaseImplement.Migrations
name: "FK_Orders_Products_SnackID",
table: "Orders",
column: "SnackID",
principalTable: "Products",
principalTable: "Components",
principalColumn: "ID");
}

View File

@ -30,7 +30,7 @@ namespace DinerDataBaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("ID"));
b.Property<string>("ComponentName")
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("nvarchar(max)");
@ -95,7 +95,7 @@ namespace DinerDataBaseImplement.Migrations
b.HasKey("ID");
b.ToTable("Products", (string)null);
b.ToTable("Components", (string)null);
});
modelBuilder.Entity("DinerDataBaseImplement.Models.SnackFood", b =>

View File

@ -59,7 +59,7 @@ namespace DinerDataBaseImplement.Models
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
DateImplement = DateImplement,
};
}

View File

@ -33,7 +33,7 @@ namespace DinerFileImplement.Models
return new Food()
{
ID = Convert.ToInt32(element.Attribute("ID")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
ComponentName = element.Element("ProductName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value)
};
}
@ -51,7 +51,7 @@ namespace DinerFileImplement.Models
};
public XElement GetXElement => new("Food", new XAttribute("ID", ID),
new XElement("ComponentName", ComponentName),
new XElement("ProductName", ComponentName),
new XElement("Price", Price.ToString()));
}
}

View File

@ -19,14 +19,17 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.5.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic" Version="4.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
<PackageReference Include="ReportViewerCore.WinForms" Version="15.1.17" />
</ItemGroup>
<ItemGroup>

View File

@ -34,7 +34,7 @@ namespace DinerView
{
dataGridView.DataSource = list;
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ProductName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка продуктов");
}

View File

@ -32,6 +32,10 @@
toolStripMenuItemMenu = new ToolStripMenuItem();
toolStripMenuItemFoods = new ToolStripMenuItem();
toolStripMenuItemSnacks = new ToolStripMenuItem();
toolStripMenuItemReport = new ToolStripMenuItem();
FoodsToolStripMenuItem = new ToolStripMenuItem();
FoodSnacksToolStripMenuItem = new ToolStripMenuItem();
ordersToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonInWork = new Button();
@ -45,7 +49,7 @@
// menuStrip
//
menuStrip.BackColor = SystemColors.Control;
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItemMenu });
menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItemMenu, toolStripMenuItemReport });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(951, 24);
@ -62,17 +66,45 @@
// toolStripMenuItemFoods
//
toolStripMenuItemFoods.Name = "toolStripMenuItemFoods";
toolStripMenuItemFoods.Size = new Size(180, 22);
toolStripMenuItemFoods.Size = new Size(129, 22);
toolStripMenuItemFoods.Text = "Продукты";
toolStripMenuItemFoods.Click += toolStripMenuItemFoods_Click;
//
// toolStripMenuItemSnacks
//
toolStripMenuItemSnacks.Name = "toolStripMenuItemSnacks";
toolStripMenuItemSnacks.Size = new Size(180, 22);
toolStripMenuItemSnacks.Size = new Size(129, 22);
toolStripMenuItemSnacks.Text = "Снэки";
toolStripMenuItemSnacks.Click += toolStripMenuItemSnacks_Click;
//
// toolStripMenuItemReport
//
toolStripMenuItemReport.DropDownItems.AddRange(new ToolStripItem[] { FoodsToolStripMenuItem, FoodSnacksToolStripMenuItem, ordersToolStripMenuItem });
toolStripMenuItemReport.Name = "toolStripMenuItemReport";
toolStripMenuItemReport.Size = new Size(60, 20);
toolStripMenuItemReport.Text = "Отчеты";
//
// FoodsToolStripMenuItem
//
FoodsToolStripMenuItem.Name = "FoodsToolStripMenuItem";
FoodsToolStripMenuItem.Size = new Size(192, 22);
FoodsToolStripMenuItem.Text = "Список продуктов";
FoodsToolStripMenuItem.Click += FoodsToolStripMenuItem_Click;
//
// FoodSnacksToolStripMenuItem
//
FoodSnacksToolStripMenuItem.Name = "FoodSnacksToolStripMenuItem";
FoodSnacksToolStripMenuItem.Size = new Size(192, 22);
FoodSnacksToolStripMenuItem.Text = "Продукты для снэков";
FoodSnacksToolStripMenuItem.Click += FoodSnacksToolStripMenuItem_Click;
//
// ordersToolStripMenuItem
//
ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
ordersToolStripMenuItem.Size = new Size(192, 22);
ordersToolStripMenuItem.Text = "Список заказов";
ordersToolStripMenuItem.Click += ordersToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
@ -176,5 +208,9 @@
private Button buttonIsReady;
private Button buttonIsDelivery;
private Button buttonUpdateList;
private ToolStripMenuItem toolStripMenuItemReport;
private ToolStripMenuItem FoodsToolStripMenuItem;
private ToolStripMenuItem FoodSnacksToolStripMenuItem;
private ToolStripMenuItem ordersToolStripMenuItem;
}
}

View File

@ -1,5 +1,6 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContacts;
using DinerContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -18,11 +19,13 @@ namespace DinerView
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
@ -54,7 +57,8 @@ namespace DinerView
private void toolStripMenuItemFoods_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormFoods));
if (service is FormFoods form) {
if (service is FormFoods form)
{
form.ShowDialog();
LoadData();
}
@ -63,7 +67,8 @@ namespace DinerView
private void toolStripMenuItemSnacks_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSnacks));
if (service is FormSnacks form) {
if (service is FormSnacks form)
{
form.ShowDialog();
LoadData();
}
@ -153,5 +158,33 @@ namespace DinerView
{
LoadData();
}
private void FoodsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWorldFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void FoodSnacksToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportSnackFoods));
if (service is FormReportSnackFoods form)
{
form.ShowDialog();
}
}
private void ordersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,140 @@
namespace DinerView
{
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);
}
#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()
{
panel = new Panel();
buttonToPdf = new Button();
buttonMake = new Button();
dateTimePickerTo = new DateTimePicker();
labelTo = new Label();
dateTimePickerFrom = new DateTimePicker();
labelFrom = new Label();
reportViewer1 = new Microsoft.Reporting.WinForms.ReportViewer();
panel.SuspendLayout();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonToPdf);
panel.Controls.Add(buttonMake);
panel.Controls.Add(dateTimePickerTo);
panel.Controls.Add(labelTo);
panel.Controls.Add(dateTimePickerFrom);
panel.Controls.Add(labelFrom);
panel.Dock = DockStyle.Top;
panel.Location = new Point(0, 0);
panel.Name = "panel";
panel.Size = new Size(720, 49);
panel.TabIndex = 0;
//
// buttonToPdf
//
buttonToPdf.Location = new Point(606, 11);
buttonToPdf.Name = "buttonToPdf";
buttonToPdf.Size = new Size(106, 28);
buttonToPdf.TabIndex = 5;
buttonToPdf.Text = "В .pdf";
buttonToPdf.UseVisualStyleBackColor = true;
buttonToPdf.Click += buttonToPdf_Click;
//
// buttonMake
//
buttonMake.Location = new Point(494, 11);
buttonMake.Name = "buttonMake";
buttonMake.Size = new Size(106, 28);
buttonMake.TabIndex = 4;
buttonMake.Text = "Сформировать";
buttonMake.UseVisualStyleBackColor = true;
buttonMake.Click += buttonMake_Click;
//
// dateTimePickerTo
//
dateTimePickerTo.Location = new Point(261, 12);
dateTimePickerTo.Name = "dateTimePickerTo";
dateTimePickerTo.Size = new Size(186, 23);
dateTimePickerTo.TabIndex = 3;
//
// labelTo
//
labelTo.AutoSize = true;
labelTo.Location = new Point(234, 18);
labelTo.Name = "labelTo";
labelTo.Size = new Size(21, 15);
labelTo.TabIndex = 2;
labelTo.Text = "по";
//
// dateTimePickerFrom
//
dateTimePickerFrom.Location = new Point(33, 12);
dateTimePickerFrom.Name = "dateTimePickerFrom";
dateTimePickerFrom.Size = new Size(186, 23);
dateTimePickerFrom.TabIndex = 1;
//
// labelFrom
//
labelFrom.AutoSize = true;
labelFrom.Location = new Point(12, 18);
labelFrom.Name = "labelFrom";
labelFrom.Size = new Size(15, 15);
labelFrom.TabIndex = 0;
labelFrom.Text = "С";
//
// reportViewer1
//
reportViewer1.Location = new Point(0, 0);
reportViewer1.Name = "ReportViewer";
reportViewer1.ServerReport.BearerToken = null;
reportViewer1.Size = new Size(396, 246);
reportViewer1.TabIndex = 0;
//
// FormReportOrders
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(720, 450);
Controls.Add(panel);
Name = "FormReportOrders";
Text = "Заказы";
panel.ResumeLayout(false);
panel.PerformLayout();
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonMake;
private DateTimePicker dateTimePickerTo;
private Label labelTo;
private DateTimePicker dateTimePickerFrom;
private Label labelFrom;
private Button buttonToPdf;
private Microsoft.Reporting.WinForms.ReportViewer reportViewer1;
}
}

View File

@ -0,0 +1,96 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
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;
namespace DinerView
{
public partial class FormReportOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\fedot\\source\\repos\\ISEbd-21.Fedotov.I.A.Diner\\Diner\\DinerView\\ReportOrders.rdlc", FileMode.Open));
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
});
var source = new ReportDataSource("DataSetOrders", dataSource);
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);
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);
}
}
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
});
_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);
}
}
}
}
}

View File

@ -0,0 +1,123 @@
<?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>
<metadata name="reportViewer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,109 @@
namespace DinerView
{
partial class FormReportSnackFoods
{
/// <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()
{
dataGridView = new DataGridView();
ColumnFood = new DataGridViewTextBoxColumn();
ColumnSnack = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonSaveToExcel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLight;
dataGridView.BorderStyle = BorderStyle.None;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnFood, ColumnSnack, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 55);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.Size = new Size(800, 395);
dataGridView.TabIndex = 0;
//
// ColumnFood
//
ColumnFood.HeaderText = "Еда";
ColumnFood.Name = "ColumnFood";
ColumnFood.ReadOnly = true;
//
// ColumnSnack
//
ColumnSnack.HeaderText = "Снэк";
ColumnSnack.Name = "ColumnSnack";
ColumnSnack.ReadOnly = true;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(12, 12);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(236, 37);
buttonSaveToExcel.TabIndex = 1;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += buttonSaveToExcel_Click;
//
// FormReportSnackFoods
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.LightGray;
ClientSize = new Size(800, 450);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Name = "FormReportSnackFoods";
Text = "Еда из снэков";
Load += FormReportSnackFoods_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumnFood;
private DataGridViewTextBoxColumn ColumnSnack;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,71 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
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;
namespace DinerView
{
public partial class FormReportSnackFoods : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportSnackFoods(ILogger<FormReportSnackFoods> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportSnackFoods_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetProductComponent();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ProductName, "", "" });
foreach (var listElem in elem.Components)
{
dataGridView.Rows.Add(new object[] { " ", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Загрузка списка снэков по продуктам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка снэков по продуктам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" };
if (dialog.ShowDialog() == DialogResult.OK) {
try {
_logic.SaveProductComponentToExcelFile(new ReportBindingModel { FileName = dialog.FileName });
_logger.LogInformation("Сохранение списка снэков по продуктам");
MessageBox.Show("Выполнение", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка сохранения списка снэков по продуктам");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -0,0 +1,129 @@
<?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>
<metadata name="ColumnFood.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnSnack.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

@ -93,7 +93,7 @@ namespace DinerView
if (form.ShowDialog() == DialogResult.OK)
{
if (form.foodModel == null) return;
_logger.LogInformation("Добавление нового снэка: {ComponentName} - {Count}", form.foodModel.ComponentName, form.Count);
_logger.LogInformation("Добавление нового снэка: {ProductName} - {Count}", form.foodModel.ComponentName, form.Count);
if (_productComponents.ContainsKey(form.ID))
{
_productComponents[form.ID] = (form.foodModel, form.Count);
@ -120,7 +120,7 @@ namespace DinerView
if (form.ShowDialog() == DialogResult.OK)
{
if (form.foodModel == null) return;
_logger.LogInformation("Изменение снэка: {ComponentName} - {Count}", form.foodModel.ComponentName, form.Count);
_logger.LogInformation("Изменение снэка: {ProductName} - {Count}", form.foodModel.ComponentName, form.Count);
_productComponents[form.ID] = (form.foodModel, form.Count);
LoadData();
}
@ -136,7 +136,7 @@ namespace DinerView
{
try
{
_logger.LogInformation("Удаление снэка: {ComponentName}", dataGridView.SelectedRows[0].Cells[1].Value);
_logger.LogInformation("Удаление снэка: {ProductName}", dataGridView.SelectedRows[0].Cells[1].Value);
_productComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)

View File

@ -57,7 +57,7 @@ namespace DinerView
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxComponent.DisplayMember = "ComponentName";
comboBoxComponent.DisplayMember = "ProductName";
comboBoxComponent.ValueMember = "ID";
comboBoxComponent.DataSource = _list;
comboBoxComponent.SelectedItem = null;

View File

@ -1,7 +1,10 @@
using DinerContracts.BusinessLogicsContacts;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.StoragesContracts;
using DinerDataBaseImplement.Implements;
using DineryBusinessLogic.BusinessLogic;
using DineryBusinessLogic.OfficePackage;
using DineryBusinessLogic.OfficePackage.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -41,6 +44,11 @@ namespace DinerView
services.AddTransient<IFoodLogic, FoodLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISnackLogic, SnackLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormFood>();
@ -49,6 +57,8 @@ namespace DinerView
services.AddTransient<FormSnack>();
services.AddTransient<FormSnackFood>();
services.AddTransient<FormSnacks>();
services.AddTransient<FormReportSnackFoods>();
services.AddTransient<FormReportOrders>();
}
}
}

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IFoodLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.BusinessLogicsContacts.IFoodLogic, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IOrderLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.BusinessLogicsContacts.IOrderLogic, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="ISnackLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.BusinessLogicsContacts.ISnackLogic, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IReportLogic" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.BusinessLogicsContracts.IReportLogic, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IFoodStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.StoragesContracts.IFoodStorage, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="IOrderStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.StoragesContracts.IOrderStorage, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio .Net. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="ISnackStorage" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>DinerContracts.StoragesContracts.ISnackStorage, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

@ -0,0 +1,599 @@
<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<AutoRefresh>0</AutoRefresh>
<DataSources>
<DataSource Name="DinerContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>10791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetOrders">
<Query>
<DataSourceName>DinerContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="ID">
<DataField>ID</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="DateCreate">
<DataField>DateCreate</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="ProductName">
<DataField>ProductName</DataField>
<rd:TypeName>System.String</rd:TypeName>
</Field>
<Field Name="Sum">
<DataField>Sum</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
<Field Name="Status">
<DataField>OrderStatus</DataField>
<rd:TypeName>System.Decimal</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>DinerContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>DinerContracts.ViewModels.ReportOrdersViewModel, DinerContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style>
<FontSize>14pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>1cm</Top>
<Height>1cm</Height>
<Width>21cm</Width>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Заказы</Value>
<Style>
<FontSize>16pt</FontSize>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>1cm</Height>
<Width>21cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<VerticalAlign>Middle</VerticalAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>8.23317cm</Width>
</TablixColumn>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
<TablixColumn>
<Width>2.5cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Textbox5">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Номер</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox5</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox1">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox1</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox3">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Снэк</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox3</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox7">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Сумма</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox7</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Textbox2">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Status</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Textbox2</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="ID">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!ID.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>ID</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="DateCreate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!DateCreate.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>DateCreate</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="ProductName">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!ProductName.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>ProductName</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Sum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Sum.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Sum</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
<TablixCell>
<CellContents>
<Textbox Name="Status">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Status.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Status</rd:DefaultName>
<Style>
<Border>
<Color>LightGrey</Color>
<Style>Solid</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</CellContents>
</TablixCell>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<TablixMember />
<TablixMember />
<TablixMember />
<TablixMember />
<TablixMember />
</TablixMembers>
</TablixColumnHierarchy>
<TablixRowHierarchy>
<TablixMembers>
<TablixMember>
<KeepWithGroup>After</KeepWithGroup>
</TablixMember>
<TablixMember>
<Group Name="Подробности" />
</TablixMember>
</TablixMembers>
</TablixRowHierarchy>
<DataSetName>DataSetOrders</DataSetName>
<Top>2.48391cm</Top>
<Left>0.55245cm</Left>
<Height>1.2cm</Height>
<Width>18.94755cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>Double</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxTotalSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>12cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>3</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Textbox Name="SumTotal">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!Sum.Value, "DataSetOrders")</Value>
<Style>
<FontWeight>Bold</FontWeight>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>4cm</Top>
<Left>14.5cm</Left>
<Height>0.6cm</Height>
<Width>2.5cm</Width>
<ZIndex>4</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
</ReportItems>
<Height>5.72875cm</Height>
<Style />
</Body>
<Width>25.43558cm</Width>
<Page>
<PageHeight>29.7cm</PageHeight>
<PageWidth>21cm</PageWidth>
<LeftMargin>2cm</LeftMargin>
<RightMargin>2cm</RightMargin>
<TopMargin>2cm</TopMargin>
<BottomMargin>2cm</BottomMargin>
<ColumnSpacing>0.13cm</ColumnSpacing>
<Style />
</Page>
</ReportSection>
</ReportSections>
<ReportParameters>
<ReportParameter Name="ReportParameterPeriod">
<DataType>String</DataType>
<Nullable>true</Nullable>
<Prompt>ReportParameter1</Prompt>
</ReportParameter>
</ReportParameters>
<ReportParametersLayout>
<GridLayoutDefinition>
<NumberOfColumns>4</NumberOfColumns>
<NumberOfRows>2</NumberOfRows>
<CellDefinitions>
<CellDefinition>
<ColumnIndex>0</ColumnIndex>
<RowIndex>0</RowIndex>
<ParameterName>ReportParameterPeriod</ParameterName>
</CellDefinition>
</CellDefinitions>
</GridLayoutDefinition>
</ReportParametersLayout>
<rd:ReportUnitType>Cm</rd:ReportUnitType>
<rd:ReportID>2de0031a-4d17-449d-922d-d9fc54572312</rd:ReportID>
</Report>

View File

@ -47,7 +47,7 @@ namespace DineryBusinessLogic.BusinessLogic
public FoodViewModel? ReadElement(FoodSearchModel model)
{
if (model == null) throw new ArgumentNullException(nameof(model));
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}. ID:{ID}", model.ComponentName, model.ID);
_logger.LogInformation("ReadElement. ProductName:{ProductName}. ID:{ID}", model.ComponentName, model.ID);
var element = _componentStorage.GetElement(model);
if (element == null) {
_logger.LogWarning("ReadElement. element not found");
@ -59,7 +59,7 @@ namespace DineryBusinessLogic.BusinessLogic
public List<FoodViewModel>? ReadList(FoodSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. ID:{ID}", model?.ComponentName, model?.ID);
_logger.LogInformation("ReadList. ProductName:{ProductName}. ID:{ID}", model?.ComponentName, model?.ID);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null) {
_logger.LogWarning("ReadList return null list");
@ -86,7 +86,7 @@ namespace DineryBusinessLogic.BusinessLogic
throw new ArgumentNullException("Нет названия компонента", nameof(model.ComponentName));
if (model.Price <= 0)
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Price));
_logger.LogInformation("Component. ComponentName:{ComponentName}. Price:{Price}. ID:{ID}",
_logger.LogInformation("Component. ProductName:{ProductName}. Price:{Price}. ID:{ID}",
model.ComponentName, model.Price, model.ID);
var element = _componentStorage.GetElement(new FoodSearchModel { ComponentName = model.ComponentName });
if (element != null && element.ID != model.ID)

View File

@ -0,0 +1,107 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DineryBusinessLogic.OfficePackage;
using DineryBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.BusinessLogic
{
public class ReportLogic : IReportLogic
{
private readonly IFoodStorage _componentStorage;
private readonly ISnackStorage _productStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IFoodStorage componentStorage, ISnackStorage productStorage, IOrderStorage orderStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_componentStorage = componentStorage;
_productStorage = productStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
// Получение списка заказов за определенный период
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,
ProductName = x.ProductName,
Sum = x.Sum,
OrderStatus = x.Status.ToString(),
})
.ToList();
}
// Получение списка компонент с указанием, в каких изделиях используются
public List<ReportSnackFoodsViewModel> GetProductComponent()
{
var components = _componentStorage.GetFullList();
Review

При получении изделий, у них уже есть список компонент, отдельно его получать не требуется

При получении изделий, у них уже есть список компонент, отдельно его получать не требуется
Review

Так мы же в логике проходимся по всем созданным компонентам, смотрим есть ли такое в словаре компонет изделия, если есть, то уже в созданном объекте record дополняем список и добавляем 1 к totalcount. У нас же может быть создан компонент, который в изделиях не использован. Поэтому у нас будет recoed {ComponentName = "",Products = [], totalCount = 0};

Так мы же в логике проходимся по всем созданным компонентам, смотрим есть ли такое в словаре компонет изделия, если есть, то уже в созданном объекте record дополняем список и добавляем 1 к totalcount. У нас же может быть создан компонент, который в изделиях не использован. Поэтому у нас будет recoed {ComponentName = "",Products = [], totalCount = 0};
var products = _productStorage.GetFullList();
var list = new List<ReportSnackFoodsViewModel>();
foreach (var pr in products) {
var record = new ReportSnackFoodsViewModel
{
ProductName = pr.ProductName,
Components = new(),
TotalCount = 0
};
foreach (var cp in components) {
if (pr.ProductComponents.ContainsKey(cp.ID)) {
record.Components.Add(new(cp.ComponentName, pr.ProductComponents[cp.ID].Item2));
record.TotalCount += pr.ProductComponents[cp.ID].Item2;
}
}
list.Add(record);
}
return list;
}
public void SaveComponentsToWorldFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список еды",
Products = _productStorage.GetFullList(),
});
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список заказов",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Orders = GetOrders(model)
});
}
public void SaveProductComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Список еды",
ProductComponents = GetProductComponent()
});
}
}
}

View File

@ -7,7 +7,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>
<ItemGroup>

View File

@ -0,0 +1,84 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info) {
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.ProductComponents) {
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.ProductName,
StyleInfo = ExcelStyleInfoType.Title
});
rowIndex++;
foreach (var (Product, Count) in pc.Components) {
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Product,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Итого",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Title
});
rowIndex++;
}
SaveExcel(info);
}
// Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info);
// Добавляем новую ячейку в лист
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
// Объединение ячеек
protected abstract void MergeCells(ExcelMergeParameters excelParams);
// Сохранение файла
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -0,0 +1,65 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info) {
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"c {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Text = new List<string> { "Номер", "Дата заказа", "Изделие", "Сумма", "Статус" },
Style = "NormalTittle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders) {
CreateRow(new PdfRowParameters
{
Text = new List<string> { order.ID.ToString(), order.DateCreate.ToShortTimeString(),
order.ProductName, order.Sum.ToString(), order.OrderStatus.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
SavePdf(info);
}
// Создание doc-файла
protected abstract void CreatePdf(PdfInfo info);
// Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph);
// Создание таблицы
protected abstract void CreateTable(List<string> columns);
// Создание и заполнение строки
protected abstract void CreateRow(PdfRowParameters rowParameters);
// Сохранение файла
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,44 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info) {
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties {
Size = "24",
JustificationType = WordJustificationType.Center
}
});
foreach (var pr in info.Products)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> {
(pr.ProductName+' ', new WordTextProperties { Size = "24", Bold = true }),
(pr.Price.ToString(), new WordTextProperties { Size = "24" })
},
TextProperties = new WordTextProperties { Size = "24", Bold = true}
});
}
SaveWord(info);
}
// Создание doc-файла
protected abstract void CreateWord(WordInfo info);
// Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph);
// Сохранение файла
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBorder
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Right
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
both
}
}

View File

@ -0,0 +1,18 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.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; }
}
}

View File

@ -0,0 +1,17 @@
using DinerContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportSnackFoodsViewModel> ProductComponents { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,19 @@
using DinerContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.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();
}
}

View File

@ -0,0 +1,16 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Text { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using DinerContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<SnackViewModel> Products { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,266 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
private static void CreateStyles(WorkbookPart workbookpart) {
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
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 fontTittle = new Font();
fontTittle.Append(new Bold());
fontTittle.Append(new FontSize() { Val = 14D });
fontTittle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U });
fontTittle.Append(new FontName() { Val = "Times New Roman" });
fontTittle.Append(new FontFamilyNumbering() { Val = 2 });
fontTittle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTittle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 });
fills.Append(fill1);
fills.Append(fill2);
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 borderThin = new Border();
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 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 });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U };
cellStyleFormats.Append(cellFormatStyle);
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 = 0U,
FillId = 1U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal = HorizontalAlignmentValues.Center
},
ApplyFont = true,
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
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 StylesheetExtension();
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" });
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" });
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
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);
}
// Получение номера стиля из типа
private static uint GetStyleValue(ExcelStyleInfoType styleInfo) {
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBorder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
? _spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
: _spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null) {
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{
if (_worksheet == null || _shareStringPart == null) {
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null) {
return;
}
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);
}
// Поиск нужнойц ячейки
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 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

@ -0,0 +1,103 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml.Packaging;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
// Типы выравнивания
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) {
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify
};
}
// Cоздание стилей для документа
private static void DefineStyles(Document document) {
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
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;
}
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
// Ссылка на первую секцию
_section = _document.AddSection();
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if(_table == null) {
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Text.Count; ++i)
{
// заполнение ячейки (добавления параграфа в ячейку)
row.Cells[i].AddParagraph(rowParameters.Text[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 CreateTable(List<string> columns)
{
if (_document == null) {
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns) {
_table.AddColumn(elem);
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true) {
Document = _document,
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,110 @@
using DineryBusinessLogic.OfficePackage.HelperEnums;
using DineryBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.ExtendedProperties;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DineryBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
// Получение типа выравнивания
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();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
// Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) {
if (paragraphProperties == null)
return null;
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val = GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size)) {
paragraphMarkRunProperties.AppendChild(new FontSize
{
Val = paragraphProperties.Size
});
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null) {
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts) {
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize
{
Val = run.Item2.Size
});
if (run.Item2.Bold) {
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space = SpaceProcessingModeValues.Preserve
});
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
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 SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null) {
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
}
}