PIbd-21. Makarov D.V. Lab work 05. Hard #14

Closed
DavidMakarov wants to merge 22 commits from hard_lab5 into lab5
147 changed files with 80240 additions and 647 deletions

View File

@ -17,9 +17,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopFileImplement", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopDatabaseImplement", "FlowerShopDatabaseImplement\FlowerShopDatabaseImplement.csproj", "{07E0542C-0ED4-4F69-B72D-B51EFF80C599}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlowerShopRestApi", "FlowerShopRestApi\FlowerShopRestApi.csproj", "{D77CFA3F-2DF8-4C16-A9D3-CC9C7AE1448B}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopRestApi", "FlowerShopRestApi\FlowerShopRestApi.csproj", "{D77CFA3F-2DF8-4C16-A9D3-CC9C7AE1448B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlowerShopClientApp", "FlowerShopClientApp\FlowerShopClientApp.csproj", "{E2A0B066-DBAA-4F67-9829-661DE97EA695}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlowerShopClientApp", "FlowerShopClientApp\FlowerShopClientApp.csproj", "{E2A0B066-DBAA-4F67-9829-661DE97EA695}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlowerShopShopApp", "FlowerShopShopApp\FlowerShopShopApp.csproj", "{AFEA55FA-AC75-424F-BCF2-C486F0398DD5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -63,6 +65,10 @@ Global
{E2A0B066-DBAA-4F67-9829-661DE97EA695}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E2A0B066-DBAA-4F67-9829-661DE97EA695}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E2A0B066-DBAA-4F67-9829-661DE97EA695}.Release|Any CPU.Build.0 = Release|Any CPU
{AFEA55FA-AC75-424F-BCF2-C486F0398DD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AFEA55FA-AC75-424F-BCF2-C486F0398DD5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFEA55FA-AC75-424F-BCF2-C486F0398DD5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFEA55FA-AC75-424F-BCF2-C486F0398DD5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -39,40 +39,43 @@
// label1
//
label1.AutoSize = true;
label1.Location = new Point(27, 15);
label1.Location = new Point(31, 20);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.Size = new Size(80, 20);
label1.TabIndex = 3;
label1.Text = "Название:";
//
// textBoxName
//
textBoxName.Location = new Point(92, 12);
textBoxName.Location = new Point(123, 17);
textBoxName.Margin = new Padding(3, 4, 3, 4);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(213, 23);
textBoxName.Size = new Size(243, 27);
textBoxName.TabIndex = 2;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(27, 44);
label2.Location = new Point(31, 59);
label2.Name = "label2";
label2.Size = new Size(38, 15);
label2.Size = new Size(48, 20);
label2.TabIndex = 5;
label2.Text = "Цена:";
//
// textBoxCost
//
textBoxCost.Location = new Point(92, 41);
textBoxCost.Location = new Point(123, 56);
textBoxCost.Margin = new Padding(3, 4, 3, 4);
textBoxCost.Name = "textBoxCost";
textBoxCost.Size = new Size(152, 23);
textBoxCost.Size = new Size(173, 27);
textBoxCost.TabIndex = 4;
//
// buttonSave
//
buttonSave.Location = new Point(169, 93);
buttonSave.Location = new Point(230, 124);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.Size = new Size(94, 31);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
@ -80,9 +83,10 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(250, 93);
buttonCancel.Location = new Point(330, 124);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.Size = new Size(86, 31);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -90,15 +94,16 @@
//
// FormComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(342, 134);
ClientSize = new Size(428, 179);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label2);
Controls.Add(textBoxCost);
Controls.Add(label1);
Controls.Add(textBoxName);
Margin = new Padding(3, 4, 3, 4);
Name = "FormComponent";
Text = "Компонент";
Load += FormComponent_Load;

View File

@ -40,41 +40,44 @@
//
comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(88, 9);
comboBoxComponent.Location = new Point(126, 13);
comboBoxComponent.Margin = new Padding(3, 4, 3, 4);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(250, 23);
comboBoxComponent.Size = new Size(285, 28);
comboBoxComponent.TabIndex = 0;
//
// textBoxCount
//
textBoxCount.Location = new Point(88, 38);
textBoxCount.Location = new Point(126, 52);
textBoxCount.Margin = new Padding(3, 4, 3, 4);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(250, 23);
textBoxCount.Size = new Size(285, 27);
textBoxCount.TabIndex = 1;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(10, 12);
label1.Location = new Point(11, 16);
label1.Name = "label1";
label1.Size = new Size(72, 15);
label1.Size = new Size(91, 20);
label1.TabIndex = 2;
label1.Text = "Компонент:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(10, 41);
label2.Location = new Point(11, 55);
label2.Name = "label2";
label2.Size = new Size(75, 15);
label2.Size = new Size(93, 20);
label2.TabIndex = 3;
label2.Text = "Количество:";
//
// buttonAdd
//
buttonAdd.Location = new Point(154, 80);
buttonAdd.Location = new Point(203, 109);
buttonAdd.Margin = new Padding(3, 4, 3, 4);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(86, 23);
buttonAdd.Size = new Size(98, 31);
buttonAdd.TabIndex = 4;
buttonAdd.Text = "Сохранить";
buttonAdd.UseVisualStyleBackColor = true;
@ -82,9 +85,10 @@
//
// buttonCancel
//
buttonCancel.Location = new Point(246, 80);
buttonCancel.Location = new Point(308, 109);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(86, 23);
buttonCancel.Size = new Size(98, 31);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
@ -92,15 +96,16 @@
//
// FormFlowerComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(350, 115);
ClientSize = new Size(423, 153);
Controls.Add(buttonCancel);
Controls.Add(buttonAdd);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(textBoxCount);
Controls.Add(comboBoxComponent);
Margin = new Padding(3, 4, 3, 4);
Name = "FormFlowerComponent";
Text = "Компоненты цветов";
ResumeLayout(false);

View File

