Kashin M.I. Lab work 6 hard #14

Closed
Sosees04ka wants to merge 4 commits from LabWork06_hard into LabWork05_hard
146 changed files with 79043 additions and 589 deletions
Showing only changes of commit 8b6dc76ee0 - Show all commits

View File

@ -17,9 +17,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrecastConcretePlantFileImp
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrecastConcretePlantDatabaseImplement", "PrecastConcretePlantDatabaseImplement\PrecastConcretePlantDatabaseImplement.csproj", "{080D0A98-0474-4FD7-8ABD-EDC294C8CF0D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrecastConcretePlantRestApi", "PrecastConcretePlantRestApi\PrecastConcretePlantRestApi.csproj", "{5521E334-453F-44B1-A404-561D54C18081}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrecastConcretePlantRestApi", "PrecastConcretePlantRestApi\PrecastConcretePlantRestApi.csproj", "{5521E334-453F-44B1-A404-561D54C18081}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrecastConcretePlantClientApp", "PrecastConcretePlantClientApp\PrecastConcretePlantClientApp.csproj", "{BADF79AD-155E-43C6-BE12-0F052C1F64D5}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PrecastConcretePlantClientApp", "PrecastConcretePlantClientApp\PrecastConcretePlantClientApp.csproj", "{BADF79AD-155E-43C6-BE12-0F052C1F64D5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PrecastConcretePlantShopApp", "PrecastConcretePlantShopApp\PrecastConcretePlantShopApp.csproj", "{E73EF41A-9DE4-4B27-8A50-21621F9A50A8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{BADF79AD-155E-43C6-BE12-0F052C1F64D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BADF79AD-155E-43C6-BE12-0F052C1F64D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BADF79AD-155E-43C6-BE12-0F052C1F64D5}.Release|Any CPU.Build.0 = Release|Any CPU
{E73EF41A-9DE4-4B27-8A50-21621F9A50A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E73EF41A-9DE4-4B27-8A50-21621F9A50A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E73EF41A-9DE4-4B27-8A50-21621F9A50A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E73EF41A-9DE4-4B27-8A50-21621F9A50A8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -56,8 +56,7 @@
this.запускРаботToolStripMenuItem});
this.MenuStrip.Location = new System.Drawing.Point(0, 0);
this.MenuStrip.Name = "MenuStrip";
this.MenuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
this.MenuStrip.Size = new System.Drawing.Size(1191, 30);
this.MenuStrip.Size = new System.Drawing.Size(1058, 24);
this.MenuStrip.TabIndex = 0;
this.MenuStrip.Text = "menuStrip1";
//
@ -69,20 +68,20 @@
this.КлиентыToolStripMenuItem,
this.исполнителиToolStripMenuItem});
this.СправочникиToolStripMenuItem.Name = "СправочникиToolStripMenuItem";
this.СправочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.СправочникиToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.СправочникиToolStripMenuItem.Text = "Cправочники";
//
// ИзделияToolStripMenuItem
//
this.ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem";
this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.ИзделияToolStripMenuItem.Text = "Изделия";
this.ИзделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click);
//
// КомпонентыToolStripMenuItem
//
this.КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(145, 22);
this.КомпонентыToolStripMenuItem.Text = "Компоненты";
this.КомпонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click);
//
@ -98,29 +97,32 @@
this.отчетыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.списокДокументовToolStripMenuItem,
this.компонентыПоДокументамToolStripMenuItem,
this.списокЗаказовToolStripMenuItem});
this.списокЗаказовToolStripMenuItem,
this.списокМагазиновToolStripMenuItem,
this.магазиныСИзделиямиToolStripMenuItem,
this.списокГруппЗаказовToolStripMenuItem});
this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
this.отчетыToolStripMenuItem.Text = "Отчеты";
//
// списокДокументовToolStripMenuItem
//
this.списокДокументовToolStripMenuItem.Name = "списокДокументовToolStripMenuItem";
this.списокДокументовToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокДокументовToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокДокументовToolStripMenuItem.Text = "Список документов";
this.списокДокументовToolStripMenuItem.Click += new System.EventHandler(this.списокДокументовToolStripMenuItem_Click);
//
// компонентыПоДокументамToolStripMenuItem
//
this.компонентыПоДокументамToolStripMenuItem.Name = омпонентыПоДокументамToolStripMenuItem";
this.компонентыПоДокументамToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.компонентыПоДокументамToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.компонентыПоДокументамToolStripMenuItem.Text = "Компоненты по документам";
this.компонентыПоДокументамToolStripMenuItem.Click += new System.EventHandler(this.компонентыПоДокументамToolStripMenuItem_Click);
//
// списокЗаказовToolStripMenuItem
//
this.списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказовToolStripMenuItem_Click);
//
@ -134,20 +136,18 @@
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Location = new System.Drawing.Point(0, 36);
this.DataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.DataGridView.Location = new System.Drawing.Point(0, 27);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 25;
this.DataGridView.Size = new System.Drawing.Size(1007, 561);
this.DataGridView.Size = new System.Drawing.Size(881, 421);
this.DataGridView.TabIndex = 1;
//
// CreateOrderButton
//
this.CreateOrderButton.Location = new System.Drawing.Point(1034, 36);
this.CreateOrderButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.CreateOrderButton.Location = new System.Drawing.Point(905, 27);
this.CreateOrderButton.Name = "CreateOrderButton";
this.CreateOrderButton.Size = new System.Drawing.Size(143, 44);
this.CreateOrderButton.Size = new System.Drawing.Size(125, 33);
this.CreateOrderButton.TabIndex = 2;
this.CreateOrderButton.Text = "Создать заказ";
this.CreateOrderButton.UseVisualStyleBackColor = true;
@ -158,7 +158,7 @@
this.IssuedOrderButton.Location = new System.Drawing.Point(1034, 140);
this.IssuedOrderButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.IssuedOrderButton.Name = "IssuedOrderButton";
this.IssuedOrderButton.Size = new System.Drawing.Size(143, 44);
this.IssuedOrderButton.Size = new System.Drawing.Size(125, 33);
this.IssuedOrderButton.TabIndex = 5;
this.IssuedOrderButton.Text = "Заказ выдан";
this.IssuedOrderButton.UseVisualStyleBackColor = true;
@ -166,10 +166,9 @@
//
// UpdateListButton
//
this.UpdateListButton.Location = new System.Drawing.Point(1034, 252);
this.UpdateListButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.UpdateListButton.Location = new System.Drawing.Point(905, 189);
this.UpdateListButton.Name = "UpdateListButton";
this.UpdateListButton.Size = new System.Drawing.Size(143, 44);
this.UpdateListButton.Size = new System.Drawing.Size(125, 33);
this.UpdateListButton.TabIndex = 6;
this.UpdateListButton.Text = "Обновить список";
this.UpdateListButton.UseVisualStyleBackColor = true;
@ -184,16 +183,17 @@
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1191, 600);
this.ClientSize = new System.Drawing.Size(1058, 338);
this.Controls.Add(this.buttonAddReinforcedInShop);
this.Controls.Add(this.buttonSellReinforced);
this.Controls.Add(this.UpdateListButton);
this.Controls.Add(this.IssuedOrderButton);
this.Controls.Add(this.CreateOrderButton);
this.Controls.Add(this.DataGridView);
this.Controls.Add(this.MenuStrip);
this.MainMenuStrip = this.MenuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMain";
this.Text = "Завод ЖБИ";
this.Load += new System.EventHandler(this.FormMain_Load);
@ -211,14 +211,15 @@
private ToolStripMenuItem СправочникиToolStripMenuItem;
private ToolStripMenuItem ИзделияToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private DataGridView DataGridView;
private Button CreateOrderButton;
private Button IssuedOrderButton;
private Button UpdateListButton;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem списокДокументовToolStripMenuItem;
private ToolStripMenuItem компонентыПоДокументамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private DataGridView DataGridView;
private Button CreateOrderButton;
private Button IssuedOrderButton;
private Button UpdateListButton;
private ToolStripMenuItem КлиентыToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;

View File

@ -1,4 +1,6 @@
using Microsoft.Extensions.Logging;