@ -1,114 +1,114 @@
namespace FlowerShopView
{
partial class FormFlowers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormFlowers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRef
//
buttonRef.Location = new Point(283, 126);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(103, 28);
buttonRef.TabIndex = 9;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(283, 92);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(103, 28);
buttonDel.TabIndex = 8;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(283, 58);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(103, 28);
buttonUpd.TabIndex = 7;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(283, 24);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(103, 28);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(240, 426);
dataGridView.TabIndex = 5;
//
// FormFlowers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(407, 450);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormFlowers";
Text = "FormFlowers";
Load += FormFlowers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRef
//
buttonRef.Location = new Point(283, 126);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(103, 28);
buttonRef.TabIndex = 9;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += buttonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(283, 92);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(103, 28);
buttonDel.TabIndex = 8;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += buttonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(283, 58);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(103, 28);
buttonUpd.TabIndex = 7;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += buttonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(283, 24);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(103, 28);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(240, 426);
dataGridView.TabIndex = 5;
//
// FormFlowers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(407, 450);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormFlowers";
Text = "Цветы";
Load += FormFlowers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -4,102 +4,102 @@ using FlowerShopContracts.BusinessLogicsContracts;
namespace FlowerShopView
{
public partial class FormFlowers : Form
{
private readonly ILogger _logger;
private readonly IFlowerLogic _logic;
public FormFlowers(ILogger<FormFlowers> logger, IFlowerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
public partial class FormFlowers : Form
{
private readonly ILogger _logger;
private readonly IFlowerLogic _logic;
public FormFlowers(ILogger<FormFlowers> logger, IFlowerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormFlowers_Load(object sender, EventArgs e)
{
LoadData();
}
private void FormFlowers_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["FlowerComponents"].Visible = false;
dataGridView.Columns["FlowerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
}
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["FlowerComponents"].Visible = false;
dataGridView.Columns["FlowerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormFlower));
if (service is FormFlower form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormFlower));
if (service is FormFlower 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(FormFlower));
if (service is FormFlower form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
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(FormFlower));
if (service is FormFlower 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 FlowerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления записи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
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 FlowerBindingModel
{
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();
}
}
private void buttonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>

View File

@ -20,197 +20,266 @@
base.Dispose(disposing);
}
#region Windows Form Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
ЦветыToolStripMenuItem = new ToolStripMenuItem();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
клиентыToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(964, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, клиентыToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Text = "Справочники";
//
// ЦветыToolStripMenuItem
//
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(180, 22);
ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(180, 22);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(60, 20);
отчётыToolStripMenuItem.Text = "Отчёты";
//
// списокЦветковToolStripMenuItem
//
списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem";
списокЦветковToolStripMenuItem.Size = new Size(204, 22);
списокЦветковToolStripMenuItem.Text = "Список цветков";
списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click;
//
// компонентыПоЦветамToolStripMenuItem
//
компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem";
компонентыПоЦветамToolStripMenuItem.Size = new Size(204, 22);
компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам";
компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(204, 22);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 27);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(739, 411);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(775, 55);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(158, 32);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(775, 110);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(158, 34);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(775, 168);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(158, 34);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(775, 230);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(158, 34);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(775, 289);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(158, 34);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(180, 22);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(964, 450);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Цветочный магазин";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
ЦветыToolStripMenuItem = new ToolStripMenuItem();
КомпонентыToolStripMenuItem = new ToolStripMenuItem();
магазиныToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЦветковToolStripMenuItem = new ToolStripMenuItem();
компонентыПоЦветамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
списокМагазиновToolStripMenuItem = new ToolStripMenuItem();
загруженностьМагазиновToolStripMenuItem = new ToolStripMenuItem();
заказыПоДатамToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
пополнениеМагазинаToolStripMenuItem = new ToolStripMenuItem();
продажаЦветовToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, пополнениеМагазинаToolStripMenuItem, продажаЦветовToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(7, 3, 0, 3);
menuStrip1.Size = new Size(1102, 30);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ЦветыToolStripMenuItem, КомпонентыToolStripMenuItem, магазиныToolStripMenuItem, клиентыToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// ЦветыToolStripMenuItem
//
ЦветыToolStripMenuItem.Name = "ЦветыToolStripMenuItem";
ЦветыToolStripMenuItem.Size = new Size(182, 26);
ЦветыToolStripMenuItem.Text = "Цветы";
ЦветыToolStripMenuItem.Click += ЦветыToolStripMenuItem_Click;
//
// КомпонентыToolStripMenuItem
//
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(182, 26);
КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// магазиныToolStripMenuItem
//
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(182, 26);
магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(182, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокЦветковToolStripMenuItem, компонентыПоЦветамToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоДатамToolStripMenuItem });
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
отчётыToolStripMenuItem.Size = new Size(73, 24);
отчётыToolStripMenuItem.Text = "Отчёты";
//
// списокЦветковToolStripMenuItem
//
списокЦветковToolStripMenuItem.Name = "списокЦветковToolStripMenuItem";
списокЦветковToolStripMenuItem.Size = new Size(276, 26);
списокЦветковToolStripMenuItem.Text = "Список цветков";
списокЦветковToolStripMenuItem.Click += списокЦветковToolStripMenuItem_Click;
//
// компонентыПоЦветамToolStripMenuItem
//
компонентыПоЦветамToolStripMenuItem.Name = омпонентыПоЦветамToolStripMenuItem";
компонентыПоЦветамToolStripMenuItem.Size = new Size(276, 26);
компонентыПоЦветамToolStripMenuItem.Text = "Компоненты по цветам";
компонентыПоЦветамToolStripMenuItem.Click += компонентыПоЦветамToolStripMenuItem_Click;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(276, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
//
// списокМагазиновToolStripMenuItem
//
списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
списокМагазиновToolStripMenuItem.Size = new Size(276, 26);
списокМагазиновToolStripMenuItem.Text = "Список магазинов";
списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click;
//
// загруженностьМагазиновToolStripMenuItem
//
загруженностьМагазиновToolStripMenuItem.Name = агруженностьМагазиновToolStripMenuItem";
загруженностьМагазиновToolStripMenuItem.Size = new Size(276, 26);
загруженностьМагазиновToolStripMenuItem.Text = "Загруженность магазинов";
загруженностьМагазиновToolStripMenuItem.Click += загруженностьМагазиновToolStripMenuItem_Click;
//
// заказыПоДатамToolStripMenuItem
//
заказыПоДатамToolStripMenuItem.Name = аказыПоДатамToolStripMenuItem";
заказыПоДатамToolStripMenuItem.Size = new Size(276, 26);
заказыПоДатамToolStripMenuItem.Text = "Заказы по датам";
заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.BackgroundColor = Color.White;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(14, 36);
dataGridView.Margin = new Padding(3, 4, 3, 4);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(845, 548);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(886, 73);
buttonCreateOrder.Margin = new Padding(3, 4, 3, 4);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(181, 43);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(886, 147);
buttonTakeOrderInWork.Margin = new Padding(3, 4, 3, 4);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(181, 45);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(886, 224);
buttonOrderReady.Margin = new Padding(3, 4, 3, 4);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(181, 45);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(886, 307);
buttonIssuedOrder.Margin = new Padding(3, 4, 3, 4);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(181, 45);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(886, 385);
buttonRef.Margin = new Padding(3, 4, 3, 4);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(181, 45);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// пополнениеМагазинаToolStripMenuItem
//
пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
пополнениеМагазинаToolStripMenuItem.Size = new Size(182, 24);
пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
пополнениеМагазинаToolStripMenuItem.Click += пополнениеМагазинаToolStripMenuItem_Click;
//
// продажаЦветовToolStripMenuItem
//
продажаЦветовToolStripMenuItem.Name = "продажаЦветовToolStripMenuItem";
продажаЦветовToolStripMenuItem.Size = new Size(139, 24);
продажаЦветовToolStripMenuItem.Text = "Продажа цветов";
продажаЦветовToolStripMenuItem.Click += продажаЦветовToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1102, 600);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Margin = new Padding(3, 4, 3, 4);
Name = "FormMain";
Text = "Цветочный магазин";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private void ПродажаЦветовToolStripMenuItem_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ЦветыToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem ЦветыToolStripMenuItem;
private ToolStripMenuItem КомпонентыToolStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem списокЦветковToolStripMenuItem;
private ToolStripMenuItem компонентыПоЦветамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
}
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem;
private ToolStripMenuItem заказыПоДатамToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem;
private ToolStripMenuItem продажаЦветовToolStripMenuItem;
}
}

View File

@ -1,189 +1,240 @@
using FlowerShopBusinessLogic.BusinessLogics;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["FlowerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["FlowerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ЦветыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormFlowers));
if (service is FormFlowers form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
try
{
var operationResult = _orderLogic.FinishOrder(new
OrderBindingModel
{ Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["FlowerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ЦветыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormFlowers));
if (service is FormFlowers form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
try
{
var operationResult = _orderLogic.FinishOrder(new
OrderBindingModel
{ Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id });
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void списокЦветковToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void списокЦветковToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel
{
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void компонентыПоЦветамToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportFlowerComponents));
if (service is FormReportFlowerComponents form)
{
form.ShowDialog();
}
}
private void компонентыПоЦветамToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportFlowerComponents));
if (service is FormReportFlowerComponents form)
{
form.ShowDialog();
}
}
private void клиентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients)) ;
if (service is FormClients 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.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void загруженностьМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopFlowers));
if (service is FormReportShopFlowers form)
{
form.ShowDialog();
}
}
private void заказыПоДатамToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders));
if (service is FormReportGroupedOrders form)
{
form.ShowDialog();
}
}
private void магазиныToolStripMenuItem_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)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void пополнениеМагазинаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMakeSupply));
if (service is FormMakeSupply form)
{
form.ShowDialog();
}
}
private void продажаЦветовToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMakeSale));
if (service is FormMakeSale form)
{
form.ShowDialog();
}
}
}
}

View File

@ -18,7 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>

View File

@ -0,0 +1,127 @@
namespace FlowerShopView
{
partial class FormMakeSale
{
/// <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()
{
buttonCancel = new Button();
buttonSale = new Button();
textBoxCount = new TextBox();
labelCount = new Label();
comboBoxFlower = new ComboBox();
labelFlower = new Label();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(253, 83);
buttonCancel.Margin = new Padding(4, 3, 4, 3);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(88, 27);
buttonCancel.TabIndex = 17;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSale
//
buttonSale.Location = new Point(159, 83);
buttonSale.Margin = new Padding(4, 3, 4, 3);
buttonSale.Name = "buttonSale";
buttonSale.Size = new Size(88, 27);
buttonSale.TabIndex = 16;
buttonSale.Text = "Продать";
buttonSale.UseVisualStyleBackColor = true;
buttonSale.Click += ButtonSale_Click;
//
// textBoxCount
//
textBoxCount.Location = new Point(101, 51);
textBoxCount.Margin = new Padding(4, 3, 4, 3);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(252, 23);
textBoxCount.TabIndex = 15;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(13, 54);
labelCount.Margin = new Padding(4, 0, 4, 0);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 14;
labelCount.Text = "Количество:";
//
// comboBoxFlower
//
comboBoxFlower.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxFlower.FormattingEnabled = true;
comboBoxFlower.Location = new Point(101, 15);
comboBoxFlower.Margin = new Padding(4, 3, 4, 3);
comboBoxFlower.Name = "comboBoxFlower";
comboBoxFlower.Size = new Size(252, 23);
comboBoxFlower.TabIndex = 13;
//
// labelFlower
//
labelFlower.AutoSize = true;
labelFlower.Location = new Point(13, 19);
labelFlower.Margin = new Padding(4, 0, 4, 0);
labelFlower.Name = "labelFlower";
labelFlower.Size = new Size(45, 15);
labelFlower.TabIndex = 12;
labelFlower.Text = "Цветы:";
//
// FormMakeSale
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(373, 123);
Controls.Add(buttonCancel);
Controls.Add(buttonSale);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(comboBoxFlower);
Controls.Add(labelFlower);
Name = "FormMakeSale";
StartPosition = FormStartPosition.CenterScreen;
Text = "Продажа цветов";
Load += FormMakeSale_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSale;
private TextBox textBoxCount;
private Label labelCount;
private ComboBox comboBoxFlower;
private Label labelFlower;
}
}

View File

@ -0,0 +1,85 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
public partial class FormMakeSale : Form
{
private readonly ILogger<FormMakeSale> _logger;
private readonly IFlowerLogic _logicFlower;
private readonly IShopLogic _logicShop;
public FormMakeSale(ILogger<FormMakeSale> logger, IFlowerLogic logicFlower, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicFlower = logicFlower;
_logicShop = logicShop;
}
private void FormMakeSale_Load(object sender, EventArgs e)
{
_logger.LogInformation("Flowers loading");
try
{
var list = _logicFlower.ReadList(null);
if (list != null)
{
comboBoxFlower.DisplayMember = "FlowerName";
comboBoxFlower.ValueMember = "Id";
comboBoxFlower.DataSource = list;
comboBoxFlower.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Flowers loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSale_Click(object sender, EventArgs e)
{
if (comboBoxFlower.SelectedValue == null)
{
MessageBox.Show("Выберите цветы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Flowers sale");
try
{
var operationResult = _logicShop.MakeSale(
new FlowerBindingModel
{
Id = Convert.ToInt32(comboBoxFlower.SelectedValue)
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при продаже.");
}
MessageBox.Show("Продажа прошла успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Flowers sale error");
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,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,153 @@
namespace FlowerShopView
{
partial class FormMakeSupply
{
/// <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()
{
labelShop = new Label();
comboBoxShop = new ComboBox();
labelFlower = new Label();
comboBoxFlower = new ComboBox();
labelCount = new Label();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelShop
//
labelShop.AutoSize = true;
labelShop.Location = new Point(14, 13);
labelShop.Margin = new Padding(4, 0, 4, 0);
labelShop.Name = "labelShop";
labelShop.Size = new Size(60, 15);
labelShop.TabIndex = 2;
labelShop.Text = "Магазин:";
//
// comboBoxShop
//
comboBoxShop.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxShop.FormattingEnabled = true;
comboBoxShop.Location = new Point(102, 10);
comboBoxShop.Margin = new Padding(4, 3, 4, 3);
comboBoxShop.Name = "comboBoxShop";
comboBoxShop.Size = new Size(252, 23);
comboBoxShop.TabIndex = 5;
//
// labelFlower
//
labelFlower.AutoSize = true;
labelFlower.Location = new Point(14, 48);
labelFlower.Margin = new Padding(4, 0, 4, 0);
labelFlower.Name = "labelFlower";
labelFlower.Size = new Size(80, 15);
labelFlower.TabIndex = 6;
labelFlower.Text = "Цветок:";
//
// comboBoxFlower
//
comboBoxFlower.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxFlower.FormattingEnabled = true;
comboBoxFlower.Location = new Point(102, 44);
comboBoxFlower.Margin = new Padding(4, 3, 4, 3);
comboBoxFlower.Name = "comboBoxFlower";
comboBoxFlower.Size = new Size(252, 23);
comboBoxFlower.TabIndex = 7;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(14, 83);
labelCount.Margin = new Padding(4, 0, 4, 0);
labelCount.Name = "labelCount";
labelCount.Size = new Size(78, 15);
labelCount.TabIndex = 8;
labelCount.Text = "Количество:";
//
// textBoxCount
//
textBoxCount.Location = new Point(102, 80);
textBoxCount.Margin = new Padding(4, 3, 4, 3);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(252, 23);
textBoxCount.TabIndex = 9;
//
// buttonSave
//
buttonSave.Location = new Point(160, 112);
buttonSave.Margin = new Padding(4, 3, 4, 3);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(88, 27);
buttonSave.TabIndex = 10;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(254, 112);
buttonCancel.Margin = new Padding(4, 3, 4, 3);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(88, 27);
buttonCancel.TabIndex = 11;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormMakeShipment
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(373, 147);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(comboBoxFlower);
Controls.Add(labelFlower);
Controls.Add(comboBoxShop);
Controls.Add(labelShop);
Name = "FormMakeShipment";
StartPosition = FormStartPosition.CenterScreen;
Text = "Пополнение магазина";
Load += FormMakeShipment_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelShop;
private ComboBox comboBoxShop;
private Label labelFlower;
private ComboBox comboBoxFlower;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,124 @@
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
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 FlowerShopView
{
public partial class FormMakeSupply : Form
{
private readonly ILogger _logger;
private readonly IFlowerLogic _logicFlower;
private readonly IShopLogic _logicShop;
public FormMakeSupply(ILogger<FormMakeSupply> logger, IFlowerLogic logicFlower, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicFlower = logicFlower;
_logicShop = logicShop;
}
private void FormMakeShipment_Load(object sender, EventArgs e)
{
_logger.LogInformation("Flowers loading");
try
{
var list = _logicFlower.ReadList(null);
if (list != null)
{
comboBoxFlower.DisplayMember = "FlowerName";
comboBoxFlower.ValueMember = "Id";
comboBoxFlower.DataSource = list;
comboBoxFlower.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Flowers loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Shops loading");
try
{
var list = _logicShop.ReadList(null);
if (list != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = list;
comboBoxShop.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Shops loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxFlower.SelectedValue == null)
{
MessageBox.Show("Выберите цветок", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Shop replenishment");
try
{
var iceCream = _logicFlower.ReadElement(new FlowerSearchModel
{ Id = Convert.ToInt32(comboBoxFlower.SelectedValue) });
if (iceCream == null)
{
throw new Exception("Цветок не найден.");
}
var operationResult = _logicShop.MakeSupply(new ShopSearchModel
{
Id = Convert.ToInt32(comboBoxShop.SelectedValue)
},
iceCream, Convert.ToInt32(textBoxCount.Text));
if (!operationResult)
{
throw new Exception("Ошибка при проведении поставки.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Shop supply error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

View File

@ -0,0 +1,91 @@
namespace FlowerShopView
{
partial class FormReportGroupedOrders
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
panel = new Panel();
buttonToPdf = new Button();
buttonCreateReport = new Button();
panel.SuspendLayout();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonToPdf);
panel.Controls.Add(buttonCreateReport);
panel.Dock = DockStyle.Top;
panel.Location = new Point(0, 0);
panel.Margin = new Padding(4, 3, 4, 3);
panel.Name = "panel";
panel.Size = new Size(1031, 40);
panel.TabIndex = 0;
//
// buttonToPdf
//
buttonToPdf.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonToPdf.Location = new Point(188, 8);
buttonToPdf.Margin = new Padding(4, 3, 4, 3);
buttonToPdf.Name = "buttonToPdf";
buttonToPdf.Size = new Size(139, 27);
buttonToPdf.TabIndex = 5;
buttonToPdf.Text = "В Pdf";
buttonToPdf.UseVisualStyleBackColor = true;
buttonToPdf.Click += ButtonToPdf_Click;
//
// buttonCreateReport
//
buttonCreateReport.Location = new Point(11, 8);
buttonCreateReport.Margin = new Padding(4, 3, 4, 3);
buttonCreateReport.Name = "buttonCreateReport";
buttonCreateReport.Size = new Size(139, 27);
buttonCreateReport.TabIndex = 4;
buttonCreateReport.Text = "Сформировать";
buttonCreateReport.UseVisualStyleBackColor = true;
buttonCreateReport.Click += ButtonCreateReport_Click;
//
// FormReportGroupedOrders
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1031, 647);
Controls.Add(panel);
Margin = new Padding(4, 3, 4, 3);
Name = "FormReportGroupedOrders";
StartPosition = FormStartPosition.CenterScreen;
Text = "Заказы по датам";
panel.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonToPdf;
private Button buttonCreateReport;
}
}

View File

@ -0,0 +1,68 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using Microsoft.Reporting.WinForms;
namespace FlowerShopView
{
public partial class FormReportGroupedOrders : Form
{
private readonly ReportViewer reportViewer;
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportGroupedOrders(ILogger<FormReportOrders> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
reportViewer = new ReportViewer
{
Dock = DockStyle.Fill
};
reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportGroupedOrders.rdlc", FileMode.Open));
Controls.Clear();
Controls.Add(reportViewer);
Controls.Add(panel);
}
private void ButtonCreateReport_Click(object sender, EventArgs e)
{
try
{
var dataSource = _logic.GetGroupedByDateOrders();
var source = new ReportDataSource("DataSetGroupedOrders", dataSource);
reportViewer.LocalReport.DataSources.Clear();
reportViewer.LocalReport.DataSources.Add(source);
reportViewer.RefreshReport();
_logger.LogInformation("Loading list of grouped orders");
}
catch (Exception ex)
{
_logger.LogError(ex, "Loading list of grouped orders error");
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.SaveGroupedOrdersToPdfFile(new ReportBindingModel
{
FileName = dialog.FileName,
});
_logger.LogInformation("Saving list of grouped orders");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Saving list of grouped orders error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

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

View File

@ -0,0 +1,119 @@
namespace FlowerShopView
{
partial class FormReportShopFlowers
{
/// <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();
ColumnShop = new DataGridViewTextBoxColumn();
ColumnFlower = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonSaveToExcel = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToOrderColumns = true;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShop, ColumnFlower, ColumnCount });
dataGridView.Dock = DockStyle.Bottom;
dataGridView.Location = new Point(0, 63);
dataGridView.Margin = new Padding(5, 4, 5, 4);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(737, 680);
dataGridView.TabIndex = 0;
//
// ColumnShop
//
ColumnShop.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnShop.HeaderText = "Магазин";
ColumnShop.MinimumWidth = 6;
ColumnShop.Name = "ColumnShop";
ColumnShop.ReadOnly = true;
//
// ColumnFlower
//
ColumnFlower.HeaderText = "Цветок";
ColumnFlower.MinimumWidth = 6;
ColumnFlower.Name = "ColumnFlower";
ColumnFlower.ReadOnly = true;
ColumnFlower.Width = 200;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
ColumnCount.Width = 125;
//
// buttonSaveToExcel
//
buttonSaveToExcel.Location = new Point(15, 13);
buttonSaveToExcel.Margin = new Padding(5, 4, 5, 4);
buttonSaveToExcel.Name = "buttonSaveToExcel";
buttonSaveToExcel.Size = new Size(213, 36);
buttonSaveToExcel.TabIndex = 1;
buttonSaveToExcel.Text = "Сохранить в Excel";
buttonSaveToExcel.UseVisualStyleBackColor = true;
buttonSaveToExcel.Click += ButtonSaveToExcel_Click;
//
// FormReportShopFlowers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(737, 743);
Controls.Add(buttonSaveToExcel);
Controls.Add(dataGridView);
Margin = new Padding(5, 4, 5, 4);
Name = "FormReportShopFlowers";
StartPosition = FormStartPosition.CenterScreen;
Text = "Загруженность магазинов";
Load += FormReportShopFlowers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonSaveToExcel;
private DataGridViewTextBoxColumn ColumnShop;
private DataGridViewTextBoxColumn ColumnFlower;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,67 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
public partial class FormReportShopFlowers : Form
{
private readonly ILogger _logger;
private readonly IReportLogic _logic;
public FormReportShopFlowers(ILogger<FormReportShopFlowers> logger, IReportLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormReportShopFlowers_Load(object sender, EventArgs e)
{
try
{
var dict = _logic.GetShopFlowers();
if (dict != null)
{
dataGridView.Rows.Clear();
foreach (var elem in dict)
{
dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" });
foreach (var listElem in elem.Flowers)
{
dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 });
}
dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount });
dataGridView.Rows.Add(Array.Empty<object>());
}
}
_logger.LogInformation("Loading information on store workload");
}
catch (Exception ex)
{
_logger.LogError(ex, "Loading information on store workload error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSaveToExcel_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
_logic.SaveShopFlowerToExcelFile(new ReportBindingModel
{
FileName = dialog.FileName
});
_logger.LogInformation("Saving information on store workload");
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Saving information on store workload error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

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

236
FlowerShop/FlowerShop/FormShop.Designer.cs generated Normal file
View File

@ -0,0 +1,236 @@
namespace FlowerShopView
{
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()
{
labelName = new Label();
textBoxName = new TextBox();
labelAddress = new Label();
textBoxAddress = new TextBox();
dateTimePicker = new DateTimePicker();
labelOpeningDate = new Label();
groupBoxFlowers = new GroupBox();
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnName = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonSave = new Button();
buttonCancel = new Button();
textBoxMaximum = new TextBox();
label1 = new Label();
groupBoxFlowers.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(14, 10);
labelName.Margin = new Padding(4, 0, 4, 0);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 1;
labelName.Text = "Название:";
//
// textBoxName
//
textBoxName.Location = new Point(175, 7);
textBoxName.Margin = new Padding(4, 3, 4, 3);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(252, 23);
textBoxName.TabIndex = 2;
//
// labelAddress
//
labelAddress.AutoSize = true;
labelAddress.Location = new Point(14, 40);
labelAddress.Margin = new Padding(4, 0, 4, 0);
labelAddress.Name = "labelAddress";
labelAddress.Size = new Size(43, 15);
labelAddress.TabIndex = 3;
labelAddress.Text = "Адрес:";
//
// textBoxAddress
//
textBoxAddress.Location = new Point(175, 37);
textBoxAddress.Margin = new Padding(4, 3, 4, 3);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(252, 23);
textBoxAddress.TabIndex = 4;
//
// dateTimePicker
//
dateTimePicker.Location = new Point(209, 98);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(218, 23);
dateTimePicker.TabIndex = 5;
//
// labelOpeningDate
//
labelOpeningDate.AutoSize = true;
labelOpeningDate.Location = new Point(14, 104);
labelOpeningDate.Margin = new Padding(4, 0, 4, 0);
labelOpeningDate.Name = "labelOpeningDate";
labelOpeningDate.Size = new Size(90, 15);
labelOpeningDate.TabIndex = 6;
labelOpeningDate.Text = "Дата открытия:";
//
// groupBoxFlowers
//
groupBoxFlowers.Controls.Add(dataGridView);
groupBoxFlowers.Location = new Point(4, 135);
groupBoxFlowers.Margin = new Padding(4, 3, 4, 3);
groupBoxFlowers.Name = "groupBoxFlowers";
groupBoxFlowers.Padding = new Padding(4, 3, 4, 3);
groupBoxFlowers.Size = new Size(469, 288);
groupBoxFlowers.TabIndex = 7;
groupBoxFlowers.TabStop = false;
groupBoxFlowers.Text = "Цветы";
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount });
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(4, 19);
dataGridView.Margin = new Padding(4, 3, 4, 3);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(457, 266);
dataGridView.TabIndex = 0;
//
// ColumnId
//
ColumnId.HeaderText = "Id";
ColumnId.Name = "ColumnId";
ColumnId.ReadOnly = true;
ColumnId.Visible = false;
//
// ColumnName
//
ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnName.HeaderText = "Название цветка";
ColumnName.Name = "ColumnName";
ColumnName.ReadOnly = true;
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
ColumnCount.ReadOnly = true;
//
// buttonSave
//
buttonSave.Location = new Point(255, 429);
buttonSave.Margin = new Padding(4, 3, 4, 3);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(88, 27);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(359, 429);
buttonCancel.Margin = new Padding(4, 3, 4, 3);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(88, 27);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// textBoxMaximum
//
textBoxMaximum.Location = new Point(175, 68);
textBoxMaximum.Margin = new Padding(4, 3, 4, 3);
textBoxMaximum.Name = "textBoxMaximum";
textBoxMaximum.Size = new Size(252, 23);
textBoxMaximum.TabIndex = 11;
//
// label1
//
label1.Location = new Point(14, 68);
label1.Margin = new Padding(4, 0, 4, 0);
label1.Name = "label1";
label1.Size = new Size(153, 33);
label1.TabIndex = 10;
label1.Text = "Максимальное количество цветков:";
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(478, 465);
Controls.Add(textBoxMaximum);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBoxFlowers);
Controls.Add(labelOpeningDate);
Controls.Add(dateTimePicker);
Controls.Add(textBoxAddress);
Controls.Add(labelAddress);
Controls.Add(textBoxName);
Controls.Add(labelName);
Name = "FormShop";
StartPosition = FormStartPosition.CenterScreen;
Text = "Магазин";
Load += FormShop_Load;
groupBoxFlowers.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private TextBox textBoxName;
private Label labelAddress;
private TextBox textBoxAddress;
private DateTimePicker dateTimePicker;
private Label labelOpeningDate;
private GroupBox groupBoxFlowers;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnCount;
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxMaximum;
private Label label1;
}
}

View File

@ -0,0 +1,126 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
private int? _id;
private Dictionary<int, (IFlowerModel, int)> _shopFlowers;
public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopFlowers = new Dictionary<int, (IFlowerModel, int)>();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Shop loading");
try
{
var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateTimePicker.Value = view.DateOpening;
_shopFlowers = view.ShopFlowers ?? new Dictionary<int, (IFlowerModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Shop loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Shop flowers loading");
try
{
if (_shopFlowers != null)
{
dataGridView.Rows.Clear();
foreach (var iceCream in _shopFlowers)
{
dataGridView.Rows.Add(new object[] { iceCream.Key, iceCream.Value.Item1.FlowerName, iceCream.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Shop flowers loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(dateTimePicker.Text))
{
MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Shop saving");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpening = dateTimePicker.Value,
ShopFlowers = _shopFlowers,
MaximumFlowers = Convert.ToInt32(textBoxMaximum.Text),
};
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, "Shop saving error");
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,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing"">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,126 @@
namespace FlowerShopView
{
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()
{
dataGridView = new DataGridView();
buttonUpd = new Button();
buttonDel = new Button();
buttonEdit = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.BackgroundColor = SystemColors.ControlLightLight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.Margin = new Padding(4, 3, 4, 3);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(408, 360);
dataGridView.TabIndex = 2;
//
// buttonUpd
//
buttonUpd.Location = new Point(432, 152);
buttonUpd.Margin = new Padding(4, 3, 4, 3);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(88, 27);
buttonUpd.TabIndex = 12;
buttonUpd.Text = "Обновить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonDel
//
buttonDel.Location = new Point(432, 105);
buttonDel.Margin = new Padding(4, 3, 4, 3);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(88, 27);
buttonDel.TabIndex = 11;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonEdit
//
buttonEdit.Location = new Point(432, 58);
buttonEdit.Margin = new Padding(4, 3, 4, 3);
buttonEdit.Name = "buttonEdit";
buttonEdit.Size = new Size(88, 27);
buttonEdit.TabIndex = 10;
buttonEdit.Text = "Изменить";
buttonEdit.UseVisualStyleBackColor = true;
buttonEdit.Click += ButtonEdit_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(432, 14);
buttonAdd.Margin = new Padding(4, 3, 4, 3);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(88, 27);
buttonAdd.TabIndex = 9;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormShops
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(541, 360);
Controls.Add(buttonUpd);
Controls.Add(buttonDel);
Controls.Add(buttonEdit);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormShops";
StartPosition = FormStartPosition.CenterScreen;
Text = "Магазины";
Load += FormShops_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonUpd;
private Button buttonDel;
private Button buttonEdit;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,104 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace FlowerShopView
{
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["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ShopFlowers"].Visible = false;
}
_logger.LogInformation("Shops loading");
}
catch (Exception ex)
{
_logger.LogError(ex, "Shops loading error");
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 ButtonEdit_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("Deletion of shop");
try
{
if (!_logic.Delete(new ShopBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Shop deletion error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

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

View File

@ -38,11 +38,14 @@ namespace FlowerShopView
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IFlowerStorage, FlowerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IFlowerLogic, FlowerLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
@ -50,6 +53,21 @@ namespace FlowerShopView
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormFlower>();
services.AddTransient<FormFlowerComponent>();
services.AddTransient<FormFlowers>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormMakeSupply>();
services.AddTransient<FormMakeSale>();
services.AddTransient<FormReportFlowerComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportShopFlowers>();
services.AddTransient<FormReportGroupedOrders>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();

View File

@ -0,0 +1,441 @@
<?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="FlowerShopContractsViewModels">
<ConnectionProperties>
<DataProvider>System.Data.DataSet</DataProvider>
<ConnectString>/* Local Connection */</ConnectString>
</ConnectionProperties>
<rd:DataSourceID>20791c83-cee8-4a38-bbd0-245fc17cefb3</rd:DataSourceID>
</DataSource>
</DataSources>
<DataSets>
<DataSet Name="DataSetGroupedOrders">
<Query>
<DataSourceName>FlowerShopContractsViewModels</DataSourceName>
<CommandText>/* Local Query */</CommandText>
</Query>
<Fields>
<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.Decimal</rd:TypeName>
</Field>
</Fields>
<rd:DataSetInfo>
<rd:DataSetName>FlowerShopContracts.ViewModels</rd:DataSetName>
<rd:TableName>FlowerShopReportGroupedOrdersViewModelhop</rd:TableName>
<rd:ObjectDataSourceType>FlowerShopContracts.ViewModels.FlowerShopReportGroupedOrdersViewModelhop, FlowerShopContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</rd:ObjectDataSourceType>
</rd:DataSetInfo>
</DataSet>
</DataSets>
<ReportSections>
<ReportSection>
<Body>
<ReportItems>
<Textbox Name="TextboxTitle">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Отчёт по заказам</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Height>0.6cm</Height>
<Width>16.51cm</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="ReportParameterPeriod">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Parameters!ReportParameterPeriod.Value</Value>
<Style>
<Format>d</Format>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Center</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<rd:DefaultName>ReportParameterPeriod</rd:DefaultName>
<Top>0.6cm</Top>
<Height>0.6cm</Height>
<Width>16.51cm</Width>
<ZIndex>1</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
</Textbox>
<Tablix Name="Tablix1">
<TablixBody>
<TablixColumns>
<TablixColumn>
<Width>3.90406cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.97461cm</Width>
</TablixColumn>
<TablixColumn>
<Width>3.65711cm</Width>
</TablixColumn>
</TablixColumns>
<TablixRows>
<TablixRow>
<Height>0.6cm</Height>
<TablixCells>
<TablixCell>
<CellContents>
<Textbox Name="TextboxDate">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Дата создания</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<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="TextboxCount">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Количество заказов</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<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="TextboxSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Общая сумма заказов</Value>
<Style />
</TextRun>
</TextRuns>
<Style />
</Paragraph>
</Paragraphs>
<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 />
</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>DataSetGroupedOrders</DataSetName>
<Top>1.88242cm</Top>
<Left>2.68676cm</Left>
<Height>1.2cm</Height>
<Width>11.53578cm</Width>
<ZIndex>2</ZIndex>
<Style>
<Border>
<Style>None</Style>
</Border>
</Style>
</Tablix>
<Textbox Name="TextboxResout">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>Итого:</Value>
<Style />
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>3.29409cm</Top>
<Left>8.06542cm</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="TextboxFullSum">
<CanGrow>true</CanGrow>
<KeepTogether>true</KeepTogether>
<Paragraphs>
<Paragraph>
<TextRuns>
<TextRun>
<Value>=Sum(Fields!Sum.Value, "DataSetGroupedOrders")</Value>
<Style>
<Format>0.00;(0.00)</Format>
</Style>
</TextRun>
</TextRuns>
<Style>
<TextAlign>Right</TextAlign>
</Style>
</Paragraph>
</Paragraphs>
<Top>3.29409cm</Top>
<Left>10.70653cm</Left>
<Height>0.6cm</Height>
<Width>3.48072cm</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>2in</Height>
<Style />
</Body>
<Width>6.5in</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>b5a8ad5e-1151-4687-8576-a5270295c079</rd:ReportID>
</Report>

View File

@ -4,6 +4,7 @@ using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Enums;
using FlowerShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace FlowerShopBusinessLogic.BusinessLogics
@ -12,10 +13,16 @@ namespace FlowerShopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private readonly IFlowerStorage _flowerStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IFlowerStorage flowerStorage, IShopStorage shopStorage, IShopLogic shopLogic)
{
_logger = logger;
_orderStorage = orderStorage;
_flowerStorage = flowerStorage;
_shopStorage = shopStorage;
_shopLogic = shopLogic;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -80,17 +87,32 @@ namespace FlowerShopBusinessLogic.BusinessLogics
_logger.LogWarning("Status update to " + orderStatus + " operation failed");
return false;
}
if (orderStatus == OrderStatus.Выдан)
{
var flower = _flowerStorage.GetElement(new FlowerSearchModel() { Id = model.FlowerId } );
if (flower == null)
{
return false;
}
if (!SupplyFlowers(flower, model.Count))
{
_logger.LogWarning("Change status operation failed. Flowers delivery operation failed");
return false;
}
}
model.Status = orderStatus;
if (model.Status == OrderStatus.Выдан)
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = element.DateImplement;
}
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Changing status operation faled");
_logger.LogWarning("Changing status operation failed");
return false;
}
return true;
@ -119,5 +141,62 @@ namespace FlowerShopBusinessLogic.BusinessLogics
}
_logger.LogInformation("Order. FlowerId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.FlowerId, model.Count, model.Sum, model.Id);
}
private bool SupplyFlowers(IFlowerModel flower, int count)
{
if (count < 0)
{
_logger.LogWarning("Flower supply operation failed. Count <= 0");
return false;
}
var shopList = _shopStorage.GetFullList();
var shopsCapacity = shopList.Sum(x => x.MaximumFlowers);
int currentFlowers = shopList.Select(x => x.ShopFlowers.Sum(y => y.Value.Item2)).Sum();
int freeSpace = shopsCapacity - currentFlowers;
if (freeSpace < count)
{
_logger.LogWarning("Flower supply operation failed. No free space for new flowers");
return false;
}
foreach (var shop in shopList)
{
freeSpace = shop.MaximumFlowers - shop.ShopFlowers.Sum(x => x.Value.Item2);
if (freeSpace == 0)
{
continue;
}
if (freeSpace >= count)
{
if (_shopLogic.MakeSupply(new ShopSearchModel() { Id = shop.Id }, flower, count))
{
count = 0;
}
else
{
_logger.LogWarning("Flowers delivery operation failed");
return false;
}
}
else
{
if (_shopLogic.MakeSupply(new ShopSearchModel() { Id = shop.Id }, flower, freeSpace))
{
count -= freeSpace;
}
else
{
_logger.LogWarning("Flowers delivery operation failed");
return false;
}
}
if (count == 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -13,19 +13,21 @@ namespace FlowerShopBusinessLogic.BusinessLogics
private readonly IComponentStorage _componentStorage;
private readonly IFlowerStorage _flowerStorage;
private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(IComponentStorage componentStorage, IFlowerStorage flowerStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf)
{
_componentStorage = componentStorage;
_flowerStorage = flowerStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
public List<ReportFlowerComponentViewModel> GetFlowerComponent()
public ReportLogic(IComponentStorage componentStorage, IFlowerStorage flowerStorage, IOrderStorage orderStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf, IShopStorage shopStorage)
{
_componentStorage = componentStorage;
_flowerStorage = flowerStorage;
_orderStorage = orderStorage;
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_shopStorage = shopStorage;
}
public List<ReportFlowerComponentViewModel> GetFlowerComponent()
{
var components = _componentStorage.GetFullList();
var floweres = _flowerStorage.GetFullList();
@ -51,7 +53,30 @@ namespace FlowerShopBusinessLogic.BusinessLogics
}
return list;
}
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
public List<ReportShopFlowerViewModel> GetShopFlowers()
{
var shops = _shopStorage.GetFullList();
var list = new List<ReportShopFlowerViewModel>();
foreach (var shop in shops)
{
var record = new ReportShopFlowerViewModel
{
ShopName = shop.ShopName,
Flowers = new List<(string Flower, int Count)>(),
TotalCount = 0,
};
foreach (var iceCream in shop.ShopFlowers)
{
record.Flowers.Add(new(iceCream.Value.Item1.FlowerName, iceCream.Value.Item2));
record.TotalCount += iceCream.Value.Item2;
}
list.Add(record);
}
return list;
}
public List<ReportOrdersViewModel> GetOrders(ReportBindingModel model)
{
return _orderStorage.GetFilteredList(new OrderSearchModel
{
@ -67,7 +92,17 @@ namespace FlowerShopBusinessLogic.BusinessLogics
}).ToList();
}
public void SaveComponentsToWordFile(ReportBindingModel model)
public List<ReportOrdersByDateViewModel> GetGroupedByDateOrders()
{
return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportOrdersByDateViewModel
{
Date = x.Key,
Count = x.Count(),
Sum = x.Select(y => y.Sum).Sum()
}).ToList();
}
public void SaveComponentsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateDoc(new WordInfo
{
@ -76,8 +111,16 @@ namespace FlowerShopBusinessLogic.BusinessLogics
Flowers = _flowerStorage.GetFullList()
});
}
public void SaveFlowerComponentToExcelFile(ReportBindingModel model)
public void SaveShopsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateShopsTable(new WordInfo
{
FileName = model.FileName,
Title = "Список магазинов",
Shops = _shopStorage.GetFullList()
});
}
public void SaveFlowerComponentToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateReport(new ExcelInfo
{
@ -86,7 +129,16 @@ namespace FlowerShopBusinessLogic.BusinessLogics
FlowerComponents = GetFlowerComponent()
});
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
public void SaveShopFlowerToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateShopReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Загруженность магазинов",
ShopFlowers = GetShopFlowers()
});
}
public void SaveOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDoc(new PdfInfo
{
@ -97,6 +149,14 @@ namespace FlowerShopBusinessLogic.BusinessLogics
Orders = GetOrders(model)
});
}
}
public void SaveGroupedOrdersToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateDocWithGroupedOrders(new PdfInfo
{
FileName = model.FileName,
Title = "Заказы по датам",
GroupedOrders = GetGroupedByDateOrders()
});
}
}
}

View File

@ -0,0 +1,170 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace FlowerShopBusinessLogic.BusinessLogics
{
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?.ShopName, 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.ShopName, 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);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
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;
}
public bool MakeSupply(ShopSearchModel shopModel, IFlowerModel flower, int count)
{
if (shopModel == null)
{
throw new ArgumentNullException(nameof(shopModel));
}
if (flower == null)
{
throw new ArgumentNullException(nameof(flower));
}
if (count <= 0)
{
throw new ArgumentException("Количество цветов в поставке должно быть больше нуля", nameof(count));
}
_logger.LogInformation("MakeSupply(GetElement). ShopName: {ShopName}. Id: {Id}", shopModel.ShopName, shopModel.Id);
var shop = _shopStorage.GetElement(shopModel);
if (shop == null)
{
_logger.LogWarning("MakeSupply(GetElement). Element not found");
return false;
}
int CurrentRepairsNum = shop.ShopFlowers.Select(x => x.Value.Item2).Sum();
if (count > (shop.MaximumFlowers - CurrentRepairsNum))
{
_logger.LogWarning("Попытка добавить в магазин число элементов, большее RepairsMaxCount");
return false;
}
if (shop.ShopFlowers.ContainsKey(flower.Id))
{
var shopFlower = shop.ShopFlowers[flower.Id];
shopFlower.Item2 += count;
shop.ShopFlowers[flower.Id] = shopFlower;
_logger.LogInformation("MakeSupply. Added {count} '{flower}' to '{ShopName}' shop", count, flower.FlowerName, shop.ShopName);
}
else
{
shop.ShopFlowers.Add(flower.Id, (flower, count));
_logger.LogInformation("MakeSupply. Added {count} new '{flower}' to '{ShopName}' shop", count, flower.FlowerName, shop.ShopName);
}
if (_shopStorage.Update(new ShopBindingModel()
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpening = shop.DateOpening,
ShopFlowers = shop.ShopFlowers,
MaximumFlowers = shop.MaximumFlowers,
}) == null)
{
_logger.LogWarning("MakeSupply. Update 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.ShopName))
{
throw new ArgumentNullException("Нет названия магазина ", nameof(model.ShopName));
}
if (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentNullException("Нет адреса ", nameof(model.Address));
}
_logger.LogInformation("Shop. ShopName:{ShopName}. Address:{Address}. DateOpening:{DateOpening} Id: {Id}", model.ShopName, model.Address, model.DateOpening, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool MakeSale(IFlowerModel model, int count)
{
return _shopStorage.MakeSale(model, count);
}
}
}

View File

@ -70,10 +70,77 @@ namespace FlowerShopBusinessLogic.OfficePackage
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfo info);
public void CreateShopReport(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "C1"
});
uint rowIndex = 2;
foreach (var si in info.ShopFlowers)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = si.ShopName,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var (Flower, Count) in si.Flowers)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = Flower,
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 = si.TotalCount.ToString(),
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
}
SaveExcel(info);
}
protected abstract void CreateExcel(ExcelInfo info);
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
protected abstract void MergeCells(ExcelMergeParameters excelParams);
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -43,7 +43,34 @@ namespace FlowerShopBusinessLogic.OfficePackage
});
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
public void CreateDocWithGroupedOrders(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "5cm", "6cm", "5cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата", "Количество заказов", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var order in info.GroupedOrders)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { order.Date.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
SavePdf(info);
}
protected abstract void CreatePdf(PdfInfo info);
protected abstract void CreateParagraph(PdfParagraph paragraph);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(PdfRowParameters rowParameters);

View File

@ -36,9 +36,55 @@ namespace FlowerShopBusinessLogic.OfficePackage
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfo info);
public void CreateShopsTable(WordInfo info)
{
CreateWord(info);
CreateParagraph(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) },
TextProperties = new WordTextProperties
{
Size = "24",
JustificationType = WordJustificationType.Center
}
});
CreateTable(new List<string> { "3000", "3000", "3000" });
CreateRow(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { ("Название магазина", new WordTextProperties { Size = "24" }),
("Адрес", new WordTextProperties { Size = "24" }), ("Дата открытия", new WordTextProperties { Size = "24" }) },
TextProperties = new WordTextProperties
{
Size = "24",
Bold = true,
JustificationType = WordJustificationType.Center
}
});
foreach (var shop in info.Shops)
{
CreateRow(new WordParagraph
{
Texts = new List<(string, WordTextProperties)> { (shop.ShopName, new WordTextProperties { Size = "22" }),
(shop.Address, new WordTextProperties { Size = "22" }), (shop.DateOpening.ToString(), new WordTextProperties { Size = "22" })},
TextProperties = new WordTextProperties
{
Size = "22",
JustificationType = WordJustificationType.Center
}
});
}
SaveWord(info);
}
protected abstract void CreateWord(WordInfo info);
protected abstract void CreateParagraph(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
protected abstract void CreateTable(List<string> columns);
protected abstract void CreateRow(WordParagraph paragraph);
protected abstract void SaveWord(WordInfo info);
}
}

View File

@ -11,6 +11,6 @@ namespace FlowerShopBusinessLogic.OfficePackage.HelperModels
get;
set;
} = new();
}
public List<ReportShopFlowerViewModel> ShopFlowers { get; set; } = new();
}
}

View File

@ -10,6 +10,6 @@ namespace FlowerShopBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
}
public List<ReportOrdersByDateViewModel> GroupedOrders { get; set; } = new();
}
}