using Microsoft.Extensions.Logging;
using PrecastConcretePlant;
using PrecastConcretePlantBusinessLogic.BusinessLogic;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
@ -162,7 +164,7 @@ namespace PrecastConcretePlantView
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
{
Id = id,
});
@ -188,12 +190,23 @@ namespace PrecastConcretePlantView
LoadData();
}
private void SellReinforcedButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellReinforced));
if (service is FormSellReinforced form)
{
form.ShowDialog();
}
}
private void списокДокументовToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveReinforcediesToWordFile(new ReportBindingModel
_reportLogic.SaveReinforcedsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
@ -228,6 +241,61 @@ namespace PrecastConcretePlantView
}
}
private void магазиныToolStripMenuItem1_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveShopsTableToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void магазиныСИзделиямиToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopReinforcedies));
if (service is FormReportShopReinforcedies form)
{
form.ShowDialog();
}
}
private void списокГруппЗаказовToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupOrders));
if (service is FormReportGroupOrders form)
{
form.ShowDialog();
}
}
private void buttonSellReinforced_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellReinforced));
if (service is FormSellReinforced form)
{
form.ShowDialog();
}
}
private void buttonAddReinforcedInShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReinforcedShop));
if (service is FormReinforcedShop form)
{
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((

View File

@ -0,0 +1,151 @@
namespace PrecastConcretePlantView
{
partial class FormReinforcedShop
{
/// <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()
{
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.comboBoxReinforced = new System.Windows.Forms.ComboBox();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(214, 17);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(222, 23);
this.comboBoxShop.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(84, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(124, 15);
this.label1.TabIndex = 2;
this.label1.Text = "Выбранный магазин:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 47);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(196, 15);
this.label2.TabIndex = 4;
this.label2.Text = "Изделие которое нужно добавить:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(133, 73);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(75, 15);
this.label3.TabIndex = 5;
this.label3.Text = "Количество:";
//
// comboBoxReinforced
//
this.comboBoxReinforced.FormattingEnabled = true;
this.comboBoxReinforced.Location = new System.Drawing.Point(214, 44);
this.comboBoxReinforced.Name = "comboBoxReinforced";
this.comboBoxReinforced.Size = new System.Drawing.Size(222, 23);
this.comboBoxReinforced.TabIndex = 6;
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(215, 71);
this.numericUpDownCount.Maximum = new decimal(new int[] {
1410065408,
2,
0,
0});
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(221, 23);
this.numericUpDownCount.TabIndex = 7;
//
// buttonSave
//
this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSave.Location = new System.Drawing.Point(280, 123);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(75, 23);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Location = new System.Drawing.Point(361, 123);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(75, 23);
this.buttonCancel.TabIndex = 9;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormReinforcedShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(448, 158);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.comboBoxReinforced);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.label1);
this.Name = "FormReinforcedShop";
this.Text = "Пополнение магазина";
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboBoxShop;
private Label label1;
private Label label2;
private Label label3;
private ComboBox comboBoxReinforced;
private NumericUpDown numericUpDownCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,100 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections;
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 PrecastConcretePlantView
{
public partial class FormReinforcedShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _shopLogic;
private readonly IReinforcedLogic _reinforcedLogic;
private readonly List<ShopViewModel>? _listShops;
private readonly List<ReinforcedViewModel>? _listReinforcedies;
public FormReinforcedShop(ILogger<FormReinforcedShop> logger, IShopLogic shopLogic, IReinforcedLogic reinforcedLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_reinforcedLogic = reinforcedLogic;
_logger = logger;
_listShops = shopLogic.ReadList(null);
if (_listShops != null)
{
comboBoxShop.DisplayMember = "Name";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _listShops;
comboBoxShop.SelectedItem = null;
}
_listReinforcedies = reinforcedLogic.ReadList(null);
if (_listReinforcedies != null)
{
comboBoxReinforced.DisplayMember = "ReinforcedName";
comboBoxReinforced.ValueMember= "Id";
comboBoxReinforced.DataSource = _listReinforcedies;
comboBoxReinforced.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxReinforced.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Добавление изделия в магазин");
try
{
var reinforced = _reinforcedLogic.ReadElement(new()
{
Id = (int)comboBoxReinforced.SelectedValue
});
if (reinforced == null)
{
throw new Exception("Не найдено изделие. Дополнительная информация в логах.");
}
var resultOperation = _shopLogic.AddReinforced(
model: new() { Id = (int)comboBoxShop.SelectedValue },
reinforced: reinforced,
count: (int)numericUpDownCount.Value
);
if (!resultOperation)
{
throw new Exception("Ошибка при добавлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,92 @@
namespace PrecastConcretePlant
{
partial class FormReportGroupOrders
{
/// <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()
{
this.panel = new System.Windows.Forms.Panel();
this.buttonToPdf = new System.Windows.Forms.Button();
this.buttonMake = new System.Windows.Forms.Button();
this.panel.SuspendLayout();
this.SuspendLayout();
//
// panel
//
this.panel.Controls.Add(this.buttonToPdf);
this.panel.Controls.Add(this.buttonMake);
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(5, 4, 5, 4);
this.panel.Name = "panel";
this.panel.Size = new System.Drawing.Size(1178, 53);
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(1003, 11);
this.buttonToPdf.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.buttonToPdf.Name = "buttonToPdf";
this.buttonToPdf.Size = new System.Drawing.Size(159, 36);
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(544, 11);
this.buttonMake.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.buttonMake.Name = "buttonMake";
this.buttonMake.Size = new System.Drawing.Size(159, 36);
this.buttonMake.TabIndex = 4;
this.buttonMake.Text = "Сформировать";
this.buttonMake.UseVisualStyleBackColor = true;
this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click);
//
// FormReportGroupOrders
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1178, 863);
this.Controls.Add(this.panel);
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "FormReportGroupOrders";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Заказы";
this.panel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel;
private System.Windows.Forms.Button buttonToPdf;
private System.Windows.Forms.Button buttonMake;
}
}

View File

@ -0,0 +1,71 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
namespace PrecastConcretePlant
{
public partial class FormReportGroupOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportGroupOrders(ILogger<FormReportGroupOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportGroupOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonMake_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetGroupOrders();
var source = new ReportDataSource("DataSetOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Загрузка списка заказов на весь период по датам");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов на период");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonToPdf_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveGroupOrdersToPdfFile(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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,113 @@
namespace PrecastConcretePlant
{
partial class FormReportShopReinforcedies
{
/// <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();
buttonSaveToExcel = new Button();
ColumnShop = new DataGridViewTextBoxColumn();
ColumnPastry = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
((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.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShop, ColumnPastry, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 47);
dataGridView.Margin = new Padding(4, 3, 4, 3);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.Size = new Size(616, 510);
dataGridView.TabIndex = 0;
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(14, 14);
buttonSaveToExcel.Margin = new Padding(4, 3, 4, 3);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(186, 27);
buttonSaveToExcel.TabIndex = 1;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// ColumnShop
//
ColumnShop.HeaderText = "Магазин";
ColumnShop.Name = "ColumnShop";
ColumnShop.ReadOnly = true;
ColumnShop.Width = 200;
//
// ColumnPastry
//
ColumnPastry.HeaderText = "Изделие";
ColumnPastry.Name = "ColumnPastry";
ColumnPastry.ReadOnly = true;
ColumnPastry.Width = 200;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
//
// FormReportShopPastries
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(616, 557);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Margin = new Padding(4, 3, 4, 3);
Name = "FormReportShopPastries";
Text = "Изделия с компонентами";
Load += FormReportShopReinforcedies_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private System.Windows.Forms.DataGridView dataGridView;
private System.Windows.Forms.Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumnShop;
private DataGridViewTextBoxColumn ColumnPastry;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,80 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.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 PrecastConcretePlant
{
public partial class FormReportShopReinforcedies : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopReinforcedies(ILogger<FormReportShopReinforcedies> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportShopReinforcedies_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopReinforcedies();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Reinforcedies)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(new object[] { "Загруженность", "", Math.Round(elem.Workload * 100, 2).ToString() + "%" });
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.SaveShopReinforcedToExcelFile(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,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,125 @@
namespace PrecastConcretePlantView
{
partial class FormSellReinforced
{
/// <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()
{
this.ReinforcedLabel = new System.Windows.Forms.Label();
this.QuantityLabel = new System.Windows.Forms.Label();
this.ReindorcedСomboBox = new System.Windows.Forms.ComboBox();
this.SaveButton = new System.Windows.Forms.Button();
this.ButtonCancel = new System.Windows.Forms.Button();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// ReinforcedLabel
//
this.ReinforcedLabel.AutoSize = true;
this.ReinforcedLabel.Location = new System.Drawing.Point(14, 24);
this.ReinforcedLabel.Name = "ReinforcedLabel";
this.ReinforcedLabel.Size = new System.Drawing.Size(71, 20);
this.ReinforcedLabel.TabIndex = 0;
this.ReinforcedLabel.Text = "Изделие:";
//
// QuantityLabel
//
this.QuantityLabel.AutoSize = true;
this.QuantityLabel.Location = new System.Drawing.Point(14, 68);
this.QuantityLabel.Name = "QuantityLabel";
this.QuantityLabel.Size = new System.Drawing.Size(93, 20);
this.QuantityLabel.TabIndex = 1;
this.QuantityLabel.Text = "Количество:";
//
// ReindorcedСomboBox
//
this.ReindorcedСomboBox.FormattingEnabled = true;
this.ReindorcedСomboBox.Location = new System.Drawing.Point(101, 20);
this.ReindorcedСomboBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ReindorcedСomboBox.Name = "ReindorcedСomboBox";
this.ReindorcedСomboBox.Size = new System.Drawing.Size(210, 28);
this.ReindorcedСomboBox.TabIndex = 2;
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(82, 133);
this.SaveButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(111, 39);
this.SaveButton.TabIndex = 4;
this.SaveButton.Text = "Сохранить";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// ButtonCancel
//
this.ButtonCancel.Location = new System.Drawing.Point(200, 133);
this.ButtonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.ButtonCancel.Name = "ButtonCancel";
this.ButtonCancel.Size = new System.Drawing.Size(111, 39);
this.ButtonCancel.TabIndex = 5;
this.ButtonCancel.Text = "Отмена";
this.ButtonCancel.UseVisualStyleBackColor = true;
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(113, 68);
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(198, 27);
this.numericUpDownCount.TabIndex = 7;
//
// FormSellReinforced
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(325, 188);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.ButtonCancel);
this.Controls.Add(this.SaveButton);
this.Controls.Add(this.ReindorcedСomboBox);
this.Controls.Add(this.QuantityLabel);
this.Controls.Add(this.ReinforcedLabel);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormSellReinforced";
this.Text = "Продать Изделие";
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label ReinforcedLabel;
private Label QuantityLabel;
private ComboBox ReindorcedСomboBox;
private Button SaveButton;
private Button ButtonCancel;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -0,0 +1,97 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantBusinessLogic.BusinessLogic;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
namespace PrecastConcretePlantView
{
public partial class FormSellReinforced : Form
{
private readonly ILogger _logger;
private readonly IReinforcedLogic _logicReinforced;
private readonly IShopLogic _logicShop;
public FormSellReinforced(ILogger<FormSellReinforced> logger, IReinforcedLogic logicReinforced, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicReinforced = logicReinforced;
_logicShop = logicShop;
LoadData();
}
private void FormSellReinforced_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Loading reinforcediss for sale.");
try
{
var list = _logicReinforced.ReadList(null);
if (list != null)
{
ReindorcedСomboBox.DisplayMember = "ReinforcedName";
ReindorcedСomboBox.ValueMember = "Id";
ReindorcedСomboBox.DataSource = list;
ReindorcedСomboBox.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "List loading error.");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (ReindorcedСomboBox.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(numericUpDownCount.Text))
{
MessageBox.Show("Заполните количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа изделий");
try
{
var reinforced = _logicReinforced.ReadElement(new()
{
Id = (int)ReindorcedСomboBox.SelectedValue
});
if (reinforced == null)
{
throw new Exception("Изделие не найдено. Дополнительная информация в логах.");
}
var operationResult = _logicShop.SellReinforced(
reinforced: reinforced,
quantity: (int)numericUpDownCount.Value
);
if (!operationResult)
{
throw new Exception("Ошибка при продаже изделий. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения поездки");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,224 @@
namespace PrecastConcretePlantView
{
partial class FormShop
{
/// <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()
{
this.label1 = new System.Windows.Forms.Label();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.PastryName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Price = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.textBoxDateOpening = new System.Windows.Forms.DateTimePicker();
this.ReinforcedMaxCountLable = new System.Windows.Forms.Label();
this.VolumeNumericUpDown = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(14, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(150, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Название магазина:";
//
// comboBoxShop
//
this.comboBoxShop.Location = new System.Drawing.Point(14, 39);
this.comboBoxShop.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(138, 28);
this.comboBoxShop.TabIndex = 12;
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.PastryName,
this.Price,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(14, 155);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(666, 332);
this.dataGridView.TabIndex = 2;
//
// PastryName
//
this.PastryName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.PastryName.HeaderText = "Имя изделия";
this.PastryName.MinimumWidth = 6;
this.PastryName.Name = "PastryName";
//
// Price
//
this.Price.HeaderText = "Цена";
this.Price.MinimumWidth = 6;
this.Price.Name = "Price";
this.Price.Width = 125;
//
// Count
//
this.Count.HeaderText = "Количество";
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
this.Count.Width = 125;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(182, 12);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(124, 20);
this.label2.TabIndex = 3;
this.label2.Text = "Адрес магазина:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(441, 12);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(126, 20);
this.label3.TabIndex = 4;
this.label3.Text = "Время открытия:";
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(182, 36);
this.textBoxAddress.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(252, 27);
this.textBoxAddress.TabIndex = 5;
//
// buttonCancel
//
this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonCancel.Location = new System.Drawing.Point(562, 495);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(118, 31);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSave.Location = new System.Drawing.Point(418, 496);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(137, 29);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// textBoxDateOpening
//
this.textBoxDateOpening.Location = new System.Drawing.Point(441, 36);
this.textBoxDateOpening.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.textBoxDateOpening.Name = "textBoxDateOpening";
this.textBoxDateOpening.Size = new System.Drawing.Size(228, 27);
this.textBoxDateOpening.TabIndex = 9;
//
// ReinforcedMaxCountLable
//
this.ReinforcedMaxCountLable.AutoSize = true;
this.ReinforcedMaxCountLable.Location = new System.Drawing.Point(14, 71);
this.ReinforcedMaxCountLable.Name = "ReinforcedMaxCountLable";
this.ReinforcedMaxCountLable.Size = new System.Drawing.Size(177, 20);
this.ReinforcedMaxCountLable.TabIndex = 10;
this.ReinforcedMaxCountLable.Text = "Вместимость магазина: ";
//
// VolumeNumericUpDown
//
this.VolumeNumericUpDown.Location = new System.Drawing.Point(14, 95);
this.VolumeNumericUpDown.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.VolumeNumericUpDown.Name = "VolumeNumericUpDown";
this.VolumeNumericUpDown.Size = new System.Drawing.Size(161, 27);
this.VolumeNumericUpDown.TabIndex = 11;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(694, 540);
this.Controls.Add(this.VolumeNumericUpDown);
this.Controls.Add(this.ReinforcedMaxCountLable);
this.Controls.Add(this.textBoxDateOpening);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.label1);
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormShop";
this.Text = "Просмотр изделий магазина";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.VolumeNumericUpDown)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private ComboBox comboBoxShop;
private DataGridView dataGridView;
private Label label2;
private Label label3;
private TextBox textBoxAddress;
private Button buttonCancel;
private Button buttonSave;
private DataGridViewTextBoxColumn PastryName;
private DataGridViewTextBoxColumn Price;
private DataGridViewTextBoxColumn Count;
private DateTimePicker textBoxDateOpening;
private Label ReinforcedMaxCountLable;
private NumericUpDown VolumeNumericUpDown;
}
}

View File

@ -0,0 +1,132 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PrecastConcretePlantView
{
public partial class FormShop : Form
{
private readonly IShopLogic _logic;
private readonly ILogger _logger;
private int? _id;
private Dictionary<int, (IReinforcedModel, int)> _listShops;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_listShops = new();
_logic = logic;
}
private void LoadData(bool extendDate = true)
{
_logger.LogInformation("Загрузка изделий магазина");
try
{
if (_listShops != null)
{
dataGridView.Rows.Clear();
foreach (var elem in _listShops)
{
dataGridView.Rows.Add(new object[] { elem.Key, elem.Value.Item1.ReinforcedName, elem.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(comboBoxShop.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
Name = comboBoxShop.Text,
Address = textBoxAddress.Text,
DateOpening = textBoxDateOpening.Value.Date,
ReinforcedMaxCount = (int)VolumeNumericUpDown.Value
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel
{
Id = _id.Value
});
if (view != null)
{
comboBoxShop.Text = view.Name;
textBoxAddress.Text = view.Address;
textBoxDateOpening.Text = view.DateOpening.ToString();
VolumeNumericUpDown.Value = view.ReinforcedMaxCount;
_listShops = view.ShopReinforcedies ?? new Dictionary<int, (IReinforcedModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,78 @@
<root>
<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="ReinforcedName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Price.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="PastryName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Price.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,121 @@
namespace PrecastConcretePlantView
{
partial class FormShops
{
/// <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()
{
this.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// buttonRef
//
this.buttonRef.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRef.Location = new System.Drawing.Point(685, 202);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(90, 37);
this.buttonRef.TabIndex = 14;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// buttonDel
//
this.buttonDel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDel.Location = new System.Drawing.Point(685, 151);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(90, 33);
this.buttonDel.TabIndex = 13;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUpd.Location = new System.Drawing.Point(685, 102);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(90, 34);
this.buttonUpd.TabIndex = 12;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonAdd.Location = new System.Drawing.Point(685, 57);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(90, 30);
this.buttonAdd.TabIndex = 11;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(540, 379);
this.dataGridView.TabIndex = 10;
//
// FormViewShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(787, 403);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormViewShops";
this.Text = "Просмотр магазинов";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,106 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantView;
namespace PrecastConcretePlantView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopReinforcedies"].Visible = false;
dataGridView.Columns["Name"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление магазина");
try
{
if (!_logic.Delete(new ShopBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -7,6 +7,7 @@ using NLog.Extensions.Logging;
using PrecastConcretePlantDatabaseImplement.Implements;
using PrecastConcretePlantBusinessLogic.OfficePackage.Implements;
using PrecastConcretePlantBusinessLogic.OfficePackage;
using PrecastConcretePlant;
namespace PrecastConcretePlantView
{
@ -37,6 +38,7 @@ namespace PrecastConcretePlantView
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IReinforcedStorage, ReinforcedStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IReinforcedLogic, ReinforcedLogic>();
@ -44,9 +46,12 @@ namespace PrecastConcretePlantView
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>();
services.AddTransient<FormClients>();
services.AddTransient<FormComponent>();
@ -55,7 +60,13 @@ namespace PrecastConcretePlantView
services.AddTransient<FormReinforced>();
services.AddTransient<FormReinforcedComponent>();
services.AddTransient<FormReinforceds>();
services.AddTransient<FormReinforcedShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSellReinforced>();
services.AddTransient<FormReportShopReinforcedies>();
services.AddTransient<FormReportReinforcedComponents>();
services.AddTransient<FormReportGroupOrders>();
services.AddTransient<FormReportOrder>();
services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>();

View File

@ -0,0 +1,463 @@
<?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="ConfectioneryContractsViewModels">
<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>ConfectioneryContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<Field Name="Id">
<DataField>Id</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="Date">
<DataField>Date</DataField>
<rd:TypeName>System.DateTime</rd:TypeName>
</Field>
<Field Name="Count">
<DataField>Count</DataField>
<rd:TypeName>System.Int32</rd:TypeName>
</Field>
<Field Name="Sum">
<DataField>Sum</DataField>
<rd:TypeName>System.Double</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>ConfectioneryContracts.ViewModels</rd:DataSetName>
<rd:TableName>ReportOrdersViewModel</rd:TableName>
<rd:ObjectDataSourceType>ConfectioneryContracts.ViewModels.ReportOrdersViewModel, ConfectioneryContracts, 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>12.40104cm</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>12.40104cm</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>3.21438cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.53188cm</Width>
</TablixColumn>
<TablixColumn>
<Width>4.35209cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<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>
</TablixCells>
</TablixRow>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="Date">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Date.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Date</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="Count">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Fields!Count.Value</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<rd:DefaultName>Count</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>
</TablixCells>
</TablixRow>
</TablixRows>
</TablixBody>
<TablixColumnHierarchy>
<TablixMembers>
<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>11.09835cm</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>6.6508cm</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>9.1508cm</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>12.40104cm</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

@ -18,10 +18,14 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IReinforcedStorage _reinforcedStorage;
private readonly IShopLogic _shopLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IReinforcedStorage reinforcedStorage, IShopLogic shopLogic)
{
_logger = logger;
_shopLogic = shopLogic;
_reinforcedStorage = reinforcedStorage;
_orderStorage = orderStorage;
}
@ -30,13 +34,13 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
throw new ArgumentException(
$"Статус заказа должен быть {OrderStatus.Неизвестен}", nameof(model));
}
model.Status = OrderStatus.Принят;
model.DateCreate = DateTime.Now;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
@ -44,6 +48,9 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus orderStatus)
public bool TakeOrderInWork(OrderBindingModel model) => SetOrderStatus(model, OrderStatus.Выполняется);
public bool DeliveryOrder(OrderBindingModel model) => SetOrderStatus(model, OrderStatus.Выдан);
public bool FinishOrder(OrderBindingModel model)
{
var vmodel = _orderStorage.GetElement(new() { Id = model.Id });
if (vmodel == null)
@ -56,6 +63,19 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
$"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {orderStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}");
model.DateImplement = DateTime.Now;
return SetOrderStatus(model, OrderStatus.Готов);
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. OrderName.Id:{ Id} ", model?.Id);
var list = (model == null) ? _orderStorage.GetFullList() :
_orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
model.Status = orderStatus;
model.DateCreate = vmodel.DateCreate;
@ -73,8 +93,11 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
}
return true;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool TakeOrderInWork(OrderBindingModel model)
private bool CheckModel(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
@ -96,36 +119,62 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
_logger.LogInformation("Order. OrderID:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.ReinforcedId < 0)
{
throw new ArgumentNullException("Некорректный идентификатор документа", nameof(model.ReinforcedId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество документов в заказе должно быть больше 0", nameof(model.Count));
throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. ReinforcedId: { ReinforcedId}", model.Id, model.Sum, model.ReinforcedId);
if (model.DateCreate > model.DateImplement)
{
throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement));
}
return true;
}
private bool SetOrderStatus(OrderBindingModel model, OrderStatus orderStatus)
{
var vmodel = _orderStorage.GetElement(new() { Id = model.Id });
if (vmodel == null)
{
throw new ArgumentNullException(nameof(model));
}
if ((int)vmodel.Status + 1 != (int)orderStatus)
{
throw new ArgumentException($"Попытка перевести заказ не в следующий статус: " +
$"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {orderStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}",
nameof(vmodel));
}
if (orderStatus == OrderStatus.Готов)
{
var vreinforced = _reinforcedStorage.GetElement(new() { Id = vmodel.ReinforcedId });
if (vreinforced == null || !_shopLogic.AddReinforcediesInShops(vreinforced, vmodel.Count))
{
throw new Exception($"Не удалось заполнить магазины изделием '{vreinforced?.ReinforcedName ?? string.Empty}' из заказа {vmodel.Id}");
}
}
model.Status = orderStatus;
model.DateCreate = vmodel.DateCreate;
if (model.DateImplement == null)
model.DateImplement = vmodel.DateImplement;
model.ReinforcedId = vmodel.ReinforcedId;
model.Sum = vmodel.Sum;
model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{

View File

@ -17,16 +17,18 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
{
private readonly IComponentStorage _componentStorage;
private readonly IReinforcedStorage _reinforcedStorage;
private readonly IShopStorage _shopStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IReinforcedStorage reinforcedStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
public ReportLogic(IReinforcedStorage reinforcedStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_reinforcedStorage = reinforcedStorage;
_componentStorage = componentStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_shopStorage = shopStorage;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
@ -34,9 +36,9 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
public List<ReportReinforcedComponentViewModel> GetReinforcedComponents()
{
var components = _componentStorage.GetFullList();
var reinforcedies = _reinforcedStorage.GetFullList();
var reinforceds = _reinforcedStorage.GetFullList();
var list = new List<ReportReinforcedComponentViewModel>();
foreach (var reinforced in reinforcedies)
foreach (var reinforced in reinforceds)
{
var record = new ReportReinforcedComponentViewModel
{
@ -75,7 +77,7 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
.ToList();
}
public void SaveReinforcediesToWordFile(ReportBindingModel model)
public void SaveReinforcedsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
@ -86,7 +88,7 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
}
public void SaveReinforcedComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
_saveToExcel.CreateReportReinforced(new ExcelInfoReinforced
{
FileName = model.FileName,
Title = "Список документов",
@ -96,7 +98,7 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
_saveToPdf.CreateReportDateDoc(new PdfInfoOrders
{
FileName = model.FileName,
Title = "Список заказов",
@ -106,5 +108,69 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
});
}
public List<ReportShopReinforcedViewModel> GetShopReinforcedies()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopReinforcedViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopReinforcedViewModel
{
ShopName = shop.Name,
Reinforcedies = new(),
TotalCount = 0
};
foreach (var reinforced in shop.ShopReinforcedies)
{
record.Reinforcedies.Add(new(reinforced.Value.Item1.ReinforcedName, reinforced.Value.Item2));
record.TotalCount += reinforced.Value.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportGroupOrdersViewModel> GetGroupOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportGroupOrdersViewModel
{
Date = x.Key,
Count = x.Count(),
Sum = x.Sum(y => y.Sum)
}).ToList();
}
public void SaveShopsTableToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDocTable(new WordInfoTable
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveGroupOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateReportDateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Заказы по датам",
DateOrders = GetGroupOrders()
});
}
public void SaveShopReinforcedToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReportShop(new ExcelInfo
{
FileName = model.FileName,
Title = "Список магазинов",
ShopReinforcedies = GetShopReinforcedies()
});
}
}
}

View File

@ -0,0 +1,228 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.BusinessLogic
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. Name:{Name}.Id:{ Id} ",
model?.Name, model?.Id);
var list = (model == null) ? _shopStorage.GetFullList() :
_shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Name:{Name}.Id:{ Id}",
model.Name, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
model.ShopReinforcedies = new();
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool SellReinforced(IReinforcedModel reinforced, int count)
{
return _shopStorage.SellReinforced(reinforced, count);
}
public bool Update(ShopBindingModel model)
{
CheckModel(model, false);
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия магазина",
nameof(model.Name));
}
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет названия магазина",
nameof(model.Name));
}
if (model.ReinforcedMaxCount < 0)
{
throw new ArgumentException("Максимальное количество изделий в магазине не может быть меньше нуля", nameof(model.ReinforcedMaxCount));
}
_logger.LogInformation("Shop. Name:{0}.Address:{1}. Id: {2}",
model.Name, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id && element.Name == model.Name)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool AddReinforced(ShopSearchModel model, IReinforcedModel reinforced, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddReinforced. Name:{Name}.Id:{ Id}", model.Name, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("AddReinforced element not found");
return false;
}
if (element.ReinforcedMaxCount - element.ShopReinforcedies.Select(x => x.Value.Item2).Sum() < count)
{
throw new ArgumentNullException("Магазин переполнен", nameof(count));
}
_logger.LogInformation("AddReinforced find. Id:{Id}", element.Id);
if (element.ShopReinforcedies.TryGetValue(reinforced.Id, out var pair))
{
element.ShopReinforcedies[reinforced.Id] = (reinforced, count + pair.Item2);
_logger.LogInformation("AddReinforced. Added {count} {reinforced} to '{Name}' shop", count, reinforced.ReinforcedName, element.Name);
}
else
{
element.ShopReinforcedies[reinforced.Id] = (reinforced, count);
_logger.LogInformation("AddReinforced. Added {count} new reinforced {reinforced} to '{Name}' shop", count, reinforced.ReinforcedName, element.Name);
}
_shopStorage.Update(new()
{
Id = element.Id,
Address = element.Address,
Name = element.Name,
DateOpening = element.DateOpening,
ReinforcedMaxCount = element.ReinforcedMaxCount,
ShopReinforcedies = element.ShopReinforcedies,
});
return true;
}
public bool AddReinforcediesInShops(IReinforcedModel reinforced, int count)
{
if (reinforced == null)
{
throw new ArgumentNullException(nameof(reinforced));
}
if (count <= 0)
{
throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(count));
}
var freePlaces = _shopStorage.GetFullList()
.Select(x => x.ReinforcedMaxCount - x.ShopReinforcedies
.Select(p => p.Value.Item2).Sum()).Sum() - count;
if (freePlaces < 0)
{
_logger.LogInformation("AddReinforced. Failed to add reinforced to shop. It's full.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
var temp = Math.Min(count, shop.ReinforcedMaxCount - shop.ShopReinforcedies.Select(x => x.Value.Item2).Sum());
if (temp <= 0)
{
continue;
}
if (!AddReinforced(new() { Id = shop.Id }, reinforced, temp))
{
_logger.LogWarning("An error occurred while adding reinforced to shops");
return false;
}
count -= temp;
if (count == 0)
{
return true;
}
}
return true;
}
}
}

View File

@ -10,9 +10,10 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateReport(ExcelInfo info)
public void CreateReportShop(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
@ -20,11 +21,99 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var pc in info.ShopReinforcedies)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = pc.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Shop, Count) in pc.Reinforcedies)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Shop,
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.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = "Загруженность",
StyleInfo = ExcelStyleInfoType.Text
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = pc.Workload.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
public void CreateReportReinforced(ExcelInfoReinforced info)
{
CreateExcel(new() { FileName = info.FileName });
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.ReinforcedComponents)
{
@ -36,15 +125,17 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Component, Count) in pc.Components)
foreach (var (Reinforced, Count) in pc.Components)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Component,
Text = Reinforced,
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
@ -52,8 +143,10 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
Text = Count.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder
});
rowIndex++;
}
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
@ -70,12 +163,32 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
});
rowIndex++;
}
SaveExcel(info);
SaveExcel(new());
}
/// <summary>
/// Создание excel-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateExcel(ExcelInfo info);
/// <summary>
/// Добавляем новую ячейку в лист
/// </summary>
/// <param name="cellParameters"></param>
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
/// <summary>
/// Объединение ячеек
/// </summary>
/// <param name="mergeParameters"></param>
protected abstract void MergeCells(ExcelMergeParameters excelParams);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -11,6 +11,40 @@ namespace PrecastConcretePlantBusinessLogic.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 = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "4cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Статус заказа", "Сумма" },
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.ReinforcedName, Convert.ToString(order.Status), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
SavePdf(info);
}
public void CreateReportDateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
@ -19,41 +53,61 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с{info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "4cm" });
CreateTable(new List<string> { "3cm", "3cm", "7cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер", "Дата заказа", "Изделие", "Сумма", "Статус" },
Texts = new List<string> { "Дата", "Количество", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.Orders)
foreach (var order in info.DateOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.ReinforcedName, order.Sum.ToString(), order.Status },
Texts = new List<string> { order.Date.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph
{
Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t",
Text = $"Итого: {info.DateOrders.Sum(x => x.Sum)}\t",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
SavePdf(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -10,9 +10,10 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateDoc(WordInfo info)
public void CreateDocTable(WordInfoTable info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
@ -22,14 +23,48 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
JustificationType = WordJustificationType.Center
}
});
CreateTable(new()
{
("Название", 3000),
("Дата", null),
("Адрес открытия", 4500),
},
info.Shops
.Select(x => new List<string>
{
x.Name,
Convert.ToString(x.DateOpening),
x.Address,
})
.ToList());
SaveWord(info);
}
public void CreateDoc(WordInfo info)
{
CreateWord(new() { FileName = info.FileName });
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 reinforced in info.Reinforcedies)
{
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)>
{(reinforced.ReinforcedName + " - ", new WordTextProperties { Size = "24", Bold = true}),
(reinforced.Price.ToString(), new WordTextProperties { Size = "24", })},
{
(reinforced.ReinforcedName , new WordTextProperties { Size = "24", Bold = true}),
(" - цена: " + reinforced.Price.ToString(), new WordTextProperties { Size = "24" })
},
TextProperties = new WordTextProperties
{
Size = "24",
@ -37,10 +72,15 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage
}
});
}
SaveWord(info);
SaveWord(new());
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateWord(WordInfoTable info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
protected abstract void CreateTable(List<(string, int?)> nameAndWidthColumns, List<List<string>> rows);
protected abstract void SaveWord(WordInfoTable info);
}
}

View File

@ -11,6 +11,6 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportReinforcedComponentViewModel> ReinforcedComponents { get; set; } = new();
public List<ReportShopReinforcedViewModel> ShopReinforcedies { get; set; } = new();
}
}

View File

@ -0,0 +1,20 @@
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
{
public class ExcelInfoReinforced
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportReinforcedComponentViewModel> ReinforcedComponents
{
get;
set;
} = new();
}
}

View File

@ -14,5 +14,7 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportGroupOrdersViewModel> DateOrders { get; set; } = new();
}
}

View File

@ -0,0 +1,30 @@
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
{
public class PdfInfoOrders
{
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 static implicit operator PdfInfo(PdfInfoOrders orders)
{
return new PdfInfo()
{
DateFrom = orders.DateFrom,
DateTo = orders.DateTo,
FileName = orders.FileName,
Title = orders.Title
};
}
public List<ReportGroupOrdersViewModel> DateOrders { get; set; } = new();
}
}

View File

@ -12,5 +12,6 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReinforcedViewModel> Reinforcedies { get; set; } = new();
public List<ReinforcedViewModel> Shops { get; set; } = new();
}
}

View File

@ -0,0 +1,16 @@
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
{
public class WordInfoTable
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ShopViewModel> Shops { get; set; } = new();
}
}

View File

@ -16,10 +16,12 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment
GetParagraphAlignment(PdfParagraphAlignmentType type)
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
@ -29,21 +31,29 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
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 CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
@ -55,6 +65,7 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
@ -62,11 +73,13 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
@ -77,19 +90,24 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
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)

View File

@ -3,26 +3,22 @@ using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using PrecastConcretePlantBusinessLogic.OfficePackage.HelperEnums;
using PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
using Document = DocumentFormat.OpenXml.Wordprocessing.Document;
using Text = DocumentFormat.OpenXml.Wordprocessing.Text;
namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private static JustificationValues
GetJustificationValues(WordJustificationType type)
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
@ -32,54 +28,68 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
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)
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
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
});
paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size });
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfo info)
protected override void CreateWord(WordInfoTable 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 CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
@ -89,9 +99,11 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
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)
@ -99,24 +111,66 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.Implements
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space = SpaceProcessingModeValues.Preserve
});
docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
protected override void SaveWord(WordInfoTable info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Close();
}
private static TableCell GetTableCell(string text, int? widthCell = null)
{
TableCell cell = new(new Paragraph(new Run(new Text(text))));
if (widthCell != null)
{
cell.Append(new TableCellProperties()
{
TableCellWidth = new() { Width = widthCell.ToString() }
});
}
return cell;
}
protected override void CreateTable(List<(string, int?)> nameAndWidthColumns, List<List<string>> rows)
{
if (_docBody == null)
{
return;
}
Table table = new();
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.BasicBlackDashes), Size = 3 }
)
);
table.AppendChild(tblProp);
table.Append(new TableRow(nameAndWidthColumns.Select(x => GetTableCell(x.Item1, x.Item2))));
table.Append(rows.Select(x => new TableRow(x.Select(y => GetTableCell(y)))));
_docBody.Append(table);
}
}
}