View File

@ -7,6 +7,6 @@ namespace FlowerShopBusinessLogic.OfficePackage.HelperModels
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<FlowerViewModel> Flowers { get; set; } = new();
}
public List<ShopViewModel> Shops { get; set; } = new();
}
}

View File

@ -10,7 +10,8 @@ namespace FlowerShopBusinessLogic.OfficePackage.Implements
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
private static JustificationValues GetJustificationValues(WordJustificationType type)
private Table? table;
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
@ -91,7 +92,66 @@ namespace FlowerShopBusinessLogic.OfficePackage.Implements
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
protected override void CreateTable(List<string> columns)
{
if (_docBody == null || columns == null)
{
return;
}
table = new();
TableProperties properties = new();
properties.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed });
properties.AppendChild(new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }
));
properties.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto });
table.AppendChild(properties);
TableGrid tableGrid = new();
foreach (var column in columns)
{
tableGrid.AppendChild(new GridColumn() { Width = column });
}
table.AppendChild(tableGrid);
_docBody.AppendChild(table);
}
protected override void CreateRow(WordParagraph paragraph)
{
if (_docBody == null || table == null || paragraph == null)
{
return;
}
TableRow tableRow = new();
foreach (var column in paragraph.Texts)
{
var tableParagraph = new Paragraph();
tableParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
var tableRun = new Run();
var runProperties = new RunProperties();
runProperties.AppendChild(new FontSize { Val = column.Item2.Size });
if (column.Item2.Bold)
{
runProperties.AppendChild(new Bold());
}
tableRun.AppendChild(runProperties);
tableRun.AppendChild(new Text { Text = column.Item1, Space = SpaceProcessingModeValues.Preserve });
tableParagraph.AppendChild(tableRun);
TableCell cell = new();
cell.AppendChild(tableParagraph);
tableRow.AppendChild(cell);
}
table.AppendChild(tableRow);
}
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{

View File

@ -0,0 +1,19 @@
using FlowerShopDataModels.Models;
namespace FlowerShopContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get;
set;
} = new();
public int MaximumFlowers { get; set; }
}
}

View File

@ -6,10 +6,14 @@ namespace FlowerShopContracts.BusinessLogicsContracts
public interface IReportLogic
{
List<ReportFlowerComponentViewModel> GetFlowerComponent();
List<ReportShopFlowerViewModel> GetShopFlowers();
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
List<ReportOrdersByDateViewModel> GetGroupedByDateOrders();
void SaveComponentsToWordFile(ReportBindingModel model);
void SaveShopsToWordFile(ReportBindingModel model);
void SaveFlowerComponentToExcelFile(ReportBindingModel model);
void SaveShopFlowerToExcelFile(ReportBindingModel model);
void SaveOrdersToPdfFile(ReportBindingModel model);
void SaveGroupedOrdersToPdfFile(ReportBindingModel model);
}
}

View File

@ -0,0 +1,18 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopContracts.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 MakeSupply(ShopSearchModel shopModel, IFlowerModel flower, int count);
bool MakeSale(IFlowerModel model, int count);
}
}

View File

@ -0,0 +1,8 @@
namespace FlowerShopContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? ShopName { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopContracts.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 MakeSale(IFlowerModel model, int count);
}
}

View File

@ -0,0 +1,9 @@
namespace FlowerShopContracts.ViewModels
{
public class ReportOrdersByDateViewModel
{
public DateTime Date { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace FlowerShopContracts.ViewModels
{
public class ReportShopFlowerViewModel
{
public string ShopName { get; set; } = string.Empty;
public int TotalCount { get; set; }
public List<(string Flower, int Count)> Flowers { get; set; } = new();
}
}

View File

@ -0,0 +1,8 @@
namespace FlowerShopContracts.ViewModels
{
public class ShopFlowerViewModel
{
public string FlowerName { get; set; }
public int Count { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using FlowerShopDataModels.Models;
using System.ComponentModel;
namespace FlowerShopContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get;
set;
} = new();
[DisplayName("Максимальное количество цветков")]
public int MaximumFlowers { get; set; }
public Dictionary<int, ShopFlowerViewModel> ViewFlowers { get; set; } = new();
}
}

View File

@ -0,0 +1,11 @@
namespace FlowerShopDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
Dictionary<int, (IFlowerModel, int)> ShopFlowers { get; }
DateTime DateOpening { get; }
int MaximumFlowers { get; }
}
}

View File

@ -9,16 +9,19 @@ namespace FlowerShopDatabaseImplement
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseNpgsql(@"Host=localhost;Database=FlowerShopDatabaseFull;Username=postgres;Password=postgres");
optionsBuilder.UseNpgsql(@"Host=localhost;Database=FlowerShopHardDatabaseTestFull;Username=postgres;Password=postgres");
}
base.OnConfiguring(optionsBuilder);
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDataTimeInfinityConversions", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Flower> Flowers { set; get; }
public virtual DbSet<FlowerComponent> FlowerComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopFlower> ShopFlowers { set; get; }
public virtual DbSet<Client> Clients { set; get; }
}
}