View File

@ -0,0 +1,24 @@
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public string Name { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public int ReinforcedMaxCount { get; set; }
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies { get; set; } = new();
public int Id { get; set; }
}
}

View File

@ -10,10 +10,15 @@ namespace PrecastConcretePlantContracts.BusinessLogicsContracts
{
public interface IReportLogic
{
List<ReportShopReinforcedViewModel> GetShopReinforcedies();
List<ReportReinforcedComponentViewModel> GetReinforcedComponents();
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
void SaveReinforcediesToWordFile(ReportBindingModel model);
List<ReportGroupOrdersViewModel> GetGroupOrders();
void SaveReinforcedsToWordFile(ReportBindingModel model);
void SaveReinforcedComponentToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
void SaveShopsTableToWordFile(ReportBindingModel model);
void SaveShopReinforcedToExcelFile(ReportBindingModel model);
void SaveGroupOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,25 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddReinforced(ShopSearchModel model, IReinforcedModel reinforced, int count);
bool AddReinforcediesInShops(IReinforcedModel reinforced, int quantity);
bool SellReinforced(IReinforcedModel reinforced, int quantity);
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
}
}

View File

@ -0,0 +1,23 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellReinforced(IReinforcedModel model, int quantity);
}
}

View File

@ -19,6 +19,6 @@ namespace PrecastConcretePlantContracts.ViewModels
{
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 PrecastConcretePlantContracts.ViewModels
{
public class ReportGroupOrdersViewModel
{
public DateTime Date { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.ViewModels
{
public class ReportShopReinforcedViewModel
{
public string ShopName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<Tuple<string, int>> Reinforcedies { get; set; } = new();
public double Workload { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
[DisplayName("Название магазина")]
public string Name { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[DisplayName("Время открытия")]
public DateTime DateOpening { get; set; }
[DisplayName("Вместимость магазина")]
public int ReinforcedMaxCount { get; set; }
public Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies { get; set; } = new();
public int Id { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDataModels.Models
{
public interface IShopModel : IId
{
string Name { get; }
string Address { get; }
public int ReinforcedMaxCount { get; }
DateTime DateOpening { get; }
Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies { get; }
}
}

View File

@ -0,0 +1,146 @@
using Microsoft.EntityFrameworkCore;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDatabaseImplement.Models;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public List<ShopViewModel> GetFullList()
{
using var context = new PrecastConcretePlantDataBase();
return context.Shops
.Include(x => x.Reinforcedies)
.ThenInclude(x => x.Reinforced)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new PrecastConcretePlantDataBase();
return context.Shops
.Include(x => x.Reinforcedies)
.ThenInclude(x => x.Reinforced)
.Where(x => x.Name.Contains(model.Name))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new PrecastConcretePlantDataBase();
return context.Shops
.Include(x => x.Reinforcedies)
.ThenInclude(x => x.Reinforced)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new PrecastConcretePlantDataBase();
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new PrecastConcretePlantDataBase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
shop.UpdateReinforcedies(context, model);
context.SaveChanges();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new PrecastConcretePlantDataBase();
var element = context.Shops
.Include(x => x.Reinforcedies)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public bool SellReinforced(IReinforcedModel model, int count)
{
using var context = new PrecastConcretePlantDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var shops = context.ShopReinforcedies
.Include(x => x.Shop)
.ToList()
.Where(rec => rec.ReinforcedId == model.Id);
if (shops == null)
{
return false;
}
foreach (var shop in shops)
{
if (shop.Count < count)
{
shop.Count = 0;
count -= shop.Count;
}
else
{
shop.Count = shop.Count - count;
count -= count;
}
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -1,257 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using PrecastConcretePlantDatabaseImplement;
#nullable disable
namespace PrecastConcretePlantDatabaseImplement.Migrations
{
[DbContext(typeof(PrecastConcretePlantDataBase))]
[Migration("20230409171556_InitLab6")]
partial class InitLab6
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ReinforcedId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ReinforcedId");
b.ToTable("Orders");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("float");
b.Property<string>("ReinforcedName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Reinforcedies");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ReinforcedId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ReinforcedId");
b.ToTable("ReinforcedComponents");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced")
.WithMany("Orders")
.HasForeignKey("ReinforcedId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Reinforced");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ReinforcedComponent", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Component", "Component")
.WithMany("ReinforcedComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced")
.WithMany("Components")
.HasForeignKey("ReinforcedId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Reinforced");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Component", b =>
{
b.Navigation("ReinforcedComponents");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Reinforced", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,185 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace PrecastConcretePlantDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitLab6 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClientFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Reinforcedies",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ReinforcedName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Reinforcedies", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ReinforcedId = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Reinforcedies_ReinforcedId",
column: x => x.ReinforcedId,
principalTable: "Reinforcedies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ReinforcedComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ReinforcedId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ReinforcedComponents", x => x.Id);
table.ForeignKey(
name: "FK_ReinforcedComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ReinforcedComponents_Reinforcedies_ReinforcedId",
column: x => x.ReinforcedId,
principalTable: "Reinforcedies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ReinforcedId",
table: "Orders",
column: "ReinforcedId");
migrationBuilder.CreateIndex(
name: "IX_ReinforcedComponents_ComponentId",
table: "ReinforcedComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ReinforcedComponents_ReinforcedId",
table: "ReinforcedComponents",
column: "ReinforcedId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ReinforcedComponents");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Reinforcedies");
}
}
}

View File

@ -183,6 +183,59 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.ToTable("ReinforcedComponents");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpening")
.HasColumnType("datetime2");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("ReinforcedMaxCount")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ShopReinforced", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ReinforcedId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ReinforcedId");
b.HasIndex("ShopId");
b.ToTable("ShopReinforcedies");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
@ -227,6 +280,25 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.Navigation("Reinforced");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.ShopReinforced", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Reinforced", "Reinforced")
.WithMany()
.HasForeignKey("ReinforcedId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Shop", "Shop")
.WithMany("Reinforcedies")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Reinforced");
b.Navigation("Shop");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
@ -248,6 +320,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Reinforcedies");
});
#pragma warning restore 612, 618
}
}

View File

@ -0,0 +1,107 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpening { get; set; }
[Required]
public int ReinforcedMaxCount { get; set; }
private Dictionary<int, (IReinforcedModel, int)>? _shopReinforcedies = null;
[NotMapped]
public Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies
{
get
{
if (_shopReinforcedies == null)
{
_shopReinforcedies = Reinforcedies.ToDictionary(recST => recST.ReinforcedId, recST => (recST.Reinforced as IReinforcedModel, recST.Count));
}
return _shopReinforcedies;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopReinforced> Reinforcedies { get; set; } = new();
public static Shop Create(PrecastConcretePlantDataBase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
DateOpening = model.DateOpening,
ReinforcedMaxCount = model.ReinforcedMaxCount,
Reinforcedies = model.ShopReinforcedies.Select(x => new ShopReinforced
{
Reinforced = context.Reinforcedies.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
DateOpening = model.DateOpening;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
DateOpening = DateOpening,
ReinforcedMaxCount = ReinforcedMaxCount,
ShopReinforcedies = ShopReinforcedies
};
public void UpdateReinforcedies(PrecastConcretePlantDataBase context, ShopBindingModel model)
{
var shopReinforcedies = context.ShopReinforcedies
.Where(rec => rec.ShopId == model.Id)
.ToList();
if (shopReinforcedies != null && shopReinforcedies.Count > 0)
{
context.ShopReinforcedies
.RemoveRange(shopReinforcedies
.Where(rec => !model.ShopReinforcedies
.ContainsKey(rec.ReinforcedId)));
foreach (var updateReinforced in shopReinforcedies.Where(x => model.ShopReinforcedies.ContainsKey(x.ReinforcedId)))
{
updateReinforced.Count = model.ShopReinforcedies[updateReinforced.ReinforcedId].Item2;
model.ShopReinforcedies.Remove(updateReinforced.ReinforcedId);
}
}
var shop = context.Shops.First(x => x.Id == model.Id);
shop.Reinforcedies.AddRange(model.ShopReinforcedies.Select(x => new ShopReinforced
{
Reinforced = context.Reinforcedies.First(y => y.Id == x.Key),
Count = x.Value.Item2,
}).Except(shopReinforcedies ?? new()));
context.SaveChanges();
_shopReinforcedies = null;
}
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement.Models
{
public class ShopReinforced
{
public int Id { get; set; }
[Required]
public int ReinforcedId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Reinforced Reinforced { get; set; } = new();
}
}

View File

@ -0,0 +1,29 @@
using Microsoft.EntityFrameworkCore;
using PrecastConcretePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement
{
public class PrecastConcretePlantDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-V0ON61E\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFullHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Reinforced> Reinforcedies { set; get; }
public virtual DbSet<ReinforcedComponent> ReinforcedComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopReinforced> ShopReinforcedies { set; get; }
public virtual DbSet<Client> Clients { set; get; }
}
}

View File

@ -1,29 +0,0 @@
using Microsoft.EntityFrameworkCore;
using PrecastConcretePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement
{
public class PrecastConcretePlantDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=MAKSIM\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFull;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Reinforced> Reinforcedies { set; get; }
public virtual DbSet<ReinforcedComponent> ReinforcedComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -17,11 +17,14 @@ namespace PrecastConcretePlantFileImplement
private readonly string ReinforcedFileName = "Reinforced.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Reinforced> Reinforcedies { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public List<Reinforced> Reinforceds { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -38,6 +41,7 @@ namespace PrecastConcretePlantFileImplement
=> x.GetXElement);
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
@ -47,6 +51,7 @@ namespace PrecastConcretePlantFileImplement
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,112 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using PrecastConcretePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Shops.Remove(element);
source.SaveShops();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Name) && x.Name ==
model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
return source.Shops.Where(x => x.Name.Contains(model.Name)).Select(x => x.GetViewModel).ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public bool SellReinforced(IReinforcedModel model, int quantity)
{
if (source.Shops.Select(x => x.ShopReinforcedies.FirstOrDefault(y => y.Key == model.Id).Value.Item2).Sum() < quantity)
{
return false;
}
foreach (var shop in source.Shops.Where(x => x.ShopReinforcedies.ContainsKey(model.Id)))
{
int QuantityInCurrentShop = shop.ShopReinforcedies[model.Id].Item2;
if (QuantityInCurrentShop <= quantity)
{
shop.ShopReinforcedies.Remove(model.Id);
quantity -= QuantityInCurrentShop;
}
else
{
shop.ShopReinforcedies[model.Id] = (shop.ShopReinforcedies[model.Id].Item1, QuantityInCurrentShop - quantity);
quantity = 0;
}
if (quantity == 0)
{
return true;
}
}
return false;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
}
}

View File

@ -0,0 +1,107 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PrecastConcretePlantFileImplement.Models
{
public class Shop : IShopModel
{
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, int> Reinforcedies { get; private set; } = new();
public Dictionary<int, (IReinforcedModel, int)> _shopReinforcedies = null;
public Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies
{
get
{
if (_shopReinforcedies == null)
{
var source = DataFileSingleton.GetInstance();
_shopReinforcedies = Reinforcedies.ToDictionary(x => x.Key, y => ((source.Reinforceds.FirstOrDefault(z => z.Id == y.Key) as IReinforcedModel)!, y.Value));
}
return _shopReinforcedies;
}
}
public int Id { get; private set; }
public int ReinforcedMaxCount { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
ReinforcedMaxCount = model.ReinforcedMaxCount,
DateOpening = model.DateOpening,
Reinforcedies = model.ShopReinforcedies.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Name = element.Element("Name")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
ReinforcedMaxCount = Convert.ToInt32(element.Element("ReinforcedMaxCount")!.Value),
Reinforcedies = element.Element("ShopReinforcedies")!.Elements("Reinforced").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
DateOpening = model.DateOpening;
ReinforcedMaxCount = model.ReinforcedMaxCount;
Reinforcedies = model.ShopReinforcedies.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopReinforcedies = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
ShopReinforcedies = ShopReinforcedies,
DateOpening = DateOpening,
ReinforcedMaxCount = ReinforcedMaxCount,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening),
new XElement("ReinforcedMaxCount", ReinforcedMaxCount),
new XElement("ShopReinforcedies", Reinforcedies
.Select(x => new XElement("Reinforced",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
).ToArray()));
}
}

View File

@ -15,6 +15,8 @@ namespace PrecastConcretePlantListImplement
public List<Reinforced> Reinforcedies { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<Reinforced> Reinforceds { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
@ -22,6 +24,8 @@ namespace PrecastConcretePlantListImplement
Reinforcedies = new List<Reinforced>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Reinforceds = new List<Reinforced>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,117 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using PrecastConcretePlantListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool SellReinforced(IReinforcedModel model, int quantity)
{
throw new NotImplementedException();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.Name) &&
shop.Name == model.Name) ||
(model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.Name.Contains(model.Name ?? string.Empty))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,60 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantListImplement.Models
{
public class Shop : IShopModel
{
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, (IReinforcedModel, int)> ShopReinforcedies { get; private set; } = new();
public int Id { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
DateOpening = model.DateOpening,
ShopReinforcedies = new()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
DateOpening = model.DateOpening;
ShopReinforcedies = model.ShopReinforcedies;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
ShopReinforcedies = ShopReinforcedies,
DateOpening = DateOpening,
};
public int ReinforcedMaxCount => throw new NotImplementedException();
}
}

View File

@ -0,0 +1,92 @@
using Microsoft.AspNetCore.Mvc;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
namespace PrecastConcretePlantRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ShopController : Controller
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public ShopController(IShopLogic logic, ILogger<ShopController> logger)
{
_logger = logger;
_logic = logic;
}
[HttpGet]
public List<ShopViewModel>? GetShops()
{
try
{
return _logic.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpGet]
public Tuple<ShopViewModel, IEnumerable<ReinforcedViewModel>, IEnumerable<int>>? GetShopWithReinforcedies(int id)
{
try
{
var shop = _logic.ReadElement(new() { Id = id });
if (shop == null)
{
return null;
}
return Tuple.Create(shop,
shop.ShopReinforcedies.Select(x => new ReinforcedViewModel()
{
Id = x.Value.Item1.Id,
Price = x.Value.Item1.Price,
ReinforcedName = x.Value.Item1.ReinforcedName,
}),
shop.ShopReinforcedies.Select(x => x.Value.Item2));
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения магазина");
throw;
}
}
[HttpPost]
public void CRUDShop(Action action)
{
try
{
action.Invoke();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка операции CRUD - {operation} с магазином", action.Method.Name);
throw;
}
}
[HttpPost]
public void UpdateShop(ShopBindingModel model) => CRUDShop(() => _logic.Update(model));
[HttpPost]
public void CreateShop(ShopBindingModel model) => CRUDShop(() => _logic.Create(model));
[HttpPost]
public void DeleteShop(ShopBindingModel model) => CRUDShop(() => _logic.Delete(model));
[HttpPost]
public void AddReinforcedInShop(Tuple<ShopSearchModel, ReinforcedViewModel, int> countReinforcedForShop)
{
CRUDShop(() => _logic.AddReinforced(countReinforcedForShop.Item1, countReinforcedForShop.Item2, countReinforcedForShop.Item3));
}
}
}

View File

@ -12,10 +12,13 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IReinforcedStorage, ReinforcedStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IReinforcedLogic, ReinforcedLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>

View File

@ -0,0 +1,51 @@
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace PrecastConcretePlantShopApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static bool IsAccessAllowed { get; set; } = false;
public static string AccessPassword { get; private set; } = string.Empty;
public static void Connect(IConfiguration configuration)
{
AccessPassword = configuration["PasswordToAccessShop"];
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -0,0 +1,199 @@
using Microsoft.AspNetCore.Mvc;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantShopApp.Models;
using System.Diagnostics;
namespace PrecastConcretePlantShopApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (APIClient.IsAccessAllowed is false)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<ShopViewModel>>($"api/shop/getshops"));
}
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.IsAccessAllowed is false)
{
return Redirect("~/Home/Enter");
}
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string password)
{
if (string.IsNullOrEmpty(password))
{
throw new Exception("Введите пароль");
}
APIClient.IsAccessAllowed = password.Equals(APIClient.AccessPassword);
if (APIClient.IsAccessAllowed is false)
{
throw new Exception("Неверный пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public void Create(string name, string address, int maxCount)
{
if (APIClient.IsAccessAllowed is false)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (maxCount <= 0)
{
throw new Exception("Количество и сумма должны быть больше 0");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception($"Имя магазина не должно быть пустым");
}
if (string.IsNullOrEmpty(address))
{
throw new Exception($"Адрес магазина не должен быть пустым");
}
APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
{
Name = name,
Address = address,
ReinforcedMaxCount = maxCount,
});
Response.Redirect("Index");
}
[HttpGet]
public Tuple<string, ShopViewModel>? GetTableReinforcediesFromShop(int shop)
{
var result = APIClient.GetRequest<Tuple<ShopViewModel, IEnumerable<ReinforcedViewModel>, IEnumerable<int>>?>($"api/shop/getshopwithreinforcedies?id={shop}");
if (result == null)
{
return null;
}
var shopModel = result.Item1;
var resultHtml = "";
foreach (var (item, count) in result.Item2.Zip(result.Item3))
{
resultHtml += "<tr>";
resultHtml += $"<td>{item?.ReinforcedName ?? string.Empty}</td>";
resultHtml += $"<td>{item?.Price ?? 0}</td>";
resultHtml += $"<td>{count}</td>";
resultHtml += "</tr>";
}
return Tuple.Create(resultHtml, shopModel);
}
[HttpGet]
public IActionResult Update()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
return View();
}
[HttpPost]
public void Update(int shop, string name, string address)
{
if (APIClient.IsAccessAllowed is false)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception($"Имя магазина не должно быть пустым");
}
if (string.IsNullOrEmpty(address))
{
throw new Exception($"Адрес магазина не должен быть пустым");
}
APIClient.PostRequest("api/shop/updateshop", new ShopBindingModel
{
Id = shop,
Name = name,
Address = address,
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Delete()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
return View();
}
[HttpPost]
public void Delete(int shop)
{
if (APIClient.IsAccessAllowed is false)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/shop/deleteshop", new ShopBindingModel
{
Id = shop,
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult AddReinforced()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshops");
ViewBag.Reinforcedies = APIClient.GetRequest<List<ReinforcedViewModel>>("api/main/getreinforcedlist");
return View();
}
[HttpPost]
public void AddReinforced(int shop, int reinforced, int count)
{
if (APIClient.IsAccessAllowed is false)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество должно быть больше 0");
}
APIClient.PostRequest("api/shop/addreinforcedinshop", Tuple.Create(
new ShopSearchModel() { Id = shop },
new ReinforcedViewModel() { Id = reinforced },
count
));
Response.Redirect("Index");
}
}
}

View File

@ -0,0 +1,9 @@
namespace PrecastConcretePlantShopApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PrecastConcretePlantContracts\PrecastConcretePlantContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,31 @@
using PrecastConcretePlantShopApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:14562",
"sslPort": 44320
}
},
"profiles": {
"PrecastConcretePlantShopApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7062;http://localhost:5062",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,33 @@
@using PrecastConcretePlantDataModels.Models
@using PrecastConcretePlantContracts.ViewModels;
@model Dictionary<int, (IReinforcedModel, int)>
@{
ViewData["Title"] = "AddReinforced";
}
<div class="text-center">
<h2 class="display-4">Пополнения магазина изделием</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Выбранный магазин:</div>
<div class="col-8">
<select id="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops, "Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Выбранное изделие:</div>
<div class="col-8">
<select id="reinforced" name="reinforced" class="form-control" asp-items="@(new SelectList(@ViewBag.Reinforcedies, "Id", "ReinforcedName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Количество:</div>
<div class="col-8"><input type="text" id="count" name="count"/></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Добавить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,24 @@
@{
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4">Создание магазина</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Название магазина:</div>
<div class="col-8"><input type="text" name="name" id="name" /></div>
</div>
<div class="row">
<div class="col-4">Адрес магазина:</div>
<div class="col-8"><input type="text" id="address" name="address"/></div>
</div>
<div class="row">
<div class="col-4">Максимальное кол-во изделий:</div>
<div class="col-8"><input type="text" id="maxCount" name="maxCount"/></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,18 @@
@{
ViewData["Title"] = "Update";
}
<div class="text-center">
<h2 class="display-4">Редактирование магазина</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Выбранный магазин:</div>
<div class="col-8">
<select id="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops, "Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Удалить" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,15 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -0,0 +1,66 @@
@using PrecastConcretePlantContracts.ViewModels
@model List<ShopViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Магазины</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Введите пароль</h3>
return;
}
<p>
<a asp-action="Create">Создать магазин</a>
<a asp-action="Update">Редактировать магазин</a>
<a asp-action="Delete">Удалить магазин</a>
<a asp-action="AddReinforced">Добавить изделие в магазин</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Название магазина
</th>
<th>
Адрес
</th>
<th>
Дата открытия
</th>
<th>
Максимальное количество изделий
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateOpening)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReinforcedMaxCount)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -0,0 +1,71 @@
@using PrecastConcretePlantContracts.ViewModels;
@using PrecastConcretePlantDataModels.Models;
@{
ViewData["Title"] = "Update";
}
<div class="text-center">
<h2 class="display-4">Редактирование магазина</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Выбранный магазин:</div>
<div class="col-8">
<select id="shop" name="shop" class="form-control" asp-items="@(new SelectList(@ViewBag.Shops, "Id", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Новое название магазина:</div>
<div class="col-8"><input type="text" name="name" id="name" /></div>
</div>
<div class="row">
<div class="col-4">Адрес магазина:</div>
<div class="col-8"><input type="text" id="address" name="address"/></div>
</div>
<table class="table">
<thead>
<tr>
<th>
Название изделия
</th>
<th>
Цена
</th>
<th>
Количество
</th>
</tr>
</thead>
<tbody id="table-reinforcedies">
</tbody>
</table>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Изменить" class="btn btn-primary" /></div>
</div>
</form>
<script>
function check() {
var shop = $('#shop').val();
if (shop) {
$.ajax({
method: "GET",
url: "/Home/GetTableReinforcediesFromShop",
data: { shop: shop },
success: function (result) {
if (result != null)
{
$('#name').val(result.item2.name);
$('#address').val(result.item2.address);
$('#table-reinforcedies').html(result.item1);
}
}
});
};
}
check();
$('#shop').on('change', (e) => check());
</script>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,46 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - PrecastConcretePlantShopApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/PrecastConcretePlantShopApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Завод</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Магазины</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - PrecastConcretePlantShopApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,3 @@
@using PrecastConcretePlantShopApp
@using PrecastConcretePlantShopApp.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5197",
"PasswordToAccessShop": "12345"
}

View File

@ -0,0 +1,18 @@
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,4 @@
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,427 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-left: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr /* rtl:ignore */;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: left;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: left;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: left;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
/* rtl:raw:
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More