View File

@ -21,8 +21,4 @@
<ProjectReference Include="..\FlowerShopDataModels\FlowerShopDataModels.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,146 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDatabaseImplement.Models;
using FlowerShopDataModels.Models;
using Microsoft.EntityFrameworkCore;
namespace FlowerShopDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public List<ShopViewModel> GetFullList()
{
using var context = new FlowerShopDatabase();
return context.Shops
.Include(x => x.Flowers)
.ThenInclude(x => x.Flower)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new FlowerShopDatabase();
return context.Shops
.Include(x => x.Flowers)
.ThenInclude(x => x.Flower)
.Where(x => x.ShopName.Contains(model.ShopName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new FlowerShopDatabase();
return context.Shops
.Include(x => x.Flowers)
.ThenInclude(x => x.Flower)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new FlowerShopDatabase();
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 FlowerShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var shop = context.Shops.FirstOrDefault(rec => rec.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
context.SaveChanges();
shop.UpdateFlowers(context, model);
transaction.Commit();
return shop.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new FlowerShopDatabase();
var element = context.Shops
.Include(x => x.Flowers)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public bool MakeSale(IFlowerModel model, int count)
{
using var context = new FlowerShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
foreach (var shop in context.Shops.Include(x => x.Flowers).ThenInclude(x => x.Flower)
.Where(x => x.Flowers.Any(x => x.FlowerId == model.Id))
.ToList())
{
var flower = shop.ShopFlowers[model.Id];
int min = Math.Min(flower.Item2, count);
if (min == flower.Item2)
{
shop.ShopFlowers.Remove(model.Id);
}
else
{
shop.ShopFlowers[model.Id] = (flower.Item1, flower.Item2 - min);
}
shop.UpdateFlowers(context, new() { Id = shop.Id, ShopFlowers = shop.ShopFlowers });
count -= min;
if (count == 0)
{
context.SaveChanges();
transaction.Commit();
return true;
}
}
transaction.Rollback();
return false;
}
catch
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FlowerShopDatabaseImplement.Migrations
{
[DbContext(typeof(FlowerShopDatabase))]
[Migration("20240404125520_initcreate")]
partial class initcreate
[Migration("20240517110214_InitCreate")]
partial class InitCreate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
@ -146,11 +146,66 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FlowerId");
b.ToTable("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateOpening")
.HasColumnType("timestamp without time zone");
b.Property<int>("MaximumFlowers")
.HasColumnType("integer");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("FlowerId")
.HasColumnType("integer");
b.Property<int>("ShopId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("FlowerId");
b.HasIndex("ShopId");
b.ToTable("ShopFlowers");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.FlowerComponent", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Component", "Component")
@ -172,11 +227,45 @@ namespace FlowerShopDatabaseImplement.Migrations
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany("Orders")
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Flower");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany()
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Flowers")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Flower");
b.Navigation("Shop");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Component", b =>
@ -190,6 +279,11 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Flowers");
});
#pragma warning restore 612, 618
}
}

View File

@ -6,7 +6,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace FlowerShopDatabaseImplement.Migrations
{
public partial class initcreate : Migration
public partial class InitCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
@ -53,6 +53,22 @@ namespace FlowerShopDatabaseImplement.Migrations
table.PrimaryKey("PK_Flowers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ShopName = table.Column<string>(type: "text", nullable: false),
Address = table.Column<string>(type: "text", nullable: false),
DateOpening = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
MaximumFlowers = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "FlowerComponents",
columns: table => new
@ -97,6 +113,12 @@ namespace FlowerShopDatabaseImplement.Migrations
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_Flowers_FlowerId",
column: x => x.FlowerId,
@ -105,6 +127,33 @@ namespace FlowerShopDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopFlowers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ShopId = table.Column<int>(type: "integer", nullable: false),
FlowerId = table.Column<int>(type: "integer", nullable: false),
Count = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopFlowers", x => x.Id);
table.ForeignKey(
name: "FK_ShopFlowers_Flowers_FlowerId",
column: x => x.FlowerId,
principalTable: "Flowers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopFlowers_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_FlowerComponents_ComponentId",
table: "FlowerComponents",
@ -115,28 +164,49 @@ namespace FlowerShopDatabaseImplement.Migrations
table: "FlowerComponents",
column: "FlowerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_FlowerId",
table: "Orders",
column: "FlowerId");
migrationBuilder.CreateIndex(
name: "IX_ShopFlowers_FlowerId",
table: "ShopFlowers",
column: "FlowerId");
migrationBuilder.CreateIndex(
name: "IX_ShopFlowers_ShopId",
table: "ShopFlowers",
column: "ShopId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "FlowerComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopFlowers");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Flowers");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -144,11 +144,66 @@ namespace FlowerShopDatabaseImplement.Migrations
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FlowerId");
b.ToTable("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateOpening")
.HasColumnType("timestamp without time zone");
b.Property<int>("MaximumFlowers")
.HasColumnType("integer");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("FlowerId")
.HasColumnType("integer");
b.Property<int>("ShopId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("FlowerId");
b.HasIndex("ShopId");
b.ToTable("ShopFlowers");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.FlowerComponent", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Component", "Component")
@ -170,11 +225,45 @@ namespace FlowerShopDatabaseImplement.Migrations
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", null)
b.HasOne("FlowerShopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany("Orders")
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Flower");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.ShopFlower", b =>
{
b.HasOne("FlowerShopDatabaseImplement.Models.Flower", "Flower")
.WithMany()
.HasForeignKey("FlowerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FlowerShopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Flowers")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Flower");
b.Navigation("Shop");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Component", b =>
@ -188,6 +277,11 @@ namespace FlowerShopDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("FlowerShopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Flowers");
});
#pragma warning restore 612, 618
}
}

View File

@ -15,6 +15,8 @@ namespace FlowerShopDatabaseImplement.Models
public string Email { get; private set; } = string.Empty;
[Required]
public string Password { get; private set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{
if (model == null)

View File

@ -9,8 +9,12 @@ namespace FlowerShopDatabaseImplement.Models
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public int FlowerId { get; private set; }
public virtual Flower Flower { get; set; }
[Required]
public int ClientId { get; private set; }
public virtual Client Client { get; set; }
[Required]
public int Count { get; set; }
[Required]

View File

@ -0,0 +1,104 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace FlowerShopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; set; }
[Required]
public string ShopName { get; set; } = string.Empty;
[Required]
public string Address { get; set; } = string.Empty;
[Required]
public DateTime DateOpening { get; set; }
[Required]
public int MaximumFlowers { get; set; }
private Dictionary<int, (IFlowerModel, int)>? _shopFlowers = null;
[NotMapped]
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get
{
if (_shopFlowers == null)
{
_shopFlowers = Flowers
.ToDictionary(x => x.FlowerId, x => (x.Flower as IFlowerModel, x.Count));
}
return _shopFlowers;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopFlower> Flowers { get; set; } = new();
public static Shop Create(FlowerShopDatabase context, ShopBindingModel model)
{
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
MaximumFlowers = model.MaximumFlowers,
Flowers = model.ShopFlowers.Select(x => new ShopFlower
{
Flower = context.Flowers.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel model)
{
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaximumFlowers = model.MaximumFlowers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaximumFlowers = MaximumFlowers,
ShopFlowers = ShopFlowers
};
public void UpdateFlowers(FlowerShopDatabase context, ShopBindingModel model)
{
var shopFlowers = context.ShopFlowers.Where(rec => rec.ShopId == model.Id).ToList();
if (shopFlowers != null && shopFlowers.Count > 0)
{
context.ShopFlowers.RemoveRange(shopFlowers.Where(rec => !model.ShopFlowers.ContainsKey(rec.FlowerId)));
context.SaveChanges();
foreach (var updateFlower in shopFlowers)
{
if (model.ShopFlowers.ContainsKey(updateFlower.FlowerId))
{
updateFlower.Count = model.ShopFlowers[updateFlower.FlowerId].Item2;
model.ShopFlowers.Remove(updateFlower.FlowerId);
}
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var ic in model.ShopFlowers)
{
context.ShopFlowers.Add(new ShopFlower
{
Shop = shop,
Flower = context.Flowers.First(x => x.Id == ic.Key),
Count = ic.Value.Item2
});
context.SaveChanges();
}
_shopFlowers = null;
}
}
}

View File

@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace FlowerShopDatabaseImplement.Models
{
public class ShopFlower
{
public int Id { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int FlowerId { get; set; }
[Required]
public int Count { get; set; }
public virtual Flower Flower { get; set; } = new();
public virtual Shop Shop { get; set; } = new();
}
}

View File

@ -10,10 +10,12 @@ namespace FlowerShopFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string FlowerFileName = "Flower.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Flower> Flowers { get; private set; }
public List<Client> Clients { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -26,12 +28,14 @@ namespace FlowerShopFileImplement
public void SaveFlowers() => SaveData(Flowers, FlowerFileName, "Flowers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Flowers = LoadData(FlowerFileName, "Flower", x => Flower.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
@ -48,6 +52,5 @@ namespace FlowerShopFileImplement
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}
}

View File

@ -0,0 +1,132 @@

using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using FlowerShopFileImplement.Models;
namespace FlowerShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops
.Where(x => x.ShopName.Contains(model.ShopName))
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
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 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;
}
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 bool MakeSale(IFlowerModel model, int count)
{
var flower = source.Flowers.FirstOrDefault(x => x.Id == model.Id);
int countInShops = source.Shops.SelectMany(x => x.ShopFlowers).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0);
if (flower == null || countInShops < count)
{
return false;
}
foreach (var shop in source.Shops)
{
var shopFlowers = shop.ShopFlowers.Where(x => x.Key == model.Id);
if (shopFlowers.Any())
{
var shopFlower = shopFlowers.First();
int min = Math.Min(shopFlower.Value.Item2, count);
if (min == shopFlower.Value.Item2)
{
shop.ShopFlowers.Remove(shopFlower.Key);
}
else
{
shop.ShopFlowers[shopFlower.Key] = (shopFlower.Value.Item1, shopFlower.Value.Item2 - min);
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpening = shop.DateOpening,
ShopFlowers = shop.ShopFlowers,
MaximumFlowers = shop.MaximumFlowers
});
count -= min;
if (count <= 0)
{
break;
}
}
}
source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,88 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, int> Flowers { get; private set; } = new();
private Dictionary<int, (IFlowerModel, int)> _shopFlowers = null;
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get
{
if (_shopFlowers == null)
{
var source = DataFileSingleton.GetInstance();
_shopFlowers = Flowers.ToDictionary(x => x.Key,
y => ((source.Flowers.FirstOrDefault(z => z.Id == y.Key) as IFlowerModel)!, y.Value));
}
return _shopFlowers;
}
}
public int MaximumFlowers { get; private set; }
public static Shop? Create(ShopBindingModel model)
{
if (model == null) return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
Flowers = model.ShopFlowers.ToDictionary(x => x.Key, x => x.Value.Item2),
MaximumFlowers = model.MaximumFlowers,
};
}
public static Shop? Create(XElement element)
{
if (element == null) return null;
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaximumFlowers = Convert.ToInt32(element.Element("MaximumFlowers")!.Value),
Flowers = element.Element("ShopFlowers")!.Elements("ShopFlower")
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null) return;
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaximumFlowers = model.MaximumFlowers;
Flowers = model.ShopFlowers.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopFlowers = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaximumFlowers = MaximumFlowers,
ShopFlowers = ShopFlowers,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("MaximumFlowers", MaximumFlowers.ToString()),
new XElement("ShopFlowers",
Flowers.Select(x => new XElement("ShopFlower",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -9,12 +9,14 @@ namespace FlowerShopListImplement
public List<Order> Orders { get; set; }
public List<Flower> Flowers { get; set; }
public List<Client> Clients { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Flowers = new List<Flower>();
Clients = new List<Client>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,114 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.StoragesContracts;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using FlowerShopListImplement.Models;
namespace FlowerShopListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.ShopName) &&
shop.ShopName == model.ShopName) ||
(model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
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;
}
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 MakeSale(IFlowerModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,56 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
namespace FlowerShopListImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, (IFlowerModel, int)> ShopFlowers { get; private set; } = new();
public int MaximumFlowers { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
ShopFlowers = model.ShopFlowers,
MaximumFlowers = model.MaximumFlowers,
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
ShopFlowers = model.ShopFlowers;
MaximumFlowers = model.MaximumFlowers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopFlowers = ShopFlowers,
MaximumFlowers = MaximumFlowers,
};
}
}

View File

@ -0,0 +1,117 @@
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.BusinessLogicsContracts;
using FlowerShopContracts.SearchModels;
using FlowerShopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace FlowerShopRestApi.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>? GetShopList()
{
try
{
return _logic.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpGet]
public ShopViewModel? GetShop(int shopId)
{
try
{
var element = _logic.ReadElement(new ShopSearchModel { Id = shopId });
var newDict = new Dictionary<int, ShopFlowerViewModel>();
if (element != null)
{
foreach (var item in element.ShopFlowers)
{
newDict.Add(item.Key, new ShopFlowerViewModel
{
FlowerName = item.Value.Item1.FlowerName,
Count = item.Value.Item2,
});
}
element.ViewFlowers = newDict;
}
return element;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка магазинов");
throw;
}
}
[HttpPost]
public void CreateShop(ShopBindingModel model)
{
try
{
_logic.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания магазина");
throw;
}
}
[HttpPost]
public void UpdateShop(ShopBindingModel model)
{
try
{
_logic.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления магазина");
throw;
}
}
[HttpPost]
public void DeleteShop(ShopBindingModel model)
{
try
{
_logic.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления магазина");
throw;
}
}
[HttpPost]
public void MakeSupply(Tuple<ShopSearchModel, FlowerViewModel, int> shopFlowers)
{
try
{
if (!_logic.MakeSupply(shopFlowers.Item1, shopFlowers.Item2, shopFlowers.Item3))
{
throw new Exception("Попытка добавить в магазин число элементов, большее чем максимум");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления цветов в магазин");
throw;
}
}
}
}

View File

@ -13,10 +13,12 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IFlowerStorage, FlowerStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IFlowerLogic, FlowerLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddControllers();

View File

@ -0,0 +1,58 @@
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace FlowerShopShopApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static string Password { get; private set; } = string.Empty;
Review

private

private
public static bool AuthenticationDone { get; private set; }
public static bool Authentication(string password)
{
if (password == Password)
{
AuthenticationDone = true;
}
return AuthenticationDone;
}
public static void Connect(IConfiguration configuration)
{
Password = configuration["Password"];
_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,175 @@
using Microsoft.AspNetCore.Mvc;
using FlowerShopContracts.ViewModels;
using FlowerShopContracts.BindingModels;
using FlowerShopDataModels.Models;
using FlowerShopShopApp.Models;
using System.Diagnostics;
using FlowerShopContracts.SearchModels;
namespace FlowerShopShopApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (!APIClient.AuthenticationDone)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<ShopViewModel>>($"api/shop/getshoplist"));
}
[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("Введите пароль");
}
if (!APIClient.Authentication(password))
{
throw new Exception("Неверный пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Create()
{
if (!APIClient.AuthenticationDone)
{
return Redirect("~/Home/Enter");
}
return View("Shop");
}
[HttpPost]
public void Create(int Id, string shopName, string address, DateTime dateOpening, int maximumFlowers)
{
if (!APIClient.AuthenticationDone)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(shopName))
{
throw new Exception("Название магазина не указано");
}
if (string.IsNullOrEmpty(address))
{
throw new Exception("Адрес магазина не указан");
}
if (maximumFlowers <= 0)
{
throw new Exception("Вместимость магазина должна быть больше нуля");
}
APIClient.PostRequest("api/shop/createshop", new ShopBindingModel
{
Id = Id,
ShopName = shopName,
Address = address,
DateOpening = dateOpening,
MaximumFlowers = maximumFlowers
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Update(int Id)
{
if (!APIClient.AuthenticationDone)
{
return Redirect("~/Home/Enter");
}
return View("Shop", APIClient.GetRequest<ShopViewModel>($"api/shop/getshop?shopId={Id}"));
}
[HttpPost]
public void Update(int Id, string shopName, string address, DateTime dateOpening, int maximumFlowers)
{
if (!APIClient.AuthenticationDone)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(shopName))
{
throw new Exception("Название магазина не указано");
}
if (string.IsNullOrEmpty(address))
{
throw new Exception("Адрес магазина не указан");
}
if (maximumFlowers <= 0)
{
throw new Exception("Вместимость магазина должна быть больше нуля");
}
var shopFlowers = APIClient.GetRequest<Dictionary<int, (IFlowerModel, int)>>($"api/shop/getlistflower?shopId={Id}");
APIClient.PostRequest("api/shop/updateshop", new ShopBindingModel
{
Id = Id,
ShopName = shopName,
Address = address,
DateOpening = dateOpening.Date,
MaximumFlowers = maximumFlowers,
ShopFlowers = shopFlowers
});
Response.Redirect("Index");
}
[HttpPost]
public void Delete(int Id)
{
if (!APIClient.AuthenticationDone)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/shop/deleteshop", new ShopBindingModel
{
Id = Id,
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Supply()
{
ViewBag.Shops = APIClient.GetRequest<List<ShopViewModel>>("api/shop/getshoplist");
ViewBag.Flowers = APIClient.GetRequest<List<FlowerViewModel>>("api/main/getflowerlist");
return View();
}
[HttpPost]
public void Supply(int shop, int flower, int count)
{
if (!APIClient.AuthenticationDone)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество должно быть больше 0");
}
APIClient.PostRequest("api/shop/makesupply", Tuple.Create(
new ShopSearchModel() { Id = shop },
new FlowerViewModel() { Id = flower },
count
));
Response.Redirect("Index");
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,30 @@
using FlowerShopShopApp;
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:43516",
"sslPort": 44361
}
},
"profiles": {
"FlowerShopShopApp": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7023;http://localhost:5054",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,15 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в систему</h2>
</div>
<form method="post">
<div class="mb-3">
<label class="form-label">Пароль</label>
<input class="form-control" type="password" name="password">
</div>
<input type="submit" value="Вход" class="btn btn-primary" />
</form>

View File

@ -0,0 +1,67 @@
@using FlowerShopContracts.ViewModels
@model List<ShopViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Магазины</h1>
</div>
<div class="text-center ">
<p>
<a asp-action="Create">Создать магазин</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Название
</th>
<th>
Адрес
</th>
<th>
Дата открытия
</th>
<th>
Максимальная вместимость
</th>
<th>
</th>
</tr>
</thead>
<tbody>
@foreach (var Item in Model)
{
<tr>
<td>
@Html.DisplayFor(ModelItem => Item.Id)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.ShopName)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.Address)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.DateOpening)
</td>
<td>
@Html.DisplayFor(ModelItem => Item.MaximumFlowers)
</td>
<td>
<a class="btn btn-primary" asp-action="Update" asp-route-Id="@(Item.Id)" role="button">Изменить</a>
</td>
</tr>
}
</tbody>
</table>
</div>

View File

@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace FlowerShopShopApp.Views.Home
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}

View File

@ -0,0 +1,75 @@
@using FlowerShopDataModels.Models
@using FlowerShopContracts.ViewModels
@model ShopViewModel
@{
ViewData["Title"] = "Shop";
}
<div class="text-center">
@{
if (Model == null)
{
<h2 class="display-4">Создание магазина</h2>
}
else
{
<h2 class="display-4">Изменение магазина</h2>
}
}
</div>
<form method="post">
<div class="mb-3">
<label class="form-label">Название</label>
<input type="text" class="form-control" name="shopname" id="shopname" value="@(Model==null ? "" : Model?.ShopName)" />
</div>
<div class="mb-3">
<label class="form-label">Адрес</label>
<input type="text" class="form-control" name="address" id="address" value="@(Model==null ? "" : Model?.Address)" />
</div>
<div class="mb-3">
<label for="startDate">Дата открытия</label>
<input class="form-control" type="date" name="dateopening" id="dateopening" value="@(Model==null ? "" : Model?.DateOpening.ToString("yyyy-MM-dd"))" />
</div>
<div class="mb-3">
<label class="form-label">Вместимость</label>
<input type="number" min="0" step="1" pattern="[0-9]" class="form-control" name="maximumflowers" id="maximumflowers" value="@(Model==null ? "" : Model?.MaximumFlowers)" />
</div>
<div class="mb-3 ">
<input class="btn btn-primary" type="submit" value="Сохранить">
@{
if (Model != null)
{
<input class="btn btn-danger" asp-action="Delete" type="submit" value="Удалить" asp-route-Id="@(Model==null ? 0 : Model.Id.ToString())">
}
}
</div>
</form>
@{
if (Model != null)
{
<div>
<h6>Содержимое магазина</h6>
</div>
<table class="table">
<thead>
<tr>
<th>Название</th>
<th>Количество</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ViewFlowers)
{
<tr>
<td>@Html.DisplayFor(shopItem => item.Value.FlowerName)</td>
<td>@Html.DisplayFor(shopItem => item.Value.Count)</td>
</tr>
}
</tbody>
</table>
}
}

View File

@ -0,0 +1,22 @@
@{
ViewData["Title"] = "Supply";
}
<div class="text-center">
<h2 class="display-4">Пополнение магазина</h2>
</div>
<form method="post">
<div class="mb-3">
<label class="form-label">Магазин</label>
<select class="form-select form-select-lg" id="shop" name="shop" asp-items="@(new SelectList(@ViewBag.Shops,"Id", "ShopName"))"></select>
</div>
<div class="mb-3">
<label class="form-label">Цветок</label>
<select class="form-select form-select-lg" id="flower" name="flower" asp-items="@(new SelectList(@ViewBag.Flowers,"Id", "FlowerName"))"></select>
</div>
<div class="mb-3">
<label class="form-label">Количество</label>
<input type="number" min="0" step="1" pattern="[0-9]" class="form-control" name="count" id="count">
</div>
<input class="btn btn-success" type="submit" value="Создать поставку">
<a class="btn btn-primary" href="./Index" role="button">Отмена</a>
</form>

View File

@ -0,0 +1,26 @@
@using FlowerShopShopApp.Models
@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,28 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Diagnostics;
namespace FlowerShopShopApp.Views.Shared
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
private readonly ILogger<ErrorModel> _logger;
public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}

View File

@ -0,0 +1,49 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - FlowerShopShopApp</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="~/FlowerShopShopApp.styles.css" asp-append-version="true" />
</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">FlowerShopShopApp</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-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 justify-content-between">
<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>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Supply">Пополнение</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; 2024 - FlowerShopShopApp - <a asp-area="" asp-controller="Home" asp-action="Index">Главная</a>
</div>
</footer>
<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>
@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 FlowerShopShopApp
@namespace FlowerShopShopApp.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

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

View File

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

View File

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

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.

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 it is too large Load Diff

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 it is too large Load Diff

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 */

